book.tex 834 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. \makeatletter
  35. \newcommand{\captionabove}[2][]{%
  36. \vskip-\abovecaptionskip
  37. \vskip+\belowcaptionskip
  38. \ifx\@nnil#1\@nnil
  39. \caption{#2}%
  40. \else
  41. \caption[#1]{#2}%
  42. \fi
  43. \vskip+\abovecaptionskip
  44. \vskip-\belowcaptionskip
  45. }
  46. %% For multiple indices:
  47. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  48. \makeindex{subject}
  49. %\makeindex{authors}
  50. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  51. \if\edition\racketEd
  52. \lstset{%
  53. language=Lisp,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  56. deletekeywords={read,mapping,vector},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. \if\edition\pythonEd
  64. \lstset{%
  65. language=Python,
  66. basicstyle=\ttfamily\small,
  67. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  68. deletekeywords={},
  69. escapechar=|,
  70. columns=flexible,
  71. %moredelim=[is][\color{red}]{~}{~},
  72. showstringspaces=false
  73. }
  74. \fi
  75. %%% Any shortcut own defined macros place here
  76. %% sample of author macro:
  77. \input{defs}
  78. \newtheorem{exercise}[theorem]{Exercise}
  79. \numberwithin{theorem}{chapter}
  80. \numberwithin{definition}{chapter}
  81. \numberwithin{equation}{chapter}
  82. % Adjusted settings
  83. \setlength{\columnsep}{4pt}
  84. %% \begingroup
  85. %% \setlength{\intextsep}{0pt}%
  86. %% \setlength{\columnsep}{0pt}%
  87. %% \begin{wrapfigure}{r}{0.5\textwidth}
  88. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  89. %% \caption{Basic layout}
  90. %% \end{wrapfigure}
  91. %% \lipsum[1]
  92. %% \endgroup
  93. \newbox\oiintbox
  94. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  95. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  96. \def\oiint{\copy\oiintbox}
  97. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  98. %\usepackage{showframe}
  99. \def\ShowFrameLinethickness{0.125pt}
  100. \addbibresource{book.bib}
  101. \if\edition\pythonEd
  102. \addbibresource{python.bib}
  103. \fi
  104. \begin{document}
  105. \frontmatter
  106. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  107. \HalfTitle{Essentials of Compilation}
  108. \halftitlepage
  109. \clearemptydoublepage
  110. \Title{Essentials of Compilation}
  111. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  112. %\edition{First Edition}
  113. \BookAuthor{Jeremy G. Siek}
  114. \imprint{The MIT Press\\
  115. Cambridge, Massachusetts\\
  116. London, England}
  117. \begin{copyrightpage}
  118. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  119. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  120. Subject to such license, all rights are reserved. \\[2ex]
  121. \includegraphics{CCBY-logo}
  122. The MIT Press would like to thank the anonymous peer reviewers who
  123. provided comments on drafts of this book. The generous work of
  124. academic experts is essential for establishing the authority and
  125. quality of our publications. We acknowledge with gratitude the
  126. contributions of these otherwise uncredited readers.
  127. This book was set in Times LT Std Roman by the author. Printed and
  128. bound in the United States of America.
  129. {\if\edition\racketEd
  130. Library of Congress Cataloging-in-Publication Data\\
  131. \ \\
  132. Names: Siek, Jeremy, author. \\
  133. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  134. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  135. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  136. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  137. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  138. LC record available at https://lccn.loc.gov/2022015399\\
  139. LC ebook record available at https://lccn.loc.gov/2022015400\\
  140. \ \\
  141. \fi}
  142. %
  143. {\if\edition\pythonEd
  144. Library of Congress Cataloging-in-Publication Data\\
  145. \ \\
  146. Names: Siek, Jeremy, author. \\
  147. Title: Essentials of compilation : an incremental approach in Python / Jeremy G. Siek. \\
  148. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes
  149. bibliographical references and index. \\
  150. Identifiers: LCCN 2022043053 (print) | LCCN 2022043054 (ebook) | ISBN
  151. 9780262048248 | ISBN 9780262375542 (epub) | ISBN 9780262375559 (pdf) \\
  152. Subjects: LCSH: Compilers (Computer programs) | Python (Computer program
  153. language) | Programming languages (Electronic computers) | Computer
  154. programming. \\
  155. Classification: LCC QA76.76.C65 S54 2023 (print) | LCC QA76.76.C65
  156. (ebook) | DDC 005.4/53--dc23/eng/20221117 \\
  157. LC record available at https://lccn.loc.gov/2022043053\\
  158. LC ebook record available at https://lccn.loc.gov/2022043054 \\
  159. \ \\
  160. \fi}
  161. 10 9 8 7 6 5 4 3 2 1
  162. %% Jeremy G. Siek. Available for free viewing
  163. %% or personal downloading under the
  164. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  165. %% license.
  166. %% Copyright in this monograph has been licensed exclusively to The MIT
  167. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  168. %% version to the public in 2022. All inquiries regarding rights should
  169. %% be addressed to The MIT Press, Rights and Permissions Department.
  170. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  171. %% All rights reserved. No part of this book may be reproduced in any
  172. %% form by any electronic or mechanical means (including photocopying,
  173. %% recording, or information storage and retrieval) without permission in
  174. %% writing from the publisher.
  175. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  176. %% United States of America.
  177. %% Library of Congress Cataloging-in-Publication Data is available.
  178. %% ISBN:
  179. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  180. \end{copyrightpage}
  181. \dedication{This book is dedicated to Katie, my partner in everything,
  182. my children, who grew up during the writing of this book, and the
  183. programming language students at Indiana University, whose
  184. thoughtful questions made this a better book.}
  185. %% \begin{epigraphpage}
  186. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  187. %% \textit{Book Name if any}}
  188. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  189. %% \end{epigraphpage}
  190. \tableofcontents
  191. %\listoffigures
  192. %\listoftables
  193. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  194. \chapter*{Preface}
  195. \addcontentsline{toc}{fmbm}{Preface}
  196. There is a magical moment when a programmer presses the \emph{run}
  197. button and the software begins to execute. Somehow a program written
  198. in a high-level language is running on a computer that is capable only
  199. of shuffling bits. Here we reveal the wizardry that makes that moment
  200. possible. Beginning with the groundbreaking work of Backus and
  201. colleagues in the 1950s, computer scientists developed techniques for
  202. constructing programs called \emph{compilers} that automatically
  203. translate high-level programs into machine code.
  204. We take you on a journey through constructing your own compiler for a
  205. small but powerful language. Along the way we explain the essential
  206. concepts, algorithms, and data structures that underlie compilers. We
  207. develop your understanding of how programs are mapped onto computer
  208. hardware, which is helpful in reasoning about properties at the
  209. junction of hardware and software, such as execution time, software
  210. errors, and security vulnerabilities. For those interested in
  211. pursuing compiler construction as a career, our goal is to provide a
  212. stepping-stone to advanced topics such as just-in-time compilation,
  213. program analysis, and program optimization. For those interested in
  214. designing and implementing programming languages, we connect language
  215. design choices to their impact on the compiler and the generated code.
  216. A compiler is typically organized as a sequence of stages that
  217. progressively translate a program to the code that runs on
  218. hardware. We take this approach to the extreme by partitioning our
  219. compiler into a large number of \emph{nanopasses}, each of which
  220. performs a single task. This enables the testing of each pass in
  221. isolation and focuses our attention, making the compiler far easier to
  222. understand.
  223. The most familiar approach to describing compilers is to dedicate each
  224. chapter to one pass. The problem with that approach is that it
  225. obfuscates how language features motivate design choices in a
  226. compiler. We instead take an \emph{incremental} approach in which we
  227. build a complete compiler in each chapter, starting with a small input
  228. language that includes only arithmetic and variables. We add new
  229. language features in subsequent chapters, extending the compiler as
  230. necessary.
  231. Our choice of language features is designed to elicit fundamental
  232. concepts and algorithms used in compilers.
  233. \begin{itemize}
  234. \item We begin with integer arithmetic and local variables in
  235. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  236. the fundamental tools of compiler construction: \emph{abstract
  237. syntax trees} and \emph{recursive functions}.
  238. {\if\edition\pythonEd\pythonColor
  239. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  240. parser framework to create a parser for the language of integer
  241. arithmetic and local variables. We learn about the parsing
  242. algorithms inside Lark, including Earley and LALR(1).
  243. %
  244. \fi}
  245. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  246. \emph{graph coloring} to assign variables to machine registers.
  247. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  248. motivates an elegant recursive algorithm for translating them into
  249. conditional \code{goto} statements.
  250. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  251. variables}. This elicits the need for \emph{dataflow
  252. analysis} in the register allocator.
  253. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  254. \emph{garbage collection}.
  255. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  256. without lexical scoping, similar to functions in the C programming
  257. language~\citep{Kernighan:1988nx}. The reader learns about the
  258. procedure call stack and \emph{calling conventions} and how they interact
  259. with register allocation and garbage collection. The chapter also
  260. describes how to generate efficient tail calls.
  261. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  262. scoping, that is, \emph{lambda} expressions. The reader learns about
  263. \emph{closure conversion}, in which lambdas are translated into a
  264. combination of functions and tuples.
  265. % Chapter about classes and objects?
  266. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  267. point the input languages are statically typed. The reader extends
  268. the statically typed language with an \code{Any} type that serves
  269. as a target for compiling the dynamically typed language.
  270. %% {\if\edition\pythonEd\pythonColor
  271. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  272. %% \emph{classes}.
  273. %% \fi}
  274. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  275. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  276. in which different regions of a program may be static or dynamically
  277. typed. The reader implements runtime support for \emph{proxies} that
  278. allow values to safely move between regions.
  279. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  280. leveraging the \code{Any} type and type casts developed in chapters
  281. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  282. \end{itemize}
  283. There are many language features that we do not include. Our choices
  284. balance the incidental complexity of a feature versus the fundamental
  285. concepts that it exposes. For example, we include tuples and not
  286. records because although they both elicit the study of heap allocation and
  287. garbage collection, records come with more incidental complexity.
  288. Since 2009, drafts of this book have served as the textbook for
  289. sixteen-week compiler courses for upper-level undergraduates and
  290. first-year graduate students at the University of Colorado and Indiana
  291. University.
  292. %
  293. Students come into the course having learned the basics of
  294. programming, data structures and algorithms, and discrete
  295. mathematics.
  296. %
  297. At the beginning of the course, students form groups of two to four
  298. people. The groups complete approximately one chapter every two
  299. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  300. according to the students interests while respecting the dependencies
  301. between chapters shown in
  302. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  303. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  304. implementation of efficient tail calls.
  305. %
  306. The last two weeks of the course involve a final project in which
  307. students design and implement a compiler extension of their choosing.
  308. The last few chapters can be used in support of these projects. Many
  309. chapters include a challenge problem that we assign to the graduate
  310. students.
  311. For compiler courses at universities on the quarter system
  312. (about ten weeks in length), we recommend completing the course
  313. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  314. some scaffolding code to the students for each compiler pass.
  315. %
  316. The course can be adapted to emphasize functional languages by
  317. skipping chapter~\ref{ch:Lwhile} (loops) and including
  318. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  319. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  320. %
  321. %% \python{A course that emphasizes object-oriented languages would
  322. %% include Chapter~\ref{ch:Lobject}.}
  323. This book has been used in compiler courses at California Polytechnic
  324. State University, Portland State University, Rose–Hulman Institute of
  325. Technology, University of Freiburg, University of Massachusetts
  326. Lowell, and the University of Vermont.
  327. \begin{figure}[tp]
  328. \begin{tcolorbox}[colback=white]
  329. {\if\edition\racketEd
  330. \begin{tikzpicture}[baseline=(current bounding box.center)]
  331. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  332. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  333. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  334. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  335. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  336. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  337. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  338. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  339. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  340. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  341. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  342. \path[->] (C1) edge [above] node {} (C2);
  343. \path[->] (C2) edge [above] node {} (C3);
  344. \path[->] (C3) edge [above] node {} (C4);
  345. \path[->] (C4) edge [above] node {} (C5);
  346. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  347. \path[->] (C5) edge [above] node {} (C7);
  348. \path[->] (C6) edge [above] node {} (C7);
  349. \path[->] (C4) edge [above] node {} (C8);
  350. \path[->] (C4) edge [above] node {} (C9);
  351. \path[->] (C7) edge [above] node {} (C10);
  352. \path[->] (C8) edge [above] node {} (C10);
  353. \path[->] (C10) edge [above] node {} (C11);
  354. \end{tikzpicture}
  355. \fi}
  356. {\if\edition\pythonEd\pythonColor
  357. \begin{tikzpicture}[baseline=(current bounding box.center)]
  358. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  359. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  360. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  361. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  362. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  363. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  364. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  365. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  366. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  367. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  368. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  369. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  370. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  371. \path[->] (Prelim) edge [above] node {} (Var);
  372. \path[->] (Var) edge [above] node {} (Reg);
  373. \path[->] (Var) edge [above] node {} (Parse);
  374. \path[->] (Reg) edge [above] node {} (Cond);
  375. \path[->] (Cond) edge [above] node {} (Tuple);
  376. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  377. \path[->] (Cond) edge [above] node {} (Fun);
  378. \path[->] (Tuple) edge [above] node {} (Lam);
  379. \path[->] (Fun) edge [above] node {} (Lam);
  380. \path[->] (Cond) edge [above] node {} (Dyn);
  381. \path[->] (Cond) edge [above] node {} (Loop);
  382. \path[->] (Lam) edge [above] node {} (Gradual);
  383. \path[->] (Dyn) edge [above] node {} (Gradual);
  384. % \path[->] (Dyn) edge [above] node {} (CO);
  385. \path[->] (Gradual) edge [above] node {} (Generic);
  386. \end{tikzpicture}
  387. \fi}
  388. \end{tcolorbox}
  389. \caption{Diagram of chapter dependencies.}
  390. \label{fig:chapter-dependences}
  391. \end{figure}
  392. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  393. the implementation of the compiler and for the input language, so the
  394. reader should be proficient with Racket or Scheme. There are many
  395. excellent resources for learning Scheme and
  396. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  397. %
  398. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  399. both for the implementation of the compiler and for the input language, so the
  400. reader should be proficient with Python. There are many
  401. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  402. %
  403. The support code for this book is in the GitHub repository at
  404. the following location:
  405. \begin{center}\small\texttt
  406. https://github.com/IUCompilerCourse/
  407. \end{center}
  408. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  409. is helpful but not necessary for the reader to have taken a computer
  410. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  411. assembly language that are needed in the compiler.
  412. %
  413. We follow the System V calling
  414. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  415. that we generate works with the runtime system (written in C) when it
  416. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  417. operating systems on Intel hardware.
  418. %
  419. On the Windows operating system, \code{gcc} uses the Microsoft x64
  420. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  421. assembly code that we generate does \emph{not} work with the runtime
  422. system on Windows. One workaround is to use a virtual machine with
  423. Linux as the guest operating system.
  424. \section*{Acknowledgments}
  425. The tradition of compiler construction at Indiana University goes back
  426. to research and courses on programming languages by Daniel Friedman in
  427. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  428. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  429. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  430. the compiler course and continued the development of Chez Scheme.
  431. %
  432. The compiler course evolved to incorporate novel pedagogical ideas
  433. while also including elements of real-world compilers. One of
  434. Friedman's ideas was to split the compiler into many small
  435. passes. Another idea, called ``the game,'' was to test the code
  436. generated by each pass using interpreters.
  437. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  438. developed infrastructure to support this approach and evolved the
  439. course to use even smaller
  440. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  441. design decisions in this book are inspired by the assignment
  442. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  443. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  444. organization of the course made it difficult for students to
  445. understand the rationale for the compiler design. Ghuloum proposed the
  446. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  447. based.
  448. I thank the many students who served as teaching assistants for the
  449. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  450. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  451. garbage collector and x86 interpreter, Michael Vollmer for work on
  452. efficient tail calls, and Michael Vitousek for help with the first
  453. offering of the incremental compiler course at IU.
  454. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  455. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  456. Michael Wollowski for teaching courses based on drafts of this book
  457. and for their feedback. I thank the National Science Foundation for
  458. the grants that helped to support this work: Grant Numbers 1518844,
  459. 1763922, and 1814460.
  460. I thank Ronald Garcia for helping me survive Dybvig's compiler
  461. course in the early 2000s and especially for finding the bug that
  462. sent our garbage collector on a wild goose chase!
  463. \mbox{}\\
  464. \noindent Jeremy G. Siek \\
  465. Bloomington, Indiana
  466. \mainmatter
  467. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  468. \chapter{Preliminaries}
  469. \label{ch:trees-recur}
  470. \setcounter{footnote}{0}
  471. In this chapter we introduce the basic tools needed to implement a
  472. compiler. Programs are typically input by a programmer as text, that
  473. is, a sequence of characters. The program-as-text representation is
  474. called \emph{concrete syntax}. We use concrete syntax to concisely
  475. write down and talk about programs. Inside the compiler, we use
  476. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  477. that efficiently supports the operations that the compiler needs to
  478. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  479. syntax}\index{subject}{abstract syntax
  480. tree}\index{subject}{AST}\index{subject}{program}
  481. The process of translating concrete syntax to abstract syntax is
  482. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  483. chapter~\ref{ch:parsing}}.
  484. \racket{This book does not cover the theory and implementation of parsing.
  485. We refer the readers interested in parsing to the thorough treatment
  486. of parsing by \citet{Aho:2006wb}. }%
  487. %
  488. \racket{A parser is provided in the support code for translating from
  489. concrete to abstract syntax.}%
  490. %
  491. \python{For now we use the \code{parse} function in Python's
  492. \code{ast} module to translate from concrete to abstract syntax.}
  493. ASTs can be represented inside the compiler in many different ways,
  494. depending on the programming language used to write the compiler.
  495. %
  496. \racket{We use Racket's
  497. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  498. feature to represent ASTs (section~\ref{sec:ast}).}
  499. %
  500. \python{We use Python classes and objects to represent ASTs, especially the
  501. classes defined in the standard \code{ast} module for the Python
  502. source language.}
  503. %
  504. We use grammars to define the abstract syntax of programming languages
  505. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  506. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  507. recursive functions to construct and deconstruct ASTs
  508. (section~\ref{sec:recursion}). This chapter provides a brief
  509. introduction to these components.
  510. \racket{\index{subject}{struct}}
  511. \python{\index{subject}{class}\index{subject}{object}}
  512. \section{Abstract Syntax Trees}
  513. \label{sec:ast}
  514. Compilers use abstract syntax trees to represent programs because they
  515. often need to ask questions such as, for a given part of a program,
  516. what kind of language feature is it? What are its subparts? Consider
  517. the program on the left and the diagram of its AST on the
  518. right~\eqref{eq:arith-prog}. This program is an addition operation
  519. that has two subparts, a \racket{read}\python{input} operation and a
  520. negation. The negation has another subpart, the integer constant
  521. \code{8}. By using a tree to represent the program, we can easily
  522. follow the links to go from one part of a program to its subparts.
  523. \begin{center}
  524. \begin{minipage}{0.4\textwidth}
  525. {\if\edition\racketEd
  526. \begin{lstlisting}
  527. (+ (read) (- 8))
  528. \end{lstlisting}
  529. \fi}
  530. {\if\edition\pythonEd\pythonColor
  531. \begin{lstlisting}
  532. input_int() + -8
  533. \end{lstlisting}
  534. \fi}
  535. \end{minipage}
  536. \begin{minipage}{0.4\textwidth}
  537. \begin{equation}
  538. \begin{tikzpicture}
  539. \node[draw] (plus) at (0 , 0) {\key{+}};
  540. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  541. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  542. \node[draw] (8) at (1 , -2) {\key{8}};
  543. \draw[->] (plus) to (read);
  544. \draw[->] (plus) to (minus);
  545. \draw[->] (minus) to (8);
  546. \end{tikzpicture}
  547. \label{eq:arith-prog}
  548. \end{equation}
  549. \end{minipage}
  550. \end{center}
  551. We use the standard terminology for trees to describe ASTs: each
  552. rectangle above is called a \emph{node}. The arrows connect a node to its
  553. \emph{children}, which are also nodes. The top-most node is the
  554. \emph{root}. Every node except for the root has a \emph{parent} (the
  555. node of which it is the child). If a node has no children, it is a
  556. \emph{leaf} node; otherwise it is an \emph{internal} node.
  557. \index{subject}{node}
  558. \index{subject}{children}
  559. \index{subject}{root}
  560. \index{subject}{parent}
  561. \index{subject}{leaf}
  562. \index{subject}{internal node}
  563. %% Recall that an \emph{symbolic expression} (S-expression) is either
  564. %% \begin{enumerate}
  565. %% \item an atom, or
  566. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  567. %% where $e_1$ and $e_2$ are each an S-expression.
  568. %% \end{enumerate}
  569. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  570. %% null value \code{'()}, etc. We can create an S-expression in Racket
  571. %% simply by writing a backquote (called a quasi-quote in Racket)
  572. %% followed by the textual representation of the S-expression. It is
  573. %% quite common to use S-expressions to represent a list, such as $a, b
  574. %% ,c$ in the following way:
  575. %% \begin{lstlisting}
  576. %% `(a . (b . (c . ())))
  577. %% \end{lstlisting}
  578. %% Each element of the list is in the first slot of a pair, and the
  579. %% second slot is either the rest of the list or the null value, to mark
  580. %% the end of the list. Such lists are so common that Racket provides
  581. %% special notation for them that removes the need for the periods
  582. %% and so many parenthesis:
  583. %% \begin{lstlisting}
  584. %% `(a b c)
  585. %% \end{lstlisting}
  586. %% The following expression creates an S-expression that represents AST
  587. %% \eqref{eq:arith-prog}.
  588. %% \begin{lstlisting}
  589. %% `(+ (read) (- 8))
  590. %% \end{lstlisting}
  591. %% When using S-expressions to represent ASTs, the convention is to
  592. %% represent each AST node as a list and to put the operation symbol at
  593. %% the front of the list. The rest of the list contains the children. So
  594. %% in the above case, the root AST node has operation \code{`+} and its
  595. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  596. %% diagram \eqref{eq:arith-prog}.
  597. %% To build larger S-expressions one often needs to splice together
  598. %% several smaller S-expressions. Racket provides the comma operator to
  599. %% splice an S-expression into a larger one. For example, instead of
  600. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  601. %% we could have first created an S-expression for AST
  602. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  603. %% S-expression.
  604. %% \begin{lstlisting}
  605. %% (define ast1.4 `(- 8))
  606. %% (define ast1_1 `(+ (read) ,ast1.4))
  607. %% \end{lstlisting}
  608. %% In general, the Racket expression that follows the comma (splice)
  609. %% can be any expression that produces an S-expression.
  610. {\if\edition\racketEd
  611. We define a Racket \code{struct} for each kind of node. For this
  612. chapter we require just two kinds of nodes: one for integer constants
  613. (aka literals\index{subject}{literals})
  614. and one for primitive operations. The following is the \code{struct}
  615. definition for integer constants.\footnote{All the AST structures are
  616. defined in the file \code{utilities.rkt} in the support code.}
  617. \begin{lstlisting}
  618. (struct Int (value))
  619. \end{lstlisting}
  620. An integer node contains just one thing: the integer value.
  621. We establish the convention that \code{struct} names, such
  622. as \code{Int}, are capitalized.
  623. To create an AST node for the integer $8$, we write \INT{8}.
  624. \begin{lstlisting}
  625. (define eight (Int 8))
  626. \end{lstlisting}
  627. We say that the value created by \INT{8} is an
  628. \emph{instance} of the
  629. \code{Int} structure.
  630. The following is the \code{struct} definition for primitive operations.
  631. \begin{lstlisting}
  632. (struct Prim (op args))
  633. \end{lstlisting}
  634. A primitive operation node includes an operator symbol \code{op} and a
  635. list of child arguments called \code{args}. For example, to create an
  636. AST that negates the number $8$, we write the following.
  637. \begin{lstlisting}
  638. (define neg-eight (Prim '- (list eight)))
  639. \end{lstlisting}
  640. Primitive operations may have zero or more children. The \code{read}
  641. operator has zero:
  642. \begin{lstlisting}
  643. (define rd (Prim 'read '()))
  644. \end{lstlisting}
  645. The addition operator has two children:
  646. \begin{lstlisting}
  647. (define ast1_1 (Prim '+ (list rd neg-eight)))
  648. \end{lstlisting}
  649. We have made a design choice regarding the \code{Prim} structure.
  650. Instead of using one structure for many different operations
  651. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  652. structure for each operation, as follows:
  653. \begin{lstlisting}
  654. (struct Read ())
  655. (struct Add (left right))
  656. (struct Neg (value))
  657. \end{lstlisting}
  658. The reason that we choose to use just one structure is that many parts
  659. of the compiler can use the same code for the different primitive
  660. operators, so we might as well just write that code once by using a
  661. single structure.
  662. %
  663. \fi}
  664. {\if\edition\pythonEd\pythonColor
  665. We use a Python \code{class} for each kind of node.
  666. The following is the class definition for
  667. constants (aka literals\index{subject}{literals})
  668. from the Python \code{ast} module.
  669. \begin{lstlisting}
  670. class Constant:
  671. def __init__(self, value):
  672. self.value = value
  673. \end{lstlisting}
  674. An integer constant node includes just one thing: the integer value.
  675. To create an AST node for the integer $8$, we write \INT{8}.
  676. \begin{lstlisting}
  677. eight = Constant(8)
  678. \end{lstlisting}
  679. We say that the value created by \INT{8} is an
  680. \emph{instance} of the \code{Constant} class.
  681. The following is the class definition for unary operators.
  682. \begin{lstlisting}
  683. class UnaryOp:
  684. def __init__(self, op, operand):
  685. self.op = op
  686. self.operand = operand
  687. \end{lstlisting}
  688. The specific operation is specified by the \code{op} parameter. For
  689. example, the class \code{USub} is for unary subtraction.
  690. (More unary operators are introduced in later chapters.) To create an AST that
  691. negates the number $8$, we write the following.
  692. \begin{lstlisting}
  693. neg_eight = UnaryOp(USub(), eight)
  694. \end{lstlisting}
  695. The call to the \code{input\_int} function is represented by the
  696. \code{Call} and \code{Name} classes.
  697. \begin{lstlisting}
  698. class Call:
  699. def __init__(self, func, args):
  700. self.func = func
  701. self.args = args
  702. class Name:
  703. def __init__(self, id):
  704. self.id = id
  705. \end{lstlisting}
  706. To create an AST node that calls \code{input\_int}, we write
  707. \begin{lstlisting}
  708. read = Call(Name('input_int'), [])
  709. \end{lstlisting}
  710. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  711. the \code{BinOp} class for binary operators.
  712. \begin{lstlisting}
  713. class BinOp:
  714. def __init__(self, left, op, right):
  715. self.op = op
  716. self.left = left
  717. self.right = right
  718. \end{lstlisting}
  719. Similar to \code{UnaryOp}, the specific operation is specified by the
  720. \code{op} parameter, which for now is just an instance of the
  721. \code{Add} class. So to create the AST
  722. node that adds negative eight to some user input, we write the following.
  723. \begin{lstlisting}
  724. ast1_1 = BinOp(read, Add(), neg_eight)
  725. \end{lstlisting}
  726. \fi}
  727. To compile a program such as \eqref{eq:arith-prog}, we need to know
  728. that the operation associated with the root node is addition and we
  729. need to be able to access its two
  730. children. \racket{Racket}\python{Python} provides pattern matching to
  731. support these kinds of queries, as we see in
  732. section~\ref{sec:pattern-matching}.
  733. We often write down the concrete syntax of a program even when we
  734. actually have in mind the AST, because the concrete syntax is more
  735. concise. We recommend that you always think of programs as abstract
  736. syntax trees.
  737. \section{Grammars}
  738. \label{sec:grammar}
  739. \index{subject}{integer}
  740. %\index{subject}{constant}
  741. A programming language can be thought of as a \emph{set} of programs.
  742. The set is infinite (that is, one can always create larger programs),
  743. so one cannot simply describe a language by listing all the
  744. programs in the language. Instead we write down a set of rules, a
  745. \emph{context-free grammar}, for building programs. Grammars are often used to
  746. define the concrete syntax of a language, but they can also be used to
  747. describe the abstract syntax. We write our rules in a variant of
  748. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  749. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  750. we describe a small language, named \LangInt{}, that consists of
  751. integers and arithmetic operations.\index{subject}{grammar}
  752. \index{subject}{context-free grammar}
  753. The first grammar rule for the abstract syntax of \LangInt{} says that an
  754. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  755. \begin{equation}
  756. \Exp ::= \INT{\Int} \label{eq:arith-int}
  757. \end{equation}
  758. %
  759. Each rule has a left-hand side and a right-hand side.
  760. If you have an AST node that matches the
  761. right-hand side, then you can categorize it according to the
  762. left-hand side.
  763. %
  764. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  765. are \emph{terminal} symbols and must literally appear in the program for the
  766. rule to be applicable.\index{subject}{terminal}
  767. %
  768. Our grammars do not mention \emph{white space}, that is, delimiter
  769. characters like spaces, tabs, and new lines. White space may be
  770. inserted between symbols for disambiguation and to improve
  771. readability. \index{subject}{white space}
  772. %
  773. A name such as $\Exp$ that is defined by the grammar rules is a
  774. \emph{nonterminal}. \index{subject}{nonterminal}
  775. %
  776. The name $\Int$ is also a nonterminal, but instead of defining it with
  777. a grammar rule, we define it with the following explanation. An
  778. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  779. $-$ (for negative integers), such that the sequence of decimals
  780. %
  781. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  782. enables the representation of integers using 63 bits, which simplifies
  783. several aspects of compilation.
  784. %
  785. Thus, these integers correspond to the Racket \texttt{fixnum}
  786. datatype on a 64-bit machine.}
  787. %
  788. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  789. enables the representation of integers using 64 bits, which simplifies
  790. several aspects of compilation. In contrast, integers in Python have
  791. unlimited precision, but the techniques needed to handle unlimited
  792. precision fall outside the scope of this book.}
  793. The second grammar rule is the \READOP{} operation, which receives an
  794. input integer from the user of the program.
  795. \begin{equation}
  796. \Exp ::= \READ{} \label{eq:arith-read}
  797. \end{equation}
  798. The third rule categorizes the negation of an $\Exp$ node as an
  799. $\Exp$.
  800. \begin{equation}
  801. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  802. \end{equation}
  803. We can apply these rules to categorize the ASTs that are in the
  804. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  805. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  806. following AST is an $\Exp$.
  807. \begin{center}
  808. \begin{minipage}{0.5\textwidth}
  809. \NEG{\INT{\code{8}}}
  810. \end{minipage}
  811. \begin{minipage}{0.25\textwidth}
  812. \begin{equation}
  813. \begin{tikzpicture}
  814. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  815. \node[draw, circle] (8) at (0, -1.2) {$8$};
  816. \draw[->] (minus) to (8);
  817. \end{tikzpicture}
  818. \label{eq:arith-neg8}
  819. \end{equation}
  820. \end{minipage}
  821. \end{center}
  822. The next two grammar rules are for addition and subtraction expressions:
  823. \begin{align}
  824. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  825. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  826. \end{align}
  827. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  828. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  829. \eqref{eq:arith-read}, and we have already categorized
  830. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  831. to show that
  832. \[
  833. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  834. \]
  835. is an $\Exp$ in the \LangInt{} language.
  836. If you have an AST for which these rules do not apply, then the
  837. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  838. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  839. because there is no rule for the \key{*} operator. Whenever we
  840. define a language with a grammar, the language includes only those
  841. programs that are justified by the grammar rules.
  842. {\if\edition\pythonEd\pythonColor
  843. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  844. There is a statement for printing the value of an expression
  845. \[
  846. \Stmt{} ::= \PRINT{\Exp}
  847. \]
  848. and a statement that evaluates an expression but ignores the result.
  849. \[
  850. \Stmt{} ::= \EXPR{\Exp}
  851. \]
  852. \fi}
  853. {\if\edition\racketEd
  854. The last grammar rule for \LangInt{} states that there is a
  855. \code{Program} node to mark the top of the whole program:
  856. \[
  857. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  858. \]
  859. The \code{Program} structure is defined as follows:
  860. \begin{lstlisting}
  861. (struct Program (info body))
  862. \end{lstlisting}
  863. where \code{body} is an expression. In further chapters, the \code{info}
  864. part is used to store auxiliary information, but for now it is
  865. just the empty list.
  866. \fi}
  867. {\if\edition\pythonEd\pythonColor
  868. The last grammar rule for \LangInt{} states that there is a
  869. \code{Module} node to mark the top of the whole program:
  870. \[
  871. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  872. \]
  873. The asterisk $*$ indicates a list of the preceding grammar item, in
  874. this case a list of statements.
  875. %
  876. The \code{Module} class is defined as follows:
  877. \begin{lstlisting}
  878. class Module:
  879. def __init__(self, body):
  880. self.body = body
  881. \end{lstlisting}
  882. where \code{body} is a list of statements.
  883. \fi}
  884. It is common to have many grammar rules with the same left-hand side
  885. but different right-hand sides, such as the rules for $\Exp$ in the
  886. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  887. combine several right-hand sides into a single rule.
  888. The concrete syntax for \LangInt{} is shown in
  889. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  890. \LangInt{} is shown in figure~\ref{fig:r0-syntax}. %
  891. %
  892. \racket{The \code{read-program} function provided in
  893. \code{utilities.rkt} of the support code reads a program from a file
  894. (the sequence of characters in the concrete syntax of Racket) and
  895. parses it into an abstract syntax tree. Refer to the description of
  896. \code{read-program} in appendix~\ref{appendix:utilities} for more
  897. details.}
  898. %
  899. \python{We recommend using the \code{parse} function in Python's
  900. \code{ast} module to convert the concrete syntax into an abstract
  901. syntax tree.}
  902. \newcommand{\LintGrammarRacket}{
  903. \begin{array}{rcl}
  904. \Type &::=& \key{Integer} \\
  905. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  906. \MID \CSUB{\Exp}{\Exp}
  907. \end{array}
  908. }
  909. \newcommand{\LintASTRacket}{
  910. \begin{array}{rcl}
  911. \Type &::=& \key{Integer} \\
  912. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  913. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  914. \end{array}
  915. }
  916. \newcommand{\LintGrammarPython}{
  917. \begin{array}{rcl}
  918. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  919. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  920. \end{array}
  921. }
  922. \newcommand{\LintASTPython}{
  923. \begin{array}{rcl}
  924. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  925. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  926. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  927. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  928. \end{array}
  929. }
  930. \begin{figure}[tp]
  931. \begin{tcolorbox}[colback=white]
  932. {\if\edition\racketEd
  933. \[
  934. \begin{array}{l}
  935. \LintGrammarRacket \\
  936. \begin{array}{rcl}
  937. \LangInt{} &::=& \Exp
  938. \end{array}
  939. \end{array}
  940. \]
  941. \fi}
  942. {\if\edition\pythonEd\pythonColor
  943. \[
  944. \begin{array}{l}
  945. \LintGrammarPython \\
  946. \begin{array}{rcl}
  947. \LangInt{} &::=& \Stmt^{*}
  948. \end{array}
  949. \end{array}
  950. \]
  951. \fi}
  952. \end{tcolorbox}
  953. \caption{The concrete syntax of \LangInt{}.}
  954. \label{fig:r0-concrete-syntax}
  955. \index{subject}{Lint@\LangInt{} concrete syntax}
  956. \end{figure}
  957. \begin{figure}[tp]
  958. \begin{tcolorbox}[colback=white]
  959. {\if\edition\racketEd
  960. \[
  961. \begin{array}{l}
  962. \LintASTRacket{} \\
  963. \begin{array}{rcl}
  964. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  965. \end{array}
  966. \end{array}
  967. \]
  968. \fi}
  969. {\if\edition\pythonEd\pythonColor
  970. \[
  971. \begin{array}{l}
  972. \LintASTPython\\
  973. \begin{array}{rcl}
  974. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  975. \end{array}
  976. \end{array}
  977. \]
  978. \fi}
  979. \end{tcolorbox}
  980. \python{
  981. \index{subject}{Constant@\texttt{Constant}}
  982. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  983. \index{subject}{USub@\texttt{USub}}
  984. \index{subject}{inputint@\texttt{input\_int}}
  985. \index{subject}{Call@\texttt{Call}}
  986. \index{subject}{Name@\texttt{Name}}
  987. \index{subject}{BinOp@\texttt{BinOp}}
  988. \index{subject}{Add@\texttt{Add}}
  989. \index{subject}{Sub@\texttt{Sub}}
  990. \index{subject}{print@\texttt{print}}
  991. \index{subject}{Expr@\texttt{Expr}}
  992. \index{subject}{Module@\texttt{Module}}
  993. }
  994. \caption{The abstract syntax of \LangInt{}.}
  995. \label{fig:r0-syntax}
  996. \index{subject}{Lint@\LangInt{} abstract syntax}
  997. \end{figure}
  998. \section{Pattern Matching}
  999. \label{sec:pattern-matching}
  1000. As mentioned in section~\ref{sec:ast}, compilers often need to access
  1001. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  1002. provides the \texttt{match} feature to access the parts of a value.
  1003. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  1004. \begin{center}
  1005. \begin{minipage}{1.0\textwidth}
  1006. {\if\edition\racketEd
  1007. \begin{lstlisting}
  1008. (match ast1_1
  1009. [(Prim op (list child1 child2))
  1010. (print op)])
  1011. \end{lstlisting}
  1012. \fi}
  1013. {\if\edition\pythonEd\pythonColor
  1014. \begin{lstlisting}
  1015. match ast1_1:
  1016. case BinOp(child1, op, child2):
  1017. print(op)
  1018. \end{lstlisting}
  1019. \fi}
  1020. \end{minipage}
  1021. \end{center}
  1022. {\if\edition\racketEd
  1023. %
  1024. In this example, the \texttt{match} form checks whether the AST
  1025. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1026. three pattern variables \texttt{op}, \texttt{child1}, and
  1027. \texttt{child2}. In general, a match clause consists of a
  1028. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1029. recursively defined to be a pattern variable, a structure name
  1030. followed by a pattern for each of the structure's arguments, or an
  1031. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1032. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1033. and chapter 9 of The Racket
  1034. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1035. for complete descriptions of \code{match}.)
  1036. %
  1037. The body of a match clause may contain arbitrary Racket code. The
  1038. pattern variables can be used in the scope of the body, such as
  1039. \code{op} in \code{(print op)}.
  1040. %
  1041. \fi}
  1042. %
  1043. %
  1044. {\if\edition\pythonEd\pythonColor
  1045. %
  1046. In the example above, the \texttt{match} form checks whether the AST
  1047. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1048. three pattern variables (\texttt{child1}, \texttt{op}, and
  1049. \texttt{child2}). In general, each \code{case} consists of a
  1050. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1051. recursively defined to be one of the following: a pattern variable, a
  1052. class name followed by a pattern for each of its constructor's
  1053. arguments, or other literals\index{subject}{literals} such as strings
  1054. or lists.
  1055. %
  1056. The body of each \code{case} may contain arbitrary Python code. The
  1057. pattern variables can be used in the body, such as \code{op} in
  1058. \code{print(op)}.
  1059. %
  1060. \fi}
  1061. A \code{match} form may contain several clauses, as in the following
  1062. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1063. the AST. The \code{match} proceeds through the clauses in order,
  1064. checking whether the pattern can match the input AST. The body of the
  1065. first clause that matches is executed. The output of \code{leaf} for
  1066. several ASTs is shown on the right side of the following:
  1067. \begin{center}
  1068. \begin{minipage}{0.6\textwidth}
  1069. {\if\edition\racketEd
  1070. \begin{lstlisting}
  1071. (define (leaf arith)
  1072. (match arith
  1073. [(Int n) #t]
  1074. [(Prim 'read '()) #t]
  1075. [(Prim '- (list e1)) #f]
  1076. [(Prim '+ (list e1 e2)) #f]
  1077. [(Prim '- (list e1 e2)) #f]))
  1078. (leaf (Prim 'read '()))
  1079. (leaf (Prim '- (list (Int 8))))
  1080. (leaf (Int 8))
  1081. \end{lstlisting}
  1082. \fi}
  1083. {\if\edition\pythonEd\pythonColor
  1084. \begin{lstlisting}
  1085. def leaf(arith):
  1086. match arith:
  1087. case Constant(n):
  1088. return True
  1089. case Call(Name('input_int'), []):
  1090. return True
  1091. case UnaryOp(USub(), e1):
  1092. return False
  1093. case BinOp(e1, Add(), e2):
  1094. return False
  1095. case BinOp(e1, Sub(), e2):
  1096. return False
  1097. print(leaf(Call(Name('input_int'), [])))
  1098. print(leaf(UnaryOp(USub(), eight)))
  1099. print(leaf(Constant(8)))
  1100. \end{lstlisting}
  1101. \fi}
  1102. \end{minipage}
  1103. \vrule
  1104. \begin{minipage}{0.25\textwidth}
  1105. {\if\edition\racketEd
  1106. \begin{lstlisting}
  1107. #t
  1108. #f
  1109. #t
  1110. \end{lstlisting}
  1111. \fi}
  1112. {\if\edition\pythonEd\pythonColor
  1113. \begin{lstlisting}
  1114. True
  1115. False
  1116. True
  1117. \end{lstlisting}
  1118. \fi}
  1119. \end{minipage}
  1120. \index{subject}{True@\TRUE{}}
  1121. \index{subject}{False@\FALSE{}}
  1122. \end{center}
  1123. When constructing a \code{match} expression, we refer to the grammar
  1124. definition to identify which nonterminal we are expecting to match
  1125. against, and then we make sure that (1) we have one
  1126. \racket{clause}\python{case} for each alternative of that nonterminal
  1127. and (2) the pattern in each \racket{clause}\python{case}
  1128. corresponds to the corresponding right-hand side of a grammar
  1129. rule. For the \code{match} in the \code{leaf} function, we refer to
  1130. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1131. nonterminal has five alternatives, so the \code{match} has five
  1132. \racket{clauses}\python{cases}. The pattern in each
  1133. \racket{clause}\python{case} corresponds to the right-hand side of a
  1134. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1135. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1136. translating from grammars to patterns, replace nonterminals such as
  1137. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1138. \code{e2}).
  1139. \section{Recursive Functions}
  1140. \label{sec:recursion}
  1141. \index{subject}{recursive function}
  1142. Programs are inherently recursive. For example, an expression is often
  1143. made of smaller expressions. Thus, the natural way to process an
  1144. entire program is to use a recursive function. As a first example of
  1145. such a recursive function, we define the function \code{is\_exp} as
  1146. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1147. value and determine whether or not it is an expression in \LangInt{}.
  1148. %
  1149. We say that a function is defined by \emph{structural recursion} if
  1150. it is defined using a sequence of match \racket{clauses}\python{cases}
  1151. that correspond to a grammar and the body of each
  1152. \racket{clause}\python{case} makes a recursive call on each child
  1153. node.\footnote{This principle of structuring code according to the
  1154. data definition is advocated in the book \emph{How to Design
  1155. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1156. second function, named \code{is\_stmt}, that recognizes whether a value
  1157. is a \LangInt{} statement.} \python{Finally, }
  1158. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1159. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1160. In general, we can write one recursive function to handle each
  1161. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1162. two examples at the bottom of the figure, the first is in
  1163. \LangInt{} and the second is not.
  1164. \begin{figure}[tp]
  1165. \begin{tcolorbox}[colback=white]
  1166. {\if\edition\racketEd
  1167. \begin{lstlisting}
  1168. (define (is_exp ast)
  1169. (match ast
  1170. [(Int n) #t]
  1171. [(Prim 'read '()) #t]
  1172. [(Prim '- (list e)) (is_exp e)]
  1173. [(Prim '+ (list e1 e2))
  1174. (and (is_exp e1) (is_exp e2))]
  1175. [(Prim '- (list e1 e2))
  1176. (and (is_exp e1) (is_exp e2))]
  1177. [else #f]))
  1178. (define (is_Lint ast)
  1179. (match ast
  1180. [(Program '() e) (is_exp e)]
  1181. [else #f]))
  1182. (is_Lint (Program '() ast1_1)
  1183. (is_Lint (Program '()
  1184. (Prim '* (list (Prim 'read '())
  1185. (Prim '+ (list (Int 8)))))))
  1186. \end{lstlisting}
  1187. \fi}
  1188. {\if\edition\pythonEd\pythonColor
  1189. \begin{lstlisting}
  1190. def is_exp(e):
  1191. match e:
  1192. case Constant(n):
  1193. return True
  1194. case Call(Name('input_int'), []):
  1195. return True
  1196. case UnaryOp(USub(), e1):
  1197. return is_exp(e1)
  1198. case BinOp(e1, Add(), e2):
  1199. return is_exp(e1) and is_exp(e2)
  1200. case BinOp(e1, Sub(), e2):
  1201. return is_exp(e1) and is_exp(e2)
  1202. case _:
  1203. return False
  1204. def is_stmt(s):
  1205. match s:
  1206. case Expr(Call(Name('print'), [e])):
  1207. return is_exp(e)
  1208. case Expr(e):
  1209. return is_exp(e)
  1210. case _:
  1211. return False
  1212. def is_Lint(p):
  1213. match p:
  1214. case Module(body):
  1215. return all([is_stmt(s) for s in body])
  1216. case _:
  1217. return False
  1218. print(is_Lint(Module([Expr(ast1_1)])))
  1219. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1220. UnaryOp(Add(), Constant(8))))])))
  1221. \end{lstlisting}
  1222. \fi}
  1223. \end{tcolorbox}
  1224. \caption{Example of recursive functions for \LangInt{}. These functions
  1225. recognize whether an AST is in \LangInt{}.}
  1226. \label{fig:exp-predicate}
  1227. \end{figure}
  1228. %% You may be tempted to merge the two functions into one, like this:
  1229. %% \begin{center}
  1230. %% \begin{minipage}{0.5\textwidth}
  1231. %% \begin{lstlisting}
  1232. %% (define (Lint ast)
  1233. %% (match ast
  1234. %% [(Int n) #t]
  1235. %% [(Prim 'read '()) #t]
  1236. %% [(Prim '- (list e)) (Lint e)]
  1237. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1238. %% [(Program '() e) (Lint e)]
  1239. %% [else #f]))
  1240. %% \end{lstlisting}
  1241. %% \end{minipage}
  1242. %% \end{center}
  1243. %% %
  1244. %% Sometimes such a trick will save a few lines of code, especially when
  1245. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1246. %% \emph{not} recommended because it can get you into trouble.
  1247. %% %
  1248. %% For example, the above function is subtly wrong:
  1249. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1250. %% returns true when it should return false.
  1251. \section{Interpreters}
  1252. \label{sec:interp_Lint}
  1253. \index{subject}{interpreter}
  1254. The behavior of a program is defined by the specification of the
  1255. programming language.
  1256. %
  1257. \racket{For example, the Scheme language is defined in the report by
  1258. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1259. reference manual~\citep{plt-tr}.}
  1260. %
  1261. \python{For example, the Python language is defined in the Python
  1262. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1263. %
  1264. In this book we use interpreters to specify each language that we
  1265. consider. An interpreter that is designated as the definition of a
  1266. language is called a \emph{definitional
  1267. interpreter}~\citep{reynolds72:_def_interp}.
  1268. \index{subject}{definitional interpreter} We warm up by creating a
  1269. definitional interpreter for the \LangInt{} language. This interpreter
  1270. serves as a second example of structural recursion. The definition of the
  1271. \code{interp\_Lint} function is shown in
  1272. figure~\ref{fig:interp_Lint}.
  1273. %
  1274. \racket{The body of the function is a match on the input program
  1275. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1276. which in turn has one match clause per grammar rule for \LangInt{}
  1277. expressions.}
  1278. %
  1279. \python{The body of the function matches on the \code{Module} AST node
  1280. and then invokes \code{interp\_stmt} on each statement in the
  1281. module. The \code{interp\_stmt} function includes a case for each
  1282. grammar rule of the \Stmt{} nonterminal, and it calls
  1283. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1284. function includes a case for each grammar rule of the \Exp{}
  1285. nonterminal. We use several auxiliary functions such as \code{add64}
  1286. and \code{input\_int} that are defined in the support code for this book.}
  1287. \begin{figure}[tp]
  1288. \begin{tcolorbox}[colback=white]
  1289. {\if\edition\racketEd
  1290. \begin{lstlisting}
  1291. (define (interp_exp e)
  1292. (match e
  1293. [(Int n) n]
  1294. [(Prim 'read '())
  1295. (define r (read))
  1296. (cond [(fixnum? r) r]
  1297. [else (error 'interp_exp "read expected an integer: ~v" r)])]
  1298. [(Prim '- (list e))
  1299. (define v (interp_exp e))
  1300. (fx- 0 v)]
  1301. [(Prim '+ (list e1 e2))
  1302. (define v1 (interp_exp e1))
  1303. (define v2 (interp_exp e2))
  1304. (fx+ v1 v2)]
  1305. [(Prim '- (list e1 e2))
  1306. (define v1 (interp_exp e1))
  1307. (define v2 (interp_exp e2))
  1308. (fx- v1 v2)]))
  1309. (define (interp_Lint p)
  1310. (match p
  1311. [(Program '() e) (interp_exp e)]))
  1312. \end{lstlisting}
  1313. \fi}
  1314. {\if\edition\pythonEd\pythonColor
  1315. \begin{lstlisting}
  1316. def interp_exp(e):
  1317. match e:
  1318. case BinOp(left, Add(), right):
  1319. l = interp_exp(left); r = interp_exp(right)
  1320. return add64(l, r)
  1321. case BinOp(left, Sub(), right):
  1322. l = interp_exp(left); r = interp_exp(right)
  1323. return sub64(l, r)
  1324. case UnaryOp(USub(), v):
  1325. return neg64(interp_exp(v))
  1326. case Constant(value):
  1327. return value
  1328. case Call(Name('input_int'), []):
  1329. return input_int()
  1330. def interp_stmt(s):
  1331. match s:
  1332. case Expr(Call(Name('print'), [arg])):
  1333. print(interp_exp(arg))
  1334. case Expr(value):
  1335. interp_exp(value)
  1336. def interp_Lint(p):
  1337. match p:
  1338. case Module(body):
  1339. for s in body:
  1340. interp_stmt(s)
  1341. \end{lstlisting}
  1342. \fi}
  1343. \end{tcolorbox}
  1344. \caption{Interpreter for the \LangInt{} language.}
  1345. \label{fig:interp_Lint}
  1346. \end{figure}
  1347. Let us consider the result of interpreting a few \LangInt{} programs. The
  1348. following program adds two integers:
  1349. {\if\edition\racketEd
  1350. \begin{lstlisting}
  1351. (+ 10 32)
  1352. \end{lstlisting}
  1353. \fi}
  1354. {\if\edition\pythonEd\pythonColor
  1355. \begin{lstlisting}
  1356. print(10 + 32)
  1357. \end{lstlisting}
  1358. \fi}
  1359. %
  1360. \noindent The result is \key{42}, the answer to life, the universe,
  1361. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1362. the Galaxy} by Douglas Adams.}
  1363. %
  1364. We wrote this program in concrete syntax, whereas the parsed
  1365. abstract syntax is
  1366. {\if\edition\racketEd
  1367. \begin{lstlisting}
  1368. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1369. \end{lstlisting}
  1370. \fi}
  1371. {\if\edition\pythonEd\pythonColor
  1372. \begin{lstlisting}
  1373. Module([Expr(Call(Name('print'),
  1374. [BinOp(Constant(10), Add(), Constant(32))]))])
  1375. \end{lstlisting}
  1376. \fi}
  1377. The following program demonstrates that expressions may be nested within
  1378. each other, in this case nesting several additions and negations.
  1379. {\if\edition\racketEd
  1380. \begin{lstlisting}
  1381. (+ 10 (- (+ 12 20)))
  1382. \end{lstlisting}
  1383. \fi}
  1384. {\if\edition\pythonEd\pythonColor
  1385. \begin{lstlisting}
  1386. print(10 + -(12 + 20))
  1387. \end{lstlisting}
  1388. \fi}
  1389. %
  1390. \noindent What is the result of this program?
  1391. {\if\edition\racketEd
  1392. As mentioned previously, the \LangInt{} language does not support
  1393. arbitrarily large integers but only $63$-bit integers, so we
  1394. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1395. in Racket.
  1396. Suppose that
  1397. \[
  1398. n = 999999999999999999
  1399. \]
  1400. which indeed fits in $63$ bits. What happens when we run the
  1401. following program in our interpreter?
  1402. \begin{lstlisting}
  1403. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1404. \end{lstlisting}
  1405. It produces the following error:
  1406. \begin{lstlisting}
  1407. fx+: result is not a fixnum
  1408. \end{lstlisting}
  1409. We establish the convention that if running the definitional
  1410. interpreter on a program produces an error, then the meaning of that
  1411. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1412. error is a \code{trapped-error}. A compiler for the language is under
  1413. no obligation regarding programs with unspecified behavior; it does
  1414. not have to produce an executable, and if it does, that executable can
  1415. do anything. On the other hand, if the error is a
  1416. \code{trapped-error}, then the compiler must produce an executable and
  1417. it is required to report that an error occurred. To signal an error,
  1418. exit with a return code of \code{255}. The interpreters in chapters
  1419. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1420. \code{trapped-error}.
  1421. \fi}
  1422. % TODO: how to deal with too-large integers in the Python interpreter?
  1423. %% This convention applies to the languages defined in this
  1424. %% book, as a way to simplify the student's task of implementing them,
  1425. %% but this convention is not applicable to all programming languages.
  1426. %%
  1427. The last feature of the \LangInt{} language, the \READOP{} operation,
  1428. prompts the user of the program for an integer. Recall that program
  1429. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1430. \code{8}. So, if we run {\if\edition\racketEd
  1431. \begin{lstlisting}
  1432. (interp_Lint (Program '() ast1_1))
  1433. \end{lstlisting}
  1434. \fi}
  1435. {\if\edition\pythonEd\pythonColor
  1436. \begin{lstlisting}
  1437. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1438. \end{lstlisting}
  1439. \fi}
  1440. \noindent and if the input is \code{50}, the result is \code{42}.
  1441. We include the \READOP{} operation in \LangInt{} so that a clever
  1442. student cannot implement a compiler for \LangInt{} that simply runs
  1443. the interpreter during compilation to obtain the output and then
  1444. generates the trivial code to produce the output.\footnote{Yes, a
  1445. clever student did this in the first instance of this course!}
  1446. The job of a compiler is to translate a program in one language into a
  1447. program in another language so that the output program behaves the
  1448. same way as the input program. This idea is depicted in the
  1449. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1450. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1451. Given a compiler that translates from language $\mathcal{L}_1$ to
  1452. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1453. compiler must translate it into some program $P_2$ such that
  1454. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1455. same input $i$ yields the same output $o$.
  1456. \begin{equation} \label{eq:compile-correct}
  1457. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1458. \node (p1) at (0, 0) {$P_1$};
  1459. \node (p2) at (3, 0) {$P_2$};
  1460. \node (o) at (3, -2.5) {$o$};
  1461. \path[->] (p1) edge [above] node {compile} (p2);
  1462. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1463. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1464. \end{tikzpicture}
  1465. \end{equation}
  1466. \python{We establish the convention that if running the definitional
  1467. interpreter on a program produces an error, then the meaning of that
  1468. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1469. unless the exception raised is a \code{TrappedError}. A compiler for
  1470. the language is under no obligation regarding programs with
  1471. unspecified behavior; it does not have to produce an executable, and
  1472. if it does, that executable can do anything. On the other hand, if
  1473. the error is a \code{TrappedError}, then the compiler must produce
  1474. an executable and it is required to report that an error
  1475. occurred. To signal an error, exit with a return code of \code{255}.
  1476. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1477. section \ref{sec:arrays} use \code{TrappedError}.}
  1478. In the next section we see our first example of a compiler.
  1479. \section{Example Compiler: A Partial Evaluator}
  1480. \label{sec:partial-evaluation}
  1481. In this section we consider a compiler that translates \LangInt{}
  1482. programs into \LangInt{} programs that may be more efficient. The
  1483. compiler eagerly computes the parts of the program that do not depend
  1484. on any inputs, a process known as \emph{partial
  1485. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1486. For example, given the following program
  1487. {\if\edition\racketEd
  1488. \begin{lstlisting}
  1489. (+ (read) (- (+ 5 3)))
  1490. \end{lstlisting}
  1491. \fi}
  1492. {\if\edition\pythonEd\pythonColor
  1493. \begin{lstlisting}
  1494. print(input_int() + -(5 + 3) )
  1495. \end{lstlisting}
  1496. \fi}
  1497. \noindent our compiler translates it into the program
  1498. {\if\edition\racketEd
  1499. \begin{lstlisting}
  1500. (+ (read) -8)
  1501. \end{lstlisting}
  1502. \fi}
  1503. {\if\edition\pythonEd\pythonColor
  1504. \begin{lstlisting}
  1505. print(input_int() + -8)
  1506. \end{lstlisting}
  1507. \fi}
  1508. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1509. evaluator for the \LangInt{} language. The output of the partial evaluator
  1510. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1511. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1512. whereas the code for partially evaluating the negation and addition
  1513. operations is factored into three auxiliary functions:
  1514. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1515. functions is the output of partially evaluating the children.
  1516. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1517. arguments are integers and if they are, perform the appropriate
  1518. arithmetic. Otherwise, they create an AST node for the arithmetic
  1519. operation.
  1520. \begin{figure}[tp]
  1521. \begin{tcolorbox}[colback=white]
  1522. {\if\edition\racketEd
  1523. \begin{lstlisting}
  1524. (define (pe_neg r)
  1525. (match r
  1526. [(Int n) (Int (fx- 0 n))]
  1527. [else (Prim '- (list r))]))
  1528. (define (pe_add r1 r2)
  1529. (match* (r1 r2)
  1530. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1531. [(_ _) (Prim '+ (list r1 r2))]))
  1532. (define (pe_sub r1 r2)
  1533. (match* (r1 r2)
  1534. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1535. [(_ _) (Prim '- (list r1 r2))]))
  1536. (define (pe_exp e)
  1537. (match e
  1538. [(Int n) (Int n)]
  1539. [(Prim 'read '()) (Prim 'read '())]
  1540. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1541. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1542. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1543. (define (pe_Lint p)
  1544. (match p
  1545. [(Program '() e) (Program '() (pe_exp e))]))
  1546. \end{lstlisting}
  1547. \fi}
  1548. {\if\edition\pythonEd\pythonColor
  1549. \begin{lstlisting}
  1550. def pe_neg(r):
  1551. match r:
  1552. case Constant(n):
  1553. return Constant(neg64(n))
  1554. case _:
  1555. return UnaryOp(USub(), r)
  1556. def pe_add(r1, r2):
  1557. match (r1, r2):
  1558. case (Constant(n1), Constant(n2)):
  1559. return Constant(add64(n1, n2))
  1560. case _:
  1561. return BinOp(r1, Add(), r2)
  1562. def pe_sub(r1, r2):
  1563. match (r1, r2):
  1564. case (Constant(n1), Constant(n2)):
  1565. return Constant(sub64(n1, n2))
  1566. case _:
  1567. return BinOp(r1, Sub(), r2)
  1568. def pe_exp(e):
  1569. match e:
  1570. case BinOp(left, Add(), right):
  1571. return pe_add(pe_exp(left), pe_exp(right))
  1572. case BinOp(left, Sub(), right):
  1573. return pe_sub(pe_exp(left), pe_exp(right))
  1574. case UnaryOp(USub(), v):
  1575. return pe_neg(pe_exp(v))
  1576. case Constant(value):
  1577. return e
  1578. case Call(Name('input_int'), []):
  1579. return e
  1580. def pe_stmt(s):
  1581. match s:
  1582. case Expr(Call(Name('print'), [arg])):
  1583. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1584. case Expr(value):
  1585. return Expr(pe_exp(value))
  1586. def pe_P_int(p):
  1587. match p:
  1588. case Module(body):
  1589. new_body = [pe_stmt(s) for s in body]
  1590. return Module(new_body)
  1591. \end{lstlisting}
  1592. \fi}
  1593. \end{tcolorbox}
  1594. \caption{A partial evaluator for \LangInt{}.}
  1595. \label{fig:pe-arith}
  1596. \end{figure}
  1597. To gain some confidence that the partial evaluator is correct, we can
  1598. test whether it produces programs that produce the same result as the
  1599. input programs. That is, we can test whether it satisfies the diagram
  1600. of \eqref{eq:compile-correct}.
  1601. %
  1602. {\if\edition\racketEd
  1603. The following code runs the partial evaluator on several examples and
  1604. tests the output program. The \texttt{parse-program} and
  1605. \texttt{assert} functions are defined in
  1606. appendix~\ref{appendix:utilities}.\\
  1607. \begin{minipage}{1.0\textwidth}
  1608. \begin{lstlisting}
  1609. (define (test_pe p)
  1610. (assert "testing pe_Lint"
  1611. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1612. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1613. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1614. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1615. \end{lstlisting}
  1616. \end{minipage}
  1617. \fi}
  1618. % TODO: python version of testing the PE
  1619. \begin{exercise}\normalfont\normalsize
  1620. Create three programs in the \LangInt{} language and test whether
  1621. partially evaluating them with \code{pe\_Lint} and then
  1622. interpreting them with \code{interp\_Lint} gives the same result
  1623. as directly interpreting them with \code{interp\_Lint}.
  1624. \end{exercise}
  1625. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1626. \chapter{Integers and Variables}
  1627. \label{ch:Lvar}
  1628. \setcounter{footnote}{0}
  1629. This chapter covers compiling a subset of
  1630. \racket{Racket}\python{Python} to x86-64 assembly
  1631. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1632. integer arithmetic and local variables. We often refer to x86-64
  1633. simply as x86. The chapter first describes the \LangVar{} language
  1634. (section~\ref{sec:s0}) and then introduces x86 assembly
  1635. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1636. discuss only the instructions needed for compiling \LangVar{}. We
  1637. introduce more x86 instructions in subsequent chapters. After
  1638. introducing \LangVar{} and x86, we reflect on their differences and
  1639. create a plan to break down the translation from \LangVar{} to x86
  1640. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1641. the chapter gives detailed hints regarding each step. We aim to give
  1642. enough hints that the well-prepared reader, together with a few
  1643. friends, can implement a compiler from \LangVar{} to x86 in a short
  1644. time. To suggest the scale of this first compiler, we note that the
  1645. instructor solution for the \LangVar{} compiler is approximately
  1646. \racket{500}\python{300} lines of code.
  1647. \section{The \LangVar{} Language}
  1648. \label{sec:s0}
  1649. \index{subject}{variable}
  1650. The \LangVar{} language extends the \LangInt{} language with
  1651. variables. The concrete syntax of the \LangVar{} language is defined
  1652. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1653. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1654. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1655. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1656. \key{-} is a unary operator, and \key{+} is a binary operator.
  1657. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1658. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1659. the top of the program.
  1660. %% The $\itm{info}$
  1661. %% field of the \key{Program} structure contains an \emph{association
  1662. %% list} (a list of key-value pairs) that is used to communicate
  1663. %% auxiliary data from one compiler pass the next.
  1664. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1665. exhibit several compilation techniques.
  1666. \newcommand{\LvarGrammarRacket}{
  1667. \begin{array}{rcl}
  1668. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1669. \end{array}
  1670. }
  1671. \newcommand{\LvarASTRacket}{
  1672. \begin{array}{rcl}
  1673. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1674. \end{array}
  1675. }
  1676. \newcommand{\LvarGrammarPython}{
  1677. \begin{array}{rcl}
  1678. \Exp &::=& \Var{} \\
  1679. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1680. \end{array}
  1681. }
  1682. \newcommand{\LvarASTPython}{
  1683. \begin{array}{rcl}
  1684. \Exp{} &::=& \VAR{\Var{}} \\
  1685. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1686. \end{array}
  1687. }
  1688. \begin{figure}[tp]
  1689. \centering
  1690. \begin{tcolorbox}[colback=white]
  1691. {\if\edition\racketEd
  1692. \[
  1693. \begin{array}{l}
  1694. \gray{\LintGrammarRacket{}} \\ \hline
  1695. \LvarGrammarRacket{} \\
  1696. \begin{array}{rcl}
  1697. \LangVarM{} &::=& \Exp
  1698. \end{array}
  1699. \end{array}
  1700. \]
  1701. \fi}
  1702. {\if\edition\pythonEd\pythonColor
  1703. \[
  1704. \begin{array}{l}
  1705. \gray{\LintGrammarPython} \\ \hline
  1706. \LvarGrammarPython \\
  1707. \begin{array}{rcl}
  1708. \LangVarM{} &::=& \Stmt^{*}
  1709. \end{array}
  1710. \end{array}
  1711. \]
  1712. \fi}
  1713. \end{tcolorbox}
  1714. \caption{The concrete syntax of \LangVar{}.}
  1715. \label{fig:Lvar-concrete-syntax}
  1716. \index{subject}{Lvar@\LangVar{} concrete syntax}
  1717. \end{figure}
  1718. \begin{figure}[tp]
  1719. \centering
  1720. \begin{tcolorbox}[colback=white]
  1721. {\if\edition\racketEd
  1722. \[
  1723. \begin{array}{l}
  1724. \gray{\LintASTRacket{}} \\ \hline
  1725. \LvarASTRacket \\
  1726. \begin{array}{rcl}
  1727. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1728. \end{array}
  1729. \end{array}
  1730. \]
  1731. \fi}
  1732. {\if\edition\pythonEd\pythonColor
  1733. \[
  1734. \begin{array}{l}
  1735. \gray{\LintASTPython}\\ \hline
  1736. \LvarASTPython \\
  1737. \begin{array}{rcl}
  1738. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1739. \end{array}
  1740. \end{array}
  1741. \]
  1742. \fi}
  1743. \end{tcolorbox}
  1744. \caption{The abstract syntax of \LangVar{}.}
  1745. \label{fig:Lvar-syntax}
  1746. \index{subject}{Lvar@\LangVar{} abstract syntax}
  1747. \end{figure}
  1748. {\if\edition\racketEd
  1749. Let us dive further into the syntax and semantics of the \LangVar{}
  1750. language. The \key{let} feature defines a variable for use within its
  1751. body and initializes the variable with the value of an expression.
  1752. The abstract syntax for \key{let} is shown in
  1753. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1754. \begin{lstlisting}
  1755. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1756. \end{lstlisting}
  1757. For example, the following program initializes \code{x} to $32$ and then
  1758. evaluates the body \code{(+ 10 x)}, producing $42$.
  1759. \begin{lstlisting}
  1760. (let ([x (+ 12 20)]) (+ 10 x))
  1761. \end{lstlisting}
  1762. \fi}
  1763. %
  1764. {\if\edition\pythonEd\pythonColor
  1765. %
  1766. The \LangVar{} language includes an assignment statement, which defines a
  1767. variable for use in later statements and initializes the variable with
  1768. the value of an expression. The abstract syntax for assignment is
  1769. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1770. assignment is \index{subject}{Assign@\texttt{Assign}}
  1771. \begin{lstlisting}
  1772. |$\itm{var}$| = |$\itm{exp}$|
  1773. \end{lstlisting}
  1774. For example, the following program initializes the variable \code{x}
  1775. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1776. \begin{lstlisting}
  1777. x = 12 + 20
  1778. print(10 + x)
  1779. \end{lstlisting}
  1780. \fi}
  1781. {\if\edition\racketEd
  1782. %
  1783. When there are multiple \key{let}s for the same variable, the closest
  1784. enclosing \key{let} is used. That is, variable definitions overshadow
  1785. prior definitions. Consider the following program with two \key{let}s
  1786. that define two variables named \code{x}. Can you figure out the
  1787. result?
  1788. \begin{lstlisting}
  1789. (let ([x 32]) (+ (let ([x 10]) x) x))
  1790. \end{lstlisting}
  1791. For the purposes of depicting which variable occurrences correspond to
  1792. which definitions, the following shows the \code{x}'s annotated with
  1793. subscripts to distinguish them. Double-check that your answer for the
  1794. previous program is the same as your answer for this annotated version
  1795. of the program.
  1796. \begin{lstlisting}
  1797. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1798. \end{lstlisting}
  1799. The initializing expression is always evaluated before the body of the
  1800. \key{let}, so in the following, the \key{read} for \code{x} is
  1801. performed before the \key{read} for \code{y}. Given the input
  1802. $52$ then $10$, the following produces $42$ (not $-42$).
  1803. \begin{lstlisting}
  1804. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1805. \end{lstlisting}
  1806. \fi}
  1807. \subsection{Extensible Interpreters via Method Overriding}
  1808. \label{sec:extensible-interp}
  1809. \index{subject}{method overriding}
  1810. To prepare for discussing the interpreter of \LangVar{}, we explain
  1811. why we implement it in an object-oriented style. Throughout this book
  1812. we define many interpreters, one for each language that we
  1813. study. Because each language builds on the prior one, there is a lot
  1814. of commonality between these interpreters. We want to write down the
  1815. common parts just once instead of many times. A naive interpreter for
  1816. \LangVar{} would handle the \racket{cases for variables and
  1817. \code{let}} \python{case for variables} but dispatch to an
  1818. interpreter for \LangInt{} in the rest of the cases. The following
  1819. code sketches this idea. (We explain the \code{env} parameter in
  1820. section~\ref{sec:interp-Lvar}.)
  1821. \begin{center}
  1822. {\if\edition\racketEd
  1823. \begin{minipage}{0.45\textwidth}
  1824. \begin{lstlisting}
  1825. (define ((interp_Lint env) e)
  1826. (match e
  1827. [(Prim '- (list e1))
  1828. (fx- 0 ((interp_Lint env) e1))]
  1829. ...))
  1830. \end{lstlisting}
  1831. \end{minipage}
  1832. \begin{minipage}{0.45\textwidth}
  1833. \begin{lstlisting}
  1834. (define ((interp_Lvar env) e)
  1835. (match e
  1836. [(Var x)
  1837. (dict-ref env x)]
  1838. [(Let x e body)
  1839. (define v ((interp_Lvar env) e))
  1840. (define env^ (dict-set env x v))
  1841. ((interp_Lvar env^) body)]
  1842. [else ((interp_Lint env) e)]))
  1843. \end{lstlisting}
  1844. \end{minipage}
  1845. \fi}
  1846. {\if\edition\pythonEd\pythonColor
  1847. \begin{minipage}{0.45\textwidth}
  1848. \begin{lstlisting}
  1849. def interp_Lint(e, env):
  1850. match e:
  1851. case UnaryOp(USub(), e1):
  1852. return - interp_Lint(e1, env)
  1853. ...
  1854. \end{lstlisting}
  1855. \end{minipage}
  1856. \begin{minipage}{0.45\textwidth}
  1857. \begin{lstlisting}
  1858. def interp_Lvar(e, env):
  1859. match e:
  1860. case Name(id):
  1861. return env[id]
  1862. case _:
  1863. return interp_Lint(e, env)
  1864. \end{lstlisting}
  1865. \end{minipage}
  1866. \fi}
  1867. \end{center}
  1868. The problem with this naive approach is that it does not handle
  1869. situations in which an \LangVar{} feature, such as a variable, is
  1870. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1871. in the following program.
  1872. {\if\edition\racketEd
  1873. \begin{lstlisting}
  1874. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1875. \end{lstlisting}
  1876. \fi}
  1877. {\if\edition\pythonEd\pythonColor
  1878. \begin{minipage}{1.0\textwidth}
  1879. \begin{lstlisting}
  1880. y = 10
  1881. print(-y)
  1882. \end{lstlisting}
  1883. \end{minipage}
  1884. \fi}
  1885. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1886. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1887. then it recursively calls \code{interp\_Lint} again on its argument.
  1888. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1889. \code{interp\_Lint}, we get an error!
  1890. To make our interpreters extensible we need something called
  1891. \emph{open recursion}\index{subject}{open recursion}, in which the
  1892. tying of the recursive knot is delayed until the functions are
  1893. composed. Object-oriented languages provide open recursion via method
  1894. overriding. The following code uses
  1895. method overriding to interpret \LangInt{} and \LangVar{} using
  1896. %
  1897. \racket{the
  1898. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1899. \index{subject}{class} feature of Racket.}%
  1900. %
  1901. \python{Python \code{class} definitions.}
  1902. %
  1903. We define one class for each language and define a method for
  1904. interpreting expressions inside each class. The class for \LangVar{}
  1905. inherits from the class for \LangInt{}, and the method
  1906. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1907. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1908. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1909. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1910. \code{interp\_exp} in \LangInt{}.
  1911. \begin{center}
  1912. \hspace{-20pt}
  1913. {\if\edition\racketEd
  1914. \begin{minipage}{0.45\textwidth}
  1915. \begin{lstlisting}
  1916. (define interp-Lint-class
  1917. (class object%
  1918. (define/public ((interp_exp env) e)
  1919. (match e
  1920. [(Prim '- (list e))
  1921. (fx- 0 ((interp_exp env) e))]
  1922. ...))
  1923. ...))
  1924. \end{lstlisting}
  1925. \end{minipage}
  1926. \begin{minipage}{0.45\textwidth}
  1927. \begin{lstlisting}
  1928. (define interp-Lvar-class
  1929. (class interp-Lint-class
  1930. (define/override ((interp_exp env) e)
  1931. (match e
  1932. [(Var x)
  1933. (dict-ref env x)]
  1934. [(Let x e body)
  1935. (define v ((interp_exp env) e))
  1936. (define env^ (dict-set env x v))
  1937. ((interp_exp env^) body)]
  1938. [else
  1939. ((super interp_exp env) e)]))
  1940. ...
  1941. ))
  1942. \end{lstlisting}
  1943. \end{minipage}
  1944. \fi}
  1945. {\if\edition\pythonEd\pythonColor
  1946. \begin{minipage}{0.45\textwidth}
  1947. \begin{lstlisting}
  1948. class InterpLint:
  1949. def interp_exp(e):
  1950. match e:
  1951. case UnaryOp(USub(), e1):
  1952. return neg64(self.interp_exp(e1))
  1953. ...
  1954. ...
  1955. \end{lstlisting}
  1956. \end{minipage}
  1957. \begin{minipage}{0.45\textwidth}
  1958. \begin{lstlisting}
  1959. def InterpLvar(InterpLint):
  1960. def interp_exp(e):
  1961. match e:
  1962. case Name(id):
  1963. return env[id]
  1964. case _:
  1965. return super().interp_exp(e)
  1966. ...
  1967. \end{lstlisting}
  1968. \end{minipage}
  1969. \fi}
  1970. \end{center}
  1971. We return to the troublesome example, repeated here:
  1972. {\if\edition\racketEd
  1973. \begin{lstlisting}
  1974. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1975. \end{lstlisting}
  1976. \fi}
  1977. {\if\edition\pythonEd\pythonColor
  1978. \begin{lstlisting}
  1979. y = 10
  1980. print(-y)
  1981. \end{lstlisting}
  1982. \fi}
  1983. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1984. \racket{on this expression,}%
  1985. \python{on the \code{-y} expression,}
  1986. %
  1987. which we call \code{e0}, by creating an object of the \LangVar{} class
  1988. and calling the \code{interp\_exp} method
  1989. {\if\edition\racketEd
  1990. \begin{lstlisting}
  1991. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1992. \end{lstlisting}
  1993. \fi}
  1994. {\if\edition\pythonEd\pythonColor
  1995. \begin{lstlisting}
  1996. InterpLvar().interp_exp(e0)
  1997. \end{lstlisting}
  1998. \fi}
  1999. \noindent To process the \code{-} operator, the default case of
  2000. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  2001. method in \LangInt{}. But then for the recursive method call, it
  2002. dispatches to \code{interp\_exp} in \LangVar{}, where the
  2003. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  2004. Thus, method overriding gives us the open recursion that we need to
  2005. implement our interpreters in an extensible way.
  2006. \subsection{Definitional Interpreter for \LangVar{}}
  2007. \label{sec:interp-Lvar}
  2008. Having justified the use of classes and methods to implement
  2009. interpreters, we revisit the definitional interpreter for \LangInt{}
  2010. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  2011. create an interpreter for \LangVar{}, shown in
  2012. figure~\ref{fig:interp-Lvar}.
  2013. %
  2014. \python{We change the \code{interp\_stmt} method in the interpreter
  2015. for \LangInt{} to take two extra parameters named \code{env}, which
  2016. we discuss in the next paragraph, and \code{cont} for
  2017. \emph{continuation}, which is the technical name for what comes
  2018. after a particular point in a program. The \code{cont} parameter is
  2019. the list of statements that follow the current statement. Note
  2020. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  2021. statement and passes the rest of the statements as the argument for
  2022. \code{cont}. This organization enables each statement to decide what
  2023. if anything should be evaluated after it, for example, allowing a
  2024. \code{return} statement to exit early from a function (see
  2025. Chapter~\ref{ch:Lfun}).}
  2026. The interpreter for \LangVar{} adds two new cases for
  2027. variables and \racket{\key{let}}\python{assignment}. For
  2028. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2029. value bound to a variable to all the uses of the variable. To
  2030. accomplish this, we maintain a mapping from variables to values called
  2031. an \emph{environment}\index{subject}{environment}.
  2032. %
  2033. We use
  2034. %
  2035. \racket{an association list (alist) }%
  2036. %
  2037. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2038. %
  2039. to represent the environment.
  2040. %
  2041. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2042. and the \code{racket/dict} package.}
  2043. %
  2044. The \code{interp\_exp} function takes the current environment,
  2045. \code{env}, as an extra parameter. When the interpreter encounters a
  2046. variable, it looks up the corresponding value in the environment. If
  2047. the variable is not in the environment (because the variable was not
  2048. defined) then the lookup will fail and the interpreter will
  2049. halt with an error. Recall that the compiler is not obligated to
  2050. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2051. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2052. prohibit access to undefined variables.}
  2053. %
  2054. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2055. initializing expression, extends the environment with the result
  2056. value bound to the variable, using \code{dict-set}, then evaluates
  2057. the body of the \key{Let}.}
  2058. %
  2059. \python{When the interpreter encounters an assignment, it evaluates
  2060. the initializing expression and then associates the resulting value
  2061. with the variable in the environment.}
  2062. \begin{figure}[tp]
  2063. \begin{tcolorbox}[colback=white]
  2064. {\if\edition\racketEd
  2065. \begin{lstlisting}
  2066. (define interp-Lint-class
  2067. (class object%
  2068. (super-new)
  2069. (define/public ((interp_exp env) e)
  2070. (match e
  2071. [(Int n) n]
  2072. [(Prim 'read '())
  2073. (define r (read))
  2074. (cond [(fixnum? r) r]
  2075. [else (error 'interp_exp "expected an integer" r)])]
  2076. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2077. [(Prim '+ (list e1 e2))
  2078. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2079. [(Prim '- (list e1 e2))
  2080. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2081. (define/public (interp_program p)
  2082. (match p
  2083. [(Program '() e) ((interp_exp '()) e)]))
  2084. ))
  2085. \end{lstlisting}
  2086. \fi}
  2087. {\if\edition\pythonEd\pythonColor
  2088. \begin{lstlisting}
  2089. class InterpLint:
  2090. def interp_exp(self, e, env):
  2091. match e:
  2092. case BinOp(left, Add(), right):
  2093. l = self.interp_exp(left, env)
  2094. r = self.interp_exp(right, env)
  2095. return add64(l, r)
  2096. case BinOp(left, Sub(), right):
  2097. l = self.interp_exp(left, env)
  2098. r = self.interp_exp(right, env)
  2099. return sub64(l, r)
  2100. case UnaryOp(USub(), v):
  2101. return neg64(self.interp_exp(v, env))
  2102. case Constant(value):
  2103. return value
  2104. case Call(Name('input_int'), []):
  2105. return int(input())
  2106. def interp_stmt(self, s, env, cont):
  2107. match s:
  2108. case Expr(Call(Name('print'), [arg])):
  2109. val = self.interp_exp(arg, env)
  2110. print(val, end='')
  2111. return self.interp_stmts(cont, env)
  2112. case Expr(value):
  2113. self.interp_exp(value, env)
  2114. return self.interp_stmts(cont, env)
  2115. case _:
  2116. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2117. def interp_stmts(self, ss, env):
  2118. match ss:
  2119. case []:
  2120. return 0
  2121. case [s, *ss]:
  2122. return self.interp_stmt(s, env, ss)
  2123. def interp(self, p):
  2124. match p:
  2125. case Module(body):
  2126. self.interp_stmts(body, {})
  2127. def interp_Lint(p):
  2128. return InterpLint().interp(p)
  2129. \end{lstlisting}
  2130. \fi}
  2131. \end{tcolorbox}
  2132. \caption{Interpreter for \LangInt{} as a class.}
  2133. \label{fig:interp-Lint-class}
  2134. \end{figure}
  2135. \begin{figure}[tp]
  2136. \begin{tcolorbox}[colback=white]
  2137. {\if\edition\racketEd
  2138. \begin{lstlisting}
  2139. (define interp-Lvar-class
  2140. (class interp-Lint-class
  2141. (super-new)
  2142. (define/override ((interp_exp env) e)
  2143. (match e
  2144. [(Var x) (dict-ref env x)]
  2145. [(Let x e body)
  2146. (define new-env (dict-set env x ((interp_exp env) e)))
  2147. ((interp_exp new-env) body)]
  2148. [else ((super interp_exp env) e)]))
  2149. ))
  2150. (define (interp_Lvar p)
  2151. (send (new interp-Lvar-class) interp_program p))
  2152. \end{lstlisting}
  2153. \fi}
  2154. {\if\edition\pythonEd\pythonColor
  2155. \begin{lstlisting}
  2156. class InterpLvar(InterpLint):
  2157. def interp_exp(self, e, env):
  2158. match e:
  2159. case Name(id):
  2160. return env[id]
  2161. case _:
  2162. return super().interp_exp(e, env)
  2163. def interp_stmt(self, s, env, cont):
  2164. match s:
  2165. case Assign([Name(id)], value):
  2166. env[id] = self.interp_exp(value, env)
  2167. return self.interp_stmts(cont, env)
  2168. case _:
  2169. return super().interp_stmt(s, env, cont)
  2170. def interp_Lvar(p):
  2171. return InterpLvar().interp(p)
  2172. \end{lstlisting}
  2173. \fi}
  2174. \end{tcolorbox}
  2175. \caption{Interpreter for the \LangVar{} language.}
  2176. \label{fig:interp-Lvar}
  2177. \end{figure}
  2178. {\if\edition\racketEd
  2179. \begin{figure}[tp]
  2180. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2181. \small
  2182. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2183. An \emph{association list} (called an alist) is a list of key-value pairs.
  2184. For example, we can map people to their ages with an alist
  2185. \index{subject}{alist}\index{subject}{association list}
  2186. \begin{lstlisting}[basicstyle=\ttfamily]
  2187. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2188. \end{lstlisting}
  2189. The \emph{dictionary} interface is for mapping keys to values.
  2190. Every alist implements this interface. \index{subject}{dictionary}
  2191. The package
  2192. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2193. provides many functions for working with dictionaries, such as
  2194. \begin{description}
  2195. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2196. returns the value associated with the given $\itm{key}$.
  2197. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2198. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2199. and otherwise is the same as $\itm{dict}$.
  2200. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2201. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2202. of keys and values in $\itm{dict}$. For example, the following
  2203. creates a new alist in which the ages are incremented:
  2204. \end{description}
  2205. \vspace{-10pt}
  2206. \begin{lstlisting}[basicstyle=\ttfamily]
  2207. (for/list ([(k v) (in-dict ages)])
  2208. (cons k (add1 v)))
  2209. \end{lstlisting}
  2210. \end{tcolorbox}
  2211. %\end{wrapfigure}
  2212. \caption{Association lists implement the dictionary interface.}
  2213. \label{fig:alist}
  2214. \end{figure}
  2215. \fi}
  2216. The goal for this chapter is to implement a compiler that translates
  2217. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2218. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2219. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2220. That is, they output the same integer $n$. We depict this correctness
  2221. criteria in the following diagram:
  2222. \[
  2223. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2224. \node (p1) at (0, 0) {$P_1$};
  2225. \node (p2) at (4, 0) {$P_2$};
  2226. \node (o) at (4, -2) {$n$};
  2227. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2228. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2229. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2230. \end{tikzpicture}
  2231. \]
  2232. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2233. compiling \LangVar{}.
  2234. \section{The \LangXInt{} Assembly Language}
  2235. \label{sec:x86}
  2236. \index{subject}{x86}
  2237. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2238. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2239. assembler.
  2240. %
  2241. A program begins with a \code{main} label followed by a sequence of
  2242. instructions. The \key{globl} directive makes the \key{main} procedure
  2243. externally visible so that the operating system can call it.
  2244. %
  2245. An x86 program is stored in the computer's memory. For our purposes,
  2246. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2247. values. The computer has a \emph{program counter}
  2248. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2249. \code{rip} register that points to the address of the next instruction
  2250. to be executed. For most instructions, the program counter is
  2251. incremented after the instruction is executed so that it points to the
  2252. next instruction in memory. Most x86 instructions take two operands,
  2253. each of which is an integer constant (called an \emph{immediate
  2254. value}\index{subject}{immediate value}), a
  2255. \emph{register}\index{subject}{register}, or a memory location.
  2256. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2257. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2258. && \key{r8} \MID \key{r9} \MID \key{r10}
  2259. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2260. \MID \key{r14} \MID \key{r15}}
  2261. \newcommand{\GrammarXInt}{
  2262. \begin{array}{rcl}
  2263. \Reg &::=& \allregisters{} \\
  2264. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2265. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2266. \key{subq} \; \Arg\key{,} \Arg \MID
  2267. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2268. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2269. \key{callq} \; \mathit{label} \MID
  2270. \key{retq} \MID
  2271. \key{jmp}\,\itm{label} \MID \\
  2272. && \itm{label}\key{:}\; \Instr
  2273. \end{array}
  2274. }
  2275. \begin{figure}[tp]
  2276. \begin{tcolorbox}[colback=white]
  2277. {\if\edition\racketEd
  2278. \[
  2279. \begin{array}{l}
  2280. \GrammarXInt \\
  2281. \begin{array}{lcl}
  2282. \LangXIntM{} &::= & \key{.globl main}\\
  2283. & & \key{main:} \; \Instr\ldots
  2284. \end{array}
  2285. \end{array}
  2286. \]
  2287. \fi}
  2288. {\if\edition\pythonEd\pythonColor
  2289. \[
  2290. \begin{array}{lcl}
  2291. \Reg &::=& \allregisters{} \\
  2292. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2293. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2294. \key{subq} \; \Arg\key{,} \Arg \MID
  2295. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2296. && \key{callq} \; \mathit{label} \MID
  2297. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2298. \LangXIntM{} &::= & \key{.globl main}\\
  2299. & & \key{main:} \; \Instr^{*}
  2300. \end{array}
  2301. \]
  2302. \fi}
  2303. \end{tcolorbox}
  2304. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2305. \label{fig:x86-int-concrete}
  2306. \index{subject}{x86int@\LangXInt{} concrete syntax}
  2307. \end{figure}
  2308. A register is a special kind of variable that holds a 64-bit
  2309. value. There are 16 general-purpose registers in the computer; their
  2310. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2311. written with a percent sign, \key{\%}, followed by its name,
  2312. for example, \key{\%rax}.
  2313. An immediate value is written using the notation \key{\$}$n$ where $n$
  2314. is an integer.
  2315. %
  2316. %
  2317. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2318. which obtains the address stored in register $r$ and then adds $n$
  2319. bytes to the address. The resulting address is used to load or to store
  2320. to memory depending on whether it occurs as a source or destination
  2321. argument of an instruction.
  2322. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2323. the source $s$ and destination $d$, applies the arithmetic operation,
  2324. and then writes the result to the destination $d$. \index{subject}{instruction}
  2325. %
  2326. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2327. stores the result in $d$.
  2328. %
  2329. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2330. specified by the label, and $\key{retq}$ returns from a procedure to
  2331. its caller.
  2332. %
  2333. We discuss procedure calls in more detail further in this chapter and
  2334. in chapter~\ref{ch:Lfun}.
  2335. %
  2336. The last letter \key{q} indicates that these instructions operate on
  2337. quadwords, which are 64-bit values.
  2338. %
  2339. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2340. counter to the address of the instruction immediately after the
  2341. specified label.}
  2342. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2343. all the x86 instructions used in this book.
  2344. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2345. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2346. \lstinline{movq $10, %rax}
  2347. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2348. adds $32$ to the $10$ in \key{rax} and
  2349. puts the result, $42$, into \key{rax}.
  2350. %
  2351. The last instruction \key{retq} finishes the \key{main} function by
  2352. returning the integer in \key{rax} to the operating system. The
  2353. operating system interprets this integer as the program's exit
  2354. code. By convention, an exit code of 0 indicates that a program has
  2355. completed successfully, and all other exit codes indicate various
  2356. errors.
  2357. %
  2358. \racket{However, in this book we return the result of the program
  2359. as the exit code.}
  2360. \begin{figure}[tbp]
  2361. \begin{minipage}{0.45\textwidth}
  2362. \begin{tcolorbox}[colback=white]
  2363. \begin{lstlisting}
  2364. .globl main
  2365. main:
  2366. movq $10, %rax
  2367. addq $32, %rax
  2368. retq
  2369. \end{lstlisting}
  2370. \end{tcolorbox}
  2371. \end{minipage}
  2372. \caption{An x86 program that computes
  2373. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2374. \label{fig:p0-x86}
  2375. \end{figure}
  2376. We exhibit the use of memory for storing intermediate results in the
  2377. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2378. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2379. uses a region of memory called the \emph{procedure call stack}
  2380. (\emph{stack} for
  2381. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2382. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2383. for each procedure call. The memory layout for an individual frame is
  2384. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2385. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2386. address of the item at the top of the stack. In general, we use the
  2387. term \emph{pointer}\index{subject}{pointer} for something that
  2388. contains an address. The stack grows downward in memory, so we
  2389. increase the size of the stack by subtracting from the stack pointer.
  2390. In the context of a procedure call, the \emph{return
  2391. address}\index{subject}{return address} is the location of the
  2392. instruction that immediately follows the call instruction on the
  2393. caller side. The function call instruction, \code{callq}, pushes the
  2394. return address onto the stack prior to jumping to the procedure. The
  2395. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2396. pointer} and is used to access variables that are stored in the
  2397. frame of the current procedure call. The base pointer of the caller
  2398. is stored immediately after the return address.
  2399. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2400. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2401. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2402. $-16\key{(\%rbp)}$, and so on.
  2403. \begin{figure}[tbp]
  2404. \begin{minipage}{0.66\textwidth}
  2405. \begin{tcolorbox}[colback=white]
  2406. {\if\edition\racketEd
  2407. \begin{lstlisting}
  2408. start:
  2409. movq $10, -8(%rbp)
  2410. negq -8(%rbp)
  2411. movq -8(%rbp), %rax
  2412. addq $52, %rax
  2413. jmp conclusion
  2414. .globl main
  2415. main:
  2416. pushq %rbp
  2417. movq %rsp, %rbp
  2418. subq $16, %rsp
  2419. jmp start
  2420. conclusion:
  2421. addq $16, %rsp
  2422. popq %rbp
  2423. retq
  2424. \end{lstlisting}
  2425. \fi}
  2426. {\if\edition\pythonEd\pythonColor
  2427. \begin{lstlisting}
  2428. .globl main
  2429. main:
  2430. pushq %rbp
  2431. movq %rsp, %rbp
  2432. subq $16, %rsp
  2433. movq $10, -8(%rbp)
  2434. negq -8(%rbp)
  2435. movq -8(%rbp), %rax
  2436. addq $52, %rax
  2437. addq $16, %rsp
  2438. popq %rbp
  2439. retq
  2440. \end{lstlisting}
  2441. \fi}
  2442. \end{tcolorbox}
  2443. \end{minipage}
  2444. \caption{An x86 program that computes
  2445. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2446. \label{fig:p1-x86}
  2447. \end{figure}
  2448. \begin{figure}[tbp]
  2449. \begin{minipage}{0.66\textwidth}
  2450. \begin{tcolorbox}[colback=white]
  2451. \centering
  2452. \begin{tabular}{|r|l|} \hline
  2453. Position & Contents \\ \hline
  2454. $8$(\key{\%rbp}) & return address \\
  2455. $0$(\key{\%rbp}) & old \key{rbp} \\
  2456. $-8$(\key{\%rbp}) & variable $1$ \\
  2457. $-16$(\key{\%rbp}) & variable $2$ \\
  2458. \ldots & \ldots \\
  2459. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2460. \end{tabular}
  2461. \end{tcolorbox}
  2462. \end{minipage}
  2463. \caption{Memory layout of a frame.}
  2464. \label{fig:frame}
  2465. \end{figure}
  2466. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2467. is transferred from the operating system to the \code{main} function.
  2468. The operating system issues a \code{callq main} instruction that
  2469. pushes its return address on the stack and then jumps to
  2470. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2471. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2472. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2473. out of alignment (because the \code{callq} pushed the return address).
  2474. The first three instructions are the typical
  2475. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2476. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2477. pointer \code{rsp} and then saves the base pointer of the caller at
  2478. address \code{rsp} on the stack. The next instruction \code{movq
  2479. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2480. which is pointing to the location of the old base pointer. The
  2481. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2482. make enough room for storing variables. This program needs one
  2483. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2484. 16-byte-aligned, and then we are ready to make calls to other functions.
  2485. \racket{The last instruction of the prelude is \code{jmp start}, which
  2486. transfers control to the instructions that were generated from the
  2487. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2488. \racket{The first instruction under the \code{start} label is}
  2489. %
  2490. \python{The first instruction after the prelude is}
  2491. %
  2492. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2493. %
  2494. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2495. $1$ to $-10$.
  2496. %
  2497. The next instruction moves the $-10$ from variable $1$ into the
  2498. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2499. the value in \code{rax}, updating its contents to $42$.
  2500. \racket{The three instructions under the label \code{conclusion} are the
  2501. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2502. %
  2503. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2504. \code{main} function consists of the last three instructions.}
  2505. %
  2506. The first two restore the \code{rsp} and \code{rbp} registers to their
  2507. states at the beginning of the procedure. In particular,
  2508. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2509. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2510. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2511. \key{retq}, jumps back to the procedure that called this one and adds
  2512. $8$ to the stack pointer.
  2513. Our compiler needs a convenient representation for manipulating x86
  2514. programs, so we define an abstract syntax for x86, shown in
  2515. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2516. \LangXInt{}.
  2517. %
  2518. {\if\edition\pythonEd\pythonColor%
  2519. The main difference between this and the concrete syntax of \LangXInt{}
  2520. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2521. names, and register names are explicitly represented by strings.
  2522. \fi} %
  2523. {\if\edition\racketEd
  2524. The main difference between this and the concrete syntax of \LangXInt{}
  2525. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2526. front of every instruction. Instead instructions are grouped into
  2527. \emph{basic blocks}\index{subject}{basic block} with a
  2528. label associated with every basic block; this is why the \key{X86Program}
  2529. struct includes an alist mapping labels to basic blocks. The reason for this
  2530. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2531. introduce conditional branching. The \code{Block} structure includes
  2532. an $\itm{info}$ field that is not needed in this chapter but becomes
  2533. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2534. $\itm{info}$ field should contain an empty list.
  2535. \fi}
  2536. %
  2537. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2538. node includes an integer for representing the arity of the function,
  2539. that is, the number of arguments, which is helpful to know during
  2540. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2541. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2542. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2543. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2544. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2545. \MID \skey{r14} \MID \skey{r15}}
  2546. \newcommand{\ASTXIntRacket}{
  2547. \begin{array}{lcl}
  2548. \Reg &::=& \allregisters{} \\
  2549. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2550. \MID \DEREF{\Reg}{\Int} \\
  2551. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2552. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2553. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2554. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2555. &\MID& \PUSHQ{\Arg}
  2556. \MID \POPQ{\Arg} \\
  2557. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2558. \MID \RETQ{}
  2559. \MID \JMP{\itm{label}} \\
  2560. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2561. \end{array}
  2562. }
  2563. \newcommand{\ASTXIntPython}{
  2564. \begin{array}{lcl}
  2565. \Reg &::=& \allregisters{} \\
  2566. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2567. \MID \DEREF{\Reg}{\Int} \\
  2568. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2569. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2570. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2571. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2572. &\MID& \PUSHQ{\Arg}
  2573. \MID \POPQ{\Arg} \\
  2574. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2575. \MID \RETQ{}
  2576. \MID \JMP{\itm{label}} \\
  2577. \Block &::= & \Instr^{+}
  2578. \end{array}
  2579. }
  2580. \begin{figure}[tp]
  2581. \begin{tcolorbox}[colback=white]
  2582. \small
  2583. {\if\edition\racketEd
  2584. \[\arraycolsep=3pt
  2585. \begin{array}{l}
  2586. \ASTXIntRacket \\
  2587. \begin{array}{lcl}
  2588. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2589. \end{array}
  2590. \end{array}
  2591. \]
  2592. \fi}
  2593. {\if\edition\pythonEd\pythonColor
  2594. \[
  2595. \begin{array}{lcl}
  2596. \Reg &::=& \allastregisters{} \\
  2597. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2598. \MID \DEREF{\Reg}{\Int} \\
  2599. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2600. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2601. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2602. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2603. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2604. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2605. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2606. \end{array}
  2607. \]
  2608. \fi}
  2609. \end{tcolorbox}
  2610. \caption{The abstract syntax of \LangXInt{} assembly.}
  2611. \label{fig:x86-int-ast}
  2612. \index{subject}{x86int@\LangXInt{} abstract syntax}
  2613. \end{figure}
  2614. \section{Planning the Trip to x86}
  2615. \label{sec:plan-s0-x86}
  2616. To compile one language to another, it helps to focus on the
  2617. differences between the two languages because the compiler will need
  2618. to bridge those differences. What are the differences between \LangVar{}
  2619. and x86 assembly? Here are some of the most important ones:
  2620. \begin{enumerate}
  2621. \item x86 arithmetic instructions typically have two arguments and
  2622. update the second argument in place. In contrast, \LangVar{}
  2623. arithmetic operations take two arguments and produce a new value.
  2624. An x86 instruction may have at most one memory-accessing argument.
  2625. Furthermore, some x86 instructions place special restrictions on
  2626. their arguments.
  2627. \item An argument of an \LangVar{} operator can be a deeply nested
  2628. expression, whereas x86 instructions restrict their arguments to be
  2629. integer constants, registers, and memory locations.
  2630. {\if\edition\racketEd
  2631. \item The order of execution in x86 is explicit in the syntax, which
  2632. is a sequence of instructions and jumps to labeled positions,
  2633. whereas in \LangVar{} the order of evaluation is a left-to-right
  2634. depth-first traversal of the abstract syntax tree. \fi}
  2635. \item A program in \LangVar{} can have any number of variables,
  2636. whereas x86 has 16 registers and the procedure call stack.
  2637. {\if\edition\racketEd
  2638. \item Variables in \LangVar{} can shadow other variables with the
  2639. same name. In x86, registers have unique names, and memory locations
  2640. have unique addresses.
  2641. \fi}
  2642. \end{enumerate}
  2643. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2644. down the problem into several steps, which deal with these differences
  2645. one at a time. Each of these steps is called a \emph{pass} of the
  2646. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2647. %
  2648. This term indicates that each step passes over, or traverses, the AST
  2649. of the program.
  2650. %
  2651. Furthermore, we follow the nanopass approach, which means that we
  2652. strive for each pass to accomplish one clear objective rather than two
  2653. or three at the same time.
  2654. %
  2655. We begin by sketching how we might implement each pass and give each
  2656. pass a name. We then figure out an ordering of the passes and the
  2657. input/output language for each pass. The very first pass has
  2658. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2659. its output language. In between these two passes, we can choose
  2660. whichever language is most convenient for expressing the output of
  2661. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2662. \emph{intermediate language} of our own design. Finally, to
  2663. implement each pass we write one recursive function per nonterminal in
  2664. the grammar of the input language of the pass.
  2665. \index{subject}{intermediate language}
  2666. Our compiler for \LangVar{} consists of the following passes:
  2667. %
  2668. \begin{description}
  2669. {\if\edition\racketEd
  2670. \item[\key{uniquify}] deals with the shadowing of variables by
  2671. renaming every variable to a unique name.
  2672. \fi}
  2673. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2674. of a primitive operation or function call is a variable or integer,
  2675. that is, an \emph{atomic} expression. We refer to nonatomic
  2676. expressions as \emph{complex}. This pass introduces temporary
  2677. variables to hold the results of complex
  2678. subexpressions.\index{subject}{atomic
  2679. expression}\index{subject}{complex expression}%
  2680. {\if\edition\racketEd
  2681. \item[\key{explicate\_control}] makes the execution order of the
  2682. program explicit. It converts the abstract syntax tree
  2683. representation into a graph in which each node is a labeled sequence
  2684. of statements and the edges are \code{goto} statements.
  2685. \fi}
  2686. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2687. handles the difference between
  2688. \LangVar{} operations and x86 instructions. This pass converts each
  2689. \LangVar{} operation to a short sequence of instructions that
  2690. accomplishes the same task.
  2691. \item[\key{assign\_homes}] replaces variables with registers or stack
  2692. locations.
  2693. \end{description}
  2694. %
  2695. {\if\edition\racketEd
  2696. %
  2697. Our treatment of \code{remove\_complex\_operands} and
  2698. \code{explicate\_control} as separate passes is an example of the
  2699. nanopass approach.\footnote{For analogous decompositions of the
  2700. translation into continuation passing style, see the work of
  2701. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2702. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2703. %
  2704. \fi}
  2705. The next question is, in what order should we apply these passes? This
  2706. question can be challenging because it is difficult to know ahead of
  2707. time which orderings will be better (that is, will be easier to
  2708. implement, produce more efficient code, and so on), and therefore
  2709. ordering often involves trial and error. Nevertheless, we can plan
  2710. ahead and make educated choices regarding the ordering.
  2711. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2712. \key{uniquify}? The \key{uniquify} pass should come first because
  2713. \key{explicate\_control} changes all the \key{let}-bound variables to
  2714. become local variables whose scope is the entire program, which would
  2715. confuse variables with the same name.}
  2716. %
  2717. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2718. because the latter removes the \key{let} form, but it is convenient to
  2719. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2720. %
  2721. \racket{The ordering of \key{uniquify} with respect to
  2722. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2723. \key{uniquify} to come first.}
  2724. The \key{select\_instructions} and \key{assign\_homes} passes are
  2725. intertwined.
  2726. %
  2727. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2728. passing arguments to functions and that it is preferable to assign
  2729. parameters to their corresponding registers. This suggests that it
  2730. would be better to start with the \key{select\_instructions} pass,
  2731. which generates the instructions for argument passing, before
  2732. performing register allocation.
  2733. %
  2734. On the other hand, by selecting instructions first we may run into a
  2735. dead end in \key{assign\_homes}. Recall that only one argument of an
  2736. x86 instruction may be a memory access, but \key{assign\_homes} might
  2737. be forced to assign both arguments to memory locations.
  2738. %
  2739. A sophisticated approach is to repeat the two passes until a solution
  2740. is found. However, to reduce implementation complexity we recommend
  2741. placing \key{select\_instructions} first, followed by the
  2742. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2743. that uses a reserved register to fix outstanding problems.
  2744. \begin{figure}[tbp]
  2745. \begin{tcolorbox}[colback=white]
  2746. {\if\edition\racketEd
  2747. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2748. \node (Lvar) at (0,2) {\large \LangVar{}};
  2749. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2750. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2751. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2752. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2753. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2754. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2755. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2756. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2757. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2758. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2759. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2760. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2761. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2762. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2763. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2764. \end{tikzpicture}
  2765. \fi}
  2766. {\if\edition\pythonEd\pythonColor
  2767. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2768. \node (Lvar) at (0,2) {\large \LangVar{}};
  2769. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2770. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2771. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2772. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2773. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2774. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2775. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2776. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2777. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2778. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2779. \end{tikzpicture}
  2780. \fi}
  2781. \end{tcolorbox}
  2782. \caption{Diagram of the passes for compiling \LangVar{}. }
  2783. \label{fig:Lvar-passes}
  2784. \end{figure}
  2785. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2786. passes and identifies the input and output language of each pass.
  2787. %
  2788. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2789. language, which extends \LangXInt{} with an unbounded number of
  2790. program-scope variables and removes the restrictions regarding
  2791. instruction arguments.
  2792. %
  2793. The last pass, \key{prelude\_and\_conclusion}, places the program
  2794. instructions inside a \code{main} function with instructions for the
  2795. prelude and conclusion.
  2796. %
  2797. \racket{In the next section we discuss the \LangCVar{} intermediate
  2798. language that serves as the output of \code{explicate\_control}.}
  2799. %
  2800. The remainder of this chapter provides guidance on the implementation
  2801. of each of the compiler passes represented in
  2802. figure~\ref{fig:Lvar-passes}.
  2803. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2804. %% are programs that are still in the \LangVar{} language, though the
  2805. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2806. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2807. %% %
  2808. %% The output of \code{explicate\_control} is in an intermediate language
  2809. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2810. %% syntax, which we introduce in the next section. The
  2811. %% \key{select-instruction} pass translates from \LangCVar{} to
  2812. %% \LangXVar{}. The \key{assign-homes} and
  2813. %% \key{patch-instructions}
  2814. %% passes input and output variants of x86 assembly.
  2815. \newcommand{\CvarGrammarRacket}{
  2816. \begin{array}{lcl}
  2817. \Atm &::=& \Int \MID \Var \\
  2818. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2819. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2820. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2821. \end{array}
  2822. }
  2823. \newcommand{\CvarASTRacket}{
  2824. \begin{array}{lcl}
  2825. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2826. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2827. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2828. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2829. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2830. \end{array}
  2831. }
  2832. {\if\edition\racketEd
  2833. \subsection{The \LangCVar{} Intermediate Language}
  2834. The output of \code{explicate\_control} is similar to the C
  2835. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2836. categories for expressions and statements, so we name it \LangCVar{}.
  2837. This style of intermediate language is also known as
  2838. \emph{three-address code}, to emphasize that the typical form of a
  2839. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2840. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2841. The concrete syntax for \LangCVar{} is shown in
  2842. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2843. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2844. %
  2845. The \LangCVar{} language supports the same operators as \LangVar{} but
  2846. the arguments of operators are restricted to atomic
  2847. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2848. assignment statements that can be executed in sequence using the
  2849. \key{Seq} form. A sequence of statements always ends with
  2850. \key{Return}, a guarantee that is baked into the grammar rules for
  2851. \itm{tail}. The naming of this nonterminal comes from the term
  2852. \emph{tail position}\index{subject}{tail position}, which refers to an
  2853. expression that is the last one to execute within a function or
  2854. program.
  2855. A \LangCVar{} program consists of an alist mapping labels to
  2856. tails. This is more general than necessary for the present chapter, as
  2857. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2858. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2859. there is just one label, \key{start}, and the whole program is
  2860. its tail.
  2861. %
  2862. The $\itm{info}$ field of the \key{CProgram} form, after the
  2863. \code{explicate\_control} pass, contains an alist that associates the
  2864. symbol \key{locals} with a list of all the variables used in the
  2865. program. At the start of the program, these variables are
  2866. uninitialized; they become initialized on their first assignment.
  2867. \begin{figure}[tbp]
  2868. \begin{tcolorbox}[colback=white]
  2869. \[
  2870. \begin{array}{l}
  2871. \CvarGrammarRacket \\
  2872. \begin{array}{lcl}
  2873. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2874. \end{array}
  2875. \end{array}
  2876. \]
  2877. \end{tcolorbox}
  2878. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2879. \label{fig:c0-concrete-syntax}
  2880. \index{subject}{Cvar@\LangCVar{} concrete syntax}
  2881. \end{figure}
  2882. \begin{figure}[tbp]
  2883. \begin{tcolorbox}[colback=white]
  2884. \[
  2885. \begin{array}{l}
  2886. \CvarASTRacket \\
  2887. \begin{array}{lcl}
  2888. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2889. \end{array}
  2890. \end{array}
  2891. \]
  2892. \end{tcolorbox}
  2893. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2894. \label{fig:c0-syntax}
  2895. \index{subject}{Cvar@\LangCVar{} abstract syntax}
  2896. \end{figure}
  2897. The definitional interpreter for \LangCVar{} is in the support code,
  2898. in the file \code{interp-Cvar.rkt}.
  2899. \fi}
  2900. {\if\edition\racketEd
  2901. \section{Uniquify Variables}
  2902. \label{sec:uniquify-Lvar}
  2903. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2904. with a unique name. Both the input and output of the \code{uniquify}
  2905. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2906. should translate the program on the left into the program on the
  2907. right.
  2908. \begin{transformation}
  2909. \begin{lstlisting}
  2910. (let ([x 32])
  2911. (+ (let ([x 10]) x) x))
  2912. \end{lstlisting}
  2913. \compilesto
  2914. \begin{lstlisting}
  2915. (let ([x.1 32])
  2916. (+ (let ([x.2 10]) x.2) x.1))
  2917. \end{lstlisting}
  2918. \end{transformation}
  2919. The following is another example translation, this time of a program
  2920. with a \key{let} nested inside the initializing expression of another
  2921. \key{let}.
  2922. \begin{transformation}
  2923. \begin{lstlisting}
  2924. (let ([x (let ([x 4])
  2925. (+ x 1))])
  2926. (+ x 2))
  2927. \end{lstlisting}
  2928. \compilesto
  2929. \begin{lstlisting}
  2930. (let ([x.2 (let ([x.1 4])
  2931. (+ x.1 1))])
  2932. (+ x.2 2))
  2933. \end{lstlisting}
  2934. \end{transformation}
  2935. We recommend implementing \code{uniquify} by creating a structurally
  2936. recursive function named \code{uniquify\_exp} that does little other
  2937. than copy an expression. However, when encountering a \key{let}, it
  2938. should generate a unique name for the variable and associate the old
  2939. name with the new name in an alist.\footnote{The Racket function
  2940. \code{gensym} is handy for generating unique variable names.} The
  2941. \code{uniquify\_exp} function needs to access this alist when it gets
  2942. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2943. for the alist.
  2944. The skeleton of the \code{uniquify\_exp} function is shown in
  2945. figure~\ref{fig:uniquify-Lvar}.
  2946. %% The function is curried so that it is
  2947. %% convenient to partially apply it to an alist and then apply it to
  2948. %% different expressions, as in the last case for primitive operations in
  2949. %% figure~\ref{fig:uniquify-Lvar}.
  2950. The
  2951. %
  2952. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2953. %
  2954. form of Racket is useful for transforming the element of a list to
  2955. produce a new list.\index{subject}{for/list}
  2956. \begin{figure}[tbp]
  2957. \begin{tcolorbox}[colback=white]
  2958. \begin{lstlisting}
  2959. (define (uniquify_exp env)
  2960. (lambda (e)
  2961. (match e
  2962. [(Var x) ___]
  2963. [(Int n) (Int n)]
  2964. [(Let x e body) ___]
  2965. [(Prim op es)
  2966. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2967. (define (uniquify p)
  2968. (match p
  2969. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2970. \end{lstlisting}
  2971. \end{tcolorbox}
  2972. \caption{Skeleton for the \key{uniquify} pass.}
  2973. \label{fig:uniquify-Lvar}
  2974. \end{figure}
  2975. \begin{exercise}
  2976. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2977. Complete the \code{uniquify} pass by filling in the blanks in
  2978. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2979. variables and for the \key{let} form in the file \code{compiler.rkt}
  2980. in the support code.
  2981. \end{exercise}
  2982. \begin{exercise}
  2983. \normalfont\normalsize
  2984. \label{ex:Lvar}
  2985. Create five \LangVar{} programs that exercise the most interesting
  2986. parts of the \key{uniquify} pass; that is, the programs should include
  2987. \key{let} forms, variables, and variables that shadow each other.
  2988. The five programs should be placed in the subdirectory named
  2989. \key{tests}, and the file names should start with \code{var\_test\_}
  2990. followed by a unique integer and end with the file extension
  2991. \key{.rkt}.
  2992. %
  2993. The \key{run-tests.rkt} script in the support code checks whether the
  2994. output programs produce the same result as the input programs. The
  2995. script uses the \key{interp-tests} function
  2996. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2997. your \key{uniquify} pass on the example programs. The \code{passes}
  2998. parameter of \key{interp-tests} is a list that should have one entry
  2999. for each pass in your compiler. For now, define \code{passes} to
  3000. contain just one entry for \code{uniquify} as follows:
  3001. \begin{lstlisting}
  3002. (define passes
  3003. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3004. \end{lstlisting}
  3005. Run the \key{run-tests.rkt} script in the support code to check
  3006. whether the output programs produce the same result as the input
  3007. programs.
  3008. \end{exercise}
  3009. \fi}
  3010. \section{Remove Complex Operands}
  3011. \label{sec:remove-complex-opera-Lvar}
  3012. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  3013. into a restricted form in which the arguments of operations are atomic
  3014. expressions. Put another way, this pass removes complex
  3015. operands\index{subject}{complex operand}, such as the expression
  3016. \racket{\code{(- 10)}}\python{\code{-10}}
  3017. in the following program. This is accomplished by introducing a new
  3018. temporary variable, assigning the complex operand to the new
  3019. variable, and then using the new variable in place of the complex
  3020. operand, as shown in the output of \code{remove\_complex\_operands} on the
  3021. right.
  3022. {\if\edition\racketEd
  3023. \begin{transformation}
  3024. % var_test_19.rkt
  3025. \begin{lstlisting}
  3026. (let ([x (+ 42 (- 10))])
  3027. (+ x 10))
  3028. \end{lstlisting}
  3029. \compilesto
  3030. \begin{lstlisting}
  3031. (let ([x (let ([tmp.1 (- 10)])
  3032. (+ 42 tmp.1))])
  3033. (+ x 10))
  3034. \end{lstlisting}
  3035. \end{transformation}
  3036. \fi}
  3037. {\if\edition\pythonEd\pythonColor
  3038. \begin{transformation}
  3039. \begin{lstlisting}
  3040. x = 42 + -10
  3041. print(x + 10)
  3042. \end{lstlisting}
  3043. \compilesto
  3044. \begin{lstlisting}
  3045. tmp_0 = -10
  3046. x = 42 + tmp_0
  3047. tmp_1 = x + 10
  3048. print(tmp_1)
  3049. \end{lstlisting}
  3050. \end{transformation}
  3051. \fi}
  3052. \newcommand{\LvarMonadASTRacket}{
  3053. \begin{array}{rcl}
  3054. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3055. \Exp &::=& \Atm \MID \READ{} \\
  3056. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3057. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3058. \end{array}
  3059. }
  3060. \newcommand{\LvarMonadASTPython}{
  3061. \begin{array}{rcl}
  3062. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3063. \Exp{} &::=& \Atm \MID \READ{} \\
  3064. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3065. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3066. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3067. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3068. \end{array}
  3069. }
  3070. \begin{figure}[tp]
  3071. \centering
  3072. \begin{tcolorbox}[colback=white]
  3073. {\if\edition\racketEd
  3074. \[
  3075. \begin{array}{l}
  3076. \LvarMonadASTRacket \\
  3077. \begin{array}{rcl}
  3078. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3079. \end{array}
  3080. \end{array}
  3081. \]
  3082. \fi}
  3083. {\if\edition\pythonEd\pythonColor
  3084. \[
  3085. \begin{array}{l}
  3086. \LvarMonadASTPython \\
  3087. \begin{array}{rcl}
  3088. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3089. \end{array}
  3090. \end{array}
  3091. \]
  3092. \fi}
  3093. \end{tcolorbox}
  3094. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3095. atomic expressions.}
  3096. \label{fig:Lvar-anf-syntax}
  3097. \index{subject}{Lvarmon@\LangVarANF{} abstract syntax}
  3098. \end{figure}
  3099. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3100. of this pass, the language \LangVarANF{}. The only difference is that
  3101. operator arguments are restricted to be atomic expressions that are
  3102. defined by the \Atm{} nonterminal. In particular, integer constants
  3103. and variables are atomic.
  3104. The atomic expressions are pure (they do not cause or depend on side
  3105. effects) whereas complex expressions may have side effects, such as
  3106. \READ{}. A language with this separation between pure expressions
  3107. versus expressions with side effects is said to be in monadic normal
  3108. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3109. in the name \LangVarANF{}. An important invariant of the
  3110. \code{remove\_complex\_operands} pass is that the relative ordering
  3111. among complex expressions is not changed, but the relative ordering
  3112. between atomic expressions and complex expressions can change and
  3113. often does. These changes are behavior preserving because
  3114. atomic expressions are pure.
  3115. {\if\edition\racketEd
  3116. Another well-known form for intermediate languages is the
  3117. \emph{administrative normal form}
  3118. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3119. \index{subject}{administrative normal form} \index{subject}{ANF}
  3120. %
  3121. The \LangVarANF{} language is not quite in ANF because it allows the
  3122. right-hand side of a \code{let} to be a complex expression, such as
  3123. another \code{let}. The flattening of nested \code{let} expressions is
  3124. instead one of the responsibilities of the \code{explicate\_control}
  3125. pass.
  3126. \fi}
  3127. {\if\edition\racketEd
  3128. We recommend implementing this pass with two mutually recursive
  3129. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3130. \code{rco\_atom} to subexpressions that need to become atomic and to
  3131. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3132. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3133. returns an expression. The \code{rco\_atom} function returns two
  3134. things: an atomic expression and an alist mapping temporary variables to
  3135. complex subexpressions. You can return multiple things from a function
  3136. using Racket's \key{values} form, and you can receive multiple things
  3137. from a function call using the \key{define-values} form.
  3138. \fi}
  3139. %
  3140. {\if\edition\pythonEd\pythonColor
  3141. %
  3142. We recommend implementing this pass with an auxiliary method named
  3143. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3144. Boolean that specifies whether the expression needs to become atomic
  3145. or not. The \code{rco\_exp} method should return a pair consisting of
  3146. the new expression and a list of pairs, associating new temporary
  3147. variables with their initializing expressions.
  3148. %
  3149. \fi}
  3150. {\if\edition\racketEd
  3151. %
  3152. In the example program with the expression \code{(+ 42 (-
  3153. 10))}, the subexpression \code{(- 10)} should be processed using the
  3154. \code{rco\_atom} function because it is an argument of the \code{+}
  3155. operator and therefore needs to become atomic. The output of
  3156. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3157. \begin{transformation}
  3158. \begin{lstlisting}
  3159. (- 10)
  3160. \end{lstlisting}
  3161. \compilesto
  3162. \begin{lstlisting}
  3163. tmp.1
  3164. ((tmp.1 . (- 10)))
  3165. \end{lstlisting}
  3166. \end{transformation}
  3167. \fi}
  3168. %
  3169. {\if\edition\pythonEd\pythonColor
  3170. %
  3171. Returning to the example program with the expression \code{42 + -10},
  3172. the subexpression \code{-10} should be processed using the
  3173. \code{rco\_exp} function with \code{True} as the second argument,
  3174. because \code{-10} is an argument of the \code{+} operator and
  3175. therefore needs to become atomic. The output of \code{rco\_exp}
  3176. applied to \code{-10} is as follows.
  3177. \begin{transformation}
  3178. \begin{lstlisting}
  3179. -10
  3180. \end{lstlisting}
  3181. \compilesto
  3182. \begin{lstlisting}
  3183. tmp_1
  3184. [(tmp_1, -10)]
  3185. \end{lstlisting}
  3186. \end{transformation}
  3187. %
  3188. \fi}
  3189. Take special care of programs, such as the following, that
  3190. %
  3191. \racket{bind a variable to an atomic expression.}
  3192. %
  3193. \python{assign an atomic expression to a variable.}
  3194. %
  3195. You should leave such \racket{variable bindings}\python{assignments}
  3196. unchanged, as shown in the program on the right:\\
  3197. %
  3198. {\if\edition\racketEd
  3199. \begin{transformation}
  3200. % var_test_20.rkt
  3201. \begin{lstlisting}
  3202. (let ([a 42])
  3203. (let ([b a])
  3204. b))
  3205. \end{lstlisting}
  3206. \compilesto
  3207. \begin{lstlisting}
  3208. (let ([a 42])
  3209. (let ([b a])
  3210. b))
  3211. \end{lstlisting}
  3212. \end{transformation}
  3213. \fi}
  3214. {\if\edition\pythonEd\pythonColor
  3215. \begin{transformation}
  3216. \begin{lstlisting}
  3217. a = 42
  3218. b = a
  3219. print(b)
  3220. \end{lstlisting}
  3221. \compilesto
  3222. \begin{lstlisting}
  3223. a = 42
  3224. b = a
  3225. print(b)
  3226. \end{lstlisting}
  3227. \end{transformation}
  3228. \fi}
  3229. %
  3230. \noindent A careless implementation might produce the following output with
  3231. unnecessary temporary variables.
  3232. \begin{center}
  3233. \begin{minipage}{0.4\textwidth}
  3234. {\if\edition\racketEd
  3235. \begin{lstlisting}
  3236. (let ([tmp.1 42])
  3237. (let ([a tmp.1])
  3238. (let ([tmp.2 a])
  3239. (let ([b tmp.2])
  3240. b))))
  3241. \end{lstlisting}
  3242. \fi}
  3243. {\if\edition\pythonEd\pythonColor
  3244. \begin{lstlisting}
  3245. tmp_1 = 42
  3246. a = tmp_1
  3247. tmp_2 = a
  3248. b = tmp_2
  3249. print(b)
  3250. \end{lstlisting}
  3251. \fi}
  3252. \end{minipage}
  3253. \end{center}
  3254. \begin{exercise}
  3255. \normalfont\normalsize
  3256. {\if\edition\racketEd
  3257. Implement the \code{remove\_complex\_operands} function in
  3258. \code{compiler.rkt}.
  3259. %
  3260. Create three new \LangVar{} programs that exercise the interesting
  3261. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3262. regarding file names described in exercise~\ref{ex:Lvar}.
  3263. %
  3264. In the \code{run-tests.rkt} script, add the following entry to the
  3265. list of \code{passes}, and then run the script to test your compiler.
  3266. \begin{lstlisting}
  3267. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3268. \end{lstlisting}
  3269. In debugging your compiler, it is often useful to see the intermediate
  3270. programs that are output from each pass. To print the intermediate
  3271. programs, place \lstinline{(debug-level 1)} before the call to
  3272. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3273. %
  3274. {\if\edition\pythonEd\pythonColor
  3275. Implement the \code{remove\_complex\_operands} pass in
  3276. \code{compiler.py}, creating auxiliary functions for each
  3277. nonterminal in the grammar, that is, \code{rco\_exp}
  3278. and \code{rco\_stmt}. We recommend that you use the function
  3279. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3280. \fi}
  3281. \end{exercise}
  3282. {\if\edition\pythonEd\pythonColor
  3283. \begin{exercise}
  3284. \normalfont\normalsize
  3285. \label{ex:Lvar}
  3286. Create five \LangVar{} programs that exercise the most interesting
  3287. parts of the \code{remove\_complex\_operands} pass. The five programs
  3288. should be placed in the subdirectory \key{tests/var}, and the file
  3289. names should end with the file extension \key{.py}. Run the
  3290. \key{run-tests.py} script in the support code to check whether the
  3291. output programs produce the same result as the input programs.
  3292. \end{exercise}
  3293. \fi}
  3294. {\if\edition\racketEd
  3295. \section{Explicate Control}
  3296. \label{sec:explicate-control-Lvar}
  3297. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3298. programs that make the order of execution explicit in their
  3299. syntax. For now this amounts to flattening \key{let} constructs into a
  3300. sequence of assignment statements. For example, consider the following
  3301. \LangVar{} program:\\
  3302. % var_test_11.rkt
  3303. \begin{minipage}{0.96\textwidth}
  3304. \begin{lstlisting}
  3305. (let ([y (let ([x 20])
  3306. (+ x (let ([x 22]) x)))])
  3307. y)
  3308. \end{lstlisting}
  3309. \end{minipage}\\
  3310. %
  3311. The output of the previous pass is shown next, on the left, and the
  3312. output of \code{explicate\_control} is on the right. Recall that the
  3313. right-hand side of a \key{let} executes before its body, so that the order
  3314. of evaluation for this program is to assign \code{20} to \code{x.1},
  3315. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3316. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3317. this ordering explicit.
  3318. \begin{transformation}
  3319. \begin{lstlisting}
  3320. (let ([y (let ([x.1 20])
  3321. (let ([x.2 22])
  3322. (+ x.1 x.2)))])
  3323. y)
  3324. \end{lstlisting}
  3325. \compilesto
  3326. \begin{lstlisting}[language=C]
  3327. start:
  3328. x.1 = 20;
  3329. x.2 = 22;
  3330. y = (+ x.1 x.2);
  3331. return y;
  3332. \end{lstlisting}
  3333. \end{transformation}
  3334. \begin{figure}[tbp]
  3335. \begin{tcolorbox}[colback=white]
  3336. \begin{lstlisting}
  3337. (define (explicate_tail e)
  3338. (match e
  3339. [(Var x) ___]
  3340. [(Int n) (Return (Int n))]
  3341. [(Let x rhs body) ___]
  3342. [(Prim op es) ___]
  3343. [else (error "explicate_tail unhandled case" e)]))
  3344. (define (explicate_assign e x cont)
  3345. (match e
  3346. [(Var x) ___]
  3347. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3348. [(Let y rhs body) ___]
  3349. [(Prim op es) ___]
  3350. [else (error "explicate_assign unhandled case" e)]))
  3351. (define (explicate_control p)
  3352. (match p
  3353. [(Program info body) ___]))
  3354. \end{lstlisting}
  3355. \end{tcolorbox}
  3356. \caption{Skeleton for the \code{explicate\_control} pass.}
  3357. \label{fig:explicate-control-Lvar}
  3358. \end{figure}
  3359. The organization of this pass depends on the notion of tail position
  3360. to which we have alluded. Here is the definition.
  3361. \begin{definition}\normalfont
  3362. The following rules define when an expression is in \emph{tail
  3363. position}\index{subject}{tail position} for the language \LangVar{}.
  3364. \begin{enumerate}
  3365. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3366. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3367. \end{enumerate}
  3368. \end{definition}
  3369. We recommend implementing \code{explicate\_control} using two
  3370. recursive functions, \code{explicate\_tail} and
  3371. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3372. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3373. function should be applied to expressions in tail position, whereas the
  3374. \code{explicate\_assign} should be applied to expressions that occur on
  3375. the right-hand side of a \key{let}.
  3376. %
  3377. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3378. input and produces a \Tail{} in \LangCVar{} (see
  3379. figure~\ref{fig:c0-syntax}).
  3380. %
  3381. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3382. the variable to which it is to be assigned, and a \Tail{} in
  3383. \LangCVar{} for the code that comes after the assignment. The
  3384. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3385. The \code{explicate\_assign} function is in accumulator-passing style:
  3386. the \code{cont} parameter is used for accumulating the output. This
  3387. accumulator-passing style plays an important role in the way that we
  3388. generate high-quality code for conditional expressions in
  3389. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3390. continuation because it contains the generated code that should come
  3391. after the current assignment. This code organization is also related
  3392. to continuation-passing style, except that \code{cont} is not what
  3393. happens next during compilation but is what happens next in the
  3394. generated code.
  3395. \begin{exercise}\normalfont\normalsize
  3396. %
  3397. Implement the \code{explicate\_control} function in
  3398. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3399. exercise the code in \code{explicate\_control}.
  3400. %
  3401. In the \code{run-tests.rkt} script, add the following entry to the
  3402. list of \code{passes} and then run the script to test your compiler.
  3403. \begin{lstlisting}
  3404. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3405. \end{lstlisting}
  3406. \end{exercise}
  3407. \fi}
  3408. \section{Select Instructions}
  3409. \label{sec:select-Lvar}
  3410. \index{subject}{select instructions}
  3411. In the \code{select\_instructions} pass we begin the work of
  3412. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3413. language of this pass, \LangXVar{}, is a variant of x86 that still
  3414. uses variables, so we add an AST node of the form $\XVAR{\itm{var}}$
  3415. to the \Arg{} nonterminal of the \LangXInt{} abstract syntax
  3416. (figure~\ref{fig:x86-int-ast})\index{subject}{x86var@\LangXVar{}}.
  3417. \racket{We recommend implementing the \code{select\_instructions} with
  3418. three auxiliary functions, one for each of the nonterminals of
  3419. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.} \python{We recommend
  3420. implementing an auxiliary function named \code{select\_stmt} for the
  3421. $\Stmt$ nonterminal.}
  3422. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3423. same and integer constants change to immediates; that is, $\INT{n}$
  3424. changes to $\IMM{n}$.}
  3425. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3426. arithmetic operations. For example, consider the following addition
  3427. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3428. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3429. \key{addq} instruction in x86, but it performs an in-place update.
  3430. %
  3431. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3432. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3433. \begin{transformation}
  3434. {\if\edition\racketEd
  3435. \begin{lstlisting}
  3436. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3437. \end{lstlisting}
  3438. \fi}
  3439. {\if\edition\pythonEd\pythonColor
  3440. \begin{lstlisting}
  3441. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3442. \end{lstlisting}
  3443. \fi}
  3444. \compilesto
  3445. \begin{lstlisting}
  3446. movq |$\Arg_1$|, %rax
  3447. addq |$\Arg_2$|, %rax
  3448. movq %rax, |$\itm{var}$|
  3449. \end{lstlisting}
  3450. \end{transformation}
  3451. %
  3452. However, with some care we can generate shorter sequences of
  3453. instructions. Suppose that one or more of the arguments of the
  3454. addition is the same variable as the left-hand side of the assignment.
  3455. Then the assignment statement can be translated into a single
  3456. \key{addq} instruction, as follows.
  3457. \begin{transformation}
  3458. {\if\edition\racketEd
  3459. \begin{lstlisting}
  3460. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3461. \end{lstlisting}
  3462. \fi}
  3463. {\if\edition\pythonEd\pythonColor
  3464. \begin{lstlisting}
  3465. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3466. \end{lstlisting}
  3467. \fi}
  3468. \compilesto
  3469. \begin{lstlisting}
  3470. addq |$\Arg_1$|, |$\itm{var}$|
  3471. \end{lstlisting}
  3472. \end{transformation}
  3473. %
  3474. On the other hand, if $\Atm_2$ is not the same variable as the
  3475. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3476. and then add $\Arg_2$ to \itm{var}.
  3477. %
  3478. \begin{transformation}
  3479. {\if\edition\racketEd
  3480. \begin{lstlisting}
  3481. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3482. \end{lstlisting}
  3483. \fi}
  3484. {\if\edition\pythonEd\pythonColor
  3485. \begin{lstlisting}
  3486. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3487. \end{lstlisting}
  3488. \fi}
  3489. \compilesto
  3490. \begin{lstlisting}
  3491. movq |$\Arg_1$|, |$\itm{var}$|
  3492. addq |$\Arg_2$|, |$\itm{var}$|
  3493. \end{lstlisting}
  3494. \end{transformation}
  3495. The \READOP{} operation does not have a direct counterpart in x86
  3496. assembly, so we provide this functionality with the function
  3497. \code{read\_int} in the file \code{runtime.c}, written in
  3498. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3499. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3500. system}, or simply the \emph{runtime} for short. When compiling your
  3501. generated x86 assembly code, you need to compile \code{runtime.c} to
  3502. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3503. \code{-c}) and link it into the executable. For our purposes of code
  3504. generation, all you need to do is translate an assignment of
  3505. \READOP{} into a call to the \code{read\_int} function followed by a
  3506. move from \code{rax} to the left-hand side variable. (The
  3507. return value of a function is placed in \code{rax}.)
  3508. \begin{transformation}
  3509. {\if\edition\racketEd
  3510. \begin{lstlisting}
  3511. |$\itm{var}$| = (read);
  3512. \end{lstlisting}
  3513. \fi}
  3514. {\if\edition\pythonEd\pythonColor
  3515. \begin{lstlisting}
  3516. |$\itm{var}$| = input_int();
  3517. \end{lstlisting}
  3518. \fi}
  3519. \compilesto
  3520. \begin{lstlisting}
  3521. callq read_int
  3522. movq %rax, |$\itm{var}$|
  3523. \end{lstlisting}
  3524. \end{transformation}
  3525. {\if\edition\pythonEd\pythonColor
  3526. %
  3527. Similarly, we translate the \code{print} operation, shown below, into
  3528. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3529. In x86, the first six arguments to functions are passed in registers,
  3530. with the first argument passed in register \code{rdi}. So we move the
  3531. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3532. \code{callq} instruction.
  3533. \begin{transformation}
  3534. \begin{lstlisting}
  3535. print(|$\Atm$|)
  3536. \end{lstlisting}
  3537. \compilesto
  3538. \begin{lstlisting}
  3539. movq |$\Arg$|, %rdi
  3540. callq print_int
  3541. \end{lstlisting}
  3542. \end{transformation}
  3543. %
  3544. \fi}
  3545. {\if\edition\racketEd
  3546. %
  3547. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3548. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3549. assignment to the \key{rax} register followed by a jump to
  3550. the label \key{conclusion}. Later, in Section~\ref{sec:print-x86},
  3551. we discuss the generation of the \key{conclusion} block.
  3552. In the meantime, the interpreter for \LangXVar{} recognizes a jump
  3553. to \key{conclusion} as the end of the program.
  3554. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3555. recursively and then append the resulting instructions.
  3556. %
  3557. \fi}
  3558. {\if\edition\pythonEd\pythonColor
  3559. We recommend that you use the function \code{utils.label\_name} to
  3560. transform strings into labels, for example, in
  3561. the target of the \code{callq} instruction. This practice makes your
  3562. compiler portable across Linux and Mac OS X, which requires an underscore
  3563. prefixed to all labels.
  3564. \fi}
  3565. \begin{exercise}
  3566. \normalfont\normalsize
  3567. {\if\edition\racketEd
  3568. Implement the \code{select\_instructions} pass in
  3569. \code{compiler.rkt}. Create three new example programs that are
  3570. designed to exercise all the interesting cases in this pass.
  3571. %
  3572. In the \code{run-tests.rkt} script, add the following entry to the
  3573. list of \code{passes} and then run the script to test your compiler.
  3574. \begin{lstlisting}
  3575. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3576. \end{lstlisting}
  3577. \fi}
  3578. {\if\edition\pythonEd\pythonColor
  3579. Implement the \key{select\_instructions} pass in
  3580. \code{compiler.py}. Create three new example programs that are
  3581. designed to exercise all the interesting cases in this pass.
  3582. Run the \code{run-tests.py} script to check
  3583. whether the output programs produce the same result as the input
  3584. programs.
  3585. \fi}
  3586. \end{exercise}
  3587. \section{Assign Homes}
  3588. \label{sec:assign-Lvar}
  3589. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3590. \LangXVar{} programs that no longer use program variables. Thus, the
  3591. \code{assign\_homes} pass is responsible for placing all the program
  3592. variables in registers or on the stack. For runtime efficiency, it is
  3593. better to place variables in registers, but because there are only
  3594. sixteen registers, some programs must necessarily resort to placing
  3595. some variables on the stack. In this chapter we focus on the mechanics
  3596. of placing variables on the stack. We study an algorithm for placing
  3597. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3598. Consider again the following \LangVar{} program from
  3599. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3600. % var_test_20.rkt
  3601. \begin{minipage}{0.96\textwidth}
  3602. {\if\edition\racketEd
  3603. \begin{lstlisting}
  3604. (let ([a 42])
  3605. (let ([b a])
  3606. b))
  3607. \end{lstlisting}
  3608. \fi}
  3609. {\if\edition\pythonEd\pythonColor
  3610. \begin{lstlisting}
  3611. a = 42
  3612. b = a
  3613. print(b)
  3614. \end{lstlisting}
  3615. \fi}
  3616. \end{minipage}\\
  3617. %
  3618. The output of \code{select\_instructions} is shown next, on the left,
  3619. and the output of \code{assign\_homes} is on the right. In this
  3620. example, we assign variable \code{a} to stack location
  3621. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3622. \begin{transformation}
  3623. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3624. movq $42, a
  3625. movq a, b
  3626. movq b, %rax
  3627. \end{lstlisting}
  3628. \compilesto
  3629. %stack-space: 16
  3630. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3631. movq $42, -8(%rbp)
  3632. movq -8(%rbp), -16(%rbp)
  3633. movq -16(%rbp), %rax
  3634. \end{lstlisting}
  3635. \end{transformation}
  3636. \racket{
  3637. The \code{assign\_homes} pass should replace all variables
  3638. with stack locations.
  3639. The list of variables can be obtained from
  3640. the \code{locals-types} entry in the $\itm{info}$ of the
  3641. \code{X86Program} node. The \code{locals-types} entry is an alist
  3642. mapping all the variables in the program to their types
  3643. (for now, just \code{Integer}).
  3644. As an aside, the \code{locals-types} entry is
  3645. computed by \code{type-check-Cvar} in the support code, which
  3646. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3647. which you should propagate to the \code{X86Program} node.}
  3648. %
  3649. \python{The \code{assign\_homes} pass should replace all uses of
  3650. variables with stack locations.}
  3651. %
  3652. In the process of assigning variables to stack locations, it is
  3653. convenient for you to compute and store the size of the frame (in
  3654. bytes) in
  3655. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3656. %
  3657. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3658. %
  3659. which is needed later to generate the conclusion of the \code{main}
  3660. procedure. The x86-64 standard requires the frame size to be a
  3661. multiple of 16 bytes.\index{subject}{frame}
  3662. % TODO: store the number of variables instead? -Jeremy
  3663. \begin{exercise}\normalfont\normalsize
  3664. Implement the \code{assign\_homes} pass in
  3665. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3666. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3667. grammar. We recommend that the auxiliary functions take an extra
  3668. parameter that maps variable names to homes (stack locations for now).
  3669. %
  3670. {\if\edition\racketEd
  3671. In the \code{run-tests.rkt} script, add the following entry to the
  3672. list of \code{passes} and then run the script to test your compiler.
  3673. \begin{lstlisting}
  3674. (list "assign homes" assign-homes interp_x86-0)
  3675. \end{lstlisting}
  3676. \fi}
  3677. {\if\edition\pythonEd\pythonColor
  3678. Run the \code{run-tests.py} script to check
  3679. whether the output programs produce the same result as the input
  3680. programs.
  3681. \fi}
  3682. \end{exercise}
  3683. \section{Patch Instructions}
  3684. \label{sec:patch-s0}
  3685. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3686. \LangXInt{} by making sure that each instruction adheres to the
  3687. restriction that at most one argument of an instruction may be a
  3688. memory reference.
  3689. We return to the following example.\\
  3690. \begin{minipage}{0.5\textwidth}
  3691. % var_test_20.rkt
  3692. {\if\edition\racketEd
  3693. \begin{lstlisting}
  3694. (let ([a 42])
  3695. (let ([b a])
  3696. b))
  3697. \end{lstlisting}
  3698. \fi}
  3699. {\if\edition\pythonEd\pythonColor
  3700. \begin{lstlisting}
  3701. a = 42
  3702. b = a
  3703. print(b)
  3704. \end{lstlisting}
  3705. \fi}
  3706. \end{minipage}\\
  3707. The \code{assign\_homes} pass produces the following translation. \\
  3708. \begin{minipage}{0.5\textwidth}
  3709. {\if\edition\racketEd
  3710. \begin{lstlisting}
  3711. movq $42, -8(%rbp)
  3712. movq -8(%rbp), -16(%rbp)
  3713. movq -16(%rbp), %rax
  3714. \end{lstlisting}
  3715. \fi}
  3716. {\if\edition\pythonEd\pythonColor
  3717. \begin{lstlisting}
  3718. movq $42, -8(%rbp)
  3719. movq -8(%rbp), -16(%rbp)
  3720. movq -16(%rbp), %rdi
  3721. callq print_int
  3722. \end{lstlisting}
  3723. \fi}
  3724. \end{minipage}\\
  3725. The second \key{movq} instruction is problematic because both
  3726. arguments are stack locations. We suggest fixing this problem by
  3727. moving from the source location to the register \key{rax} and then
  3728. from \key{rax} to the destination location, as follows.
  3729. \begin{lstlisting}
  3730. movq -8(%rbp), %rax
  3731. movq %rax, -16(%rbp)
  3732. \end{lstlisting}
  3733. There is a similar corner case that also needs to be dealt with. If
  3734. one argument is an immediate integer larger than $2^{16}$ and the
  3735. other is a memory reference, then the instruction is invalid. One can
  3736. fix this, for example, by first moving the immediate integer into
  3737. \key{rax} and then using \key{rax} in place of the integer.
  3738. \begin{exercise}
  3739. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3740. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3741. Create three new example programs that are
  3742. designed to exercise all the interesting cases in this pass.
  3743. %
  3744. {\if\edition\racketEd
  3745. In the \code{run-tests.rkt} script, add the following entry to the
  3746. list of \code{passes} and then run the script to test your compiler.
  3747. \begin{lstlisting}
  3748. (list "patch instructions" patch_instructions interp_x86-0)
  3749. \end{lstlisting}
  3750. \fi}
  3751. {\if\edition\pythonEd\pythonColor
  3752. Run the \code{run-tests.py} script to check
  3753. whether the output programs produce the same result as the input
  3754. programs.
  3755. \fi}
  3756. \end{exercise}
  3757. \section{Generate Prelude and Conclusion}
  3758. \label{sec:print-x86}
  3759. \index{subject}{prelude}\index{subject}{conclusion}
  3760. The last step of the compiler from \LangVar{} to x86 is to generate
  3761. the \code{main} function with a prelude and conclusion wrapped around
  3762. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3763. discussed in section~\ref{sec:x86}.
  3764. When running on Mac OS X, your compiler should prefix an underscore to
  3765. all labels (for example, changing \key{main} to \key{\_main}).
  3766. %
  3767. \racket{The Racket call \code{(system-type 'os)} is useful for
  3768. determining which operating system the compiler is running on. It
  3769. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3770. %
  3771. \python{The Python \code{platform.system}
  3772. function returns \code{\textquotesingle Linux\textquotesingle},
  3773. \code{\textquotesingle Windows\textquotesingle}, or
  3774. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3775. \begin{exercise}\normalfont\normalsize
  3776. %
  3777. Implement the \key{prelude\_and\_conclusion} pass in
  3778. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3779. %
  3780. {\if\edition\racketEd
  3781. In the \code{run-tests.rkt} script, add the following entry to the
  3782. list of \code{passes} and then run the script to test your compiler.
  3783. \begin{lstlisting}
  3784. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3785. \end{lstlisting}
  3786. %
  3787. Uncomment the call to the \key{compiler-tests} function
  3788. (appendix~\ref{appendix:utilities}), which tests your complete
  3789. compiler by executing the generated x86 code. It translates the x86
  3790. AST that you produce into a string by invoking the \code{print-x86}
  3791. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3792. the provided \key{runtime.c} file to \key{runtime.o} using
  3793. \key{gcc}. Run the script to test your compiler.
  3794. %
  3795. \fi}
  3796. {\if\edition\pythonEd\pythonColor
  3797. %
  3798. Run the \code{run-tests.py} script to check whether the output
  3799. programs produce the same result as the input programs. That script
  3800. translates the x86 AST that you produce into a string by invoking the
  3801. \code{repr} method that is implemented by the x86 AST classes in
  3802. \code{x86\_ast.py}.
  3803. %
  3804. \fi}
  3805. \end{exercise}
  3806. \section{Challenge: Partial Evaluator for \LangVar{}}
  3807. \label{sec:pe-Lvar}
  3808. \index{subject}{partialevaluation@partial evaluation}
  3809. This section describes two optional challenge exercises that involve
  3810. adapting and improving the partial evaluator for \LangInt{} that was
  3811. introduced in section~\ref{sec:partial-evaluation}.
  3812. \begin{exercise}\label{ex:pe-Lvar}
  3813. \normalfont\normalsize
  3814. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3815. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3816. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3817. %
  3818. \racket{\key{let} binding}\python{assignment}
  3819. %
  3820. to the \LangInt{} language, so you will need to add cases for them in
  3821. the \code{pe\_exp}
  3822. %
  3823. \racket{function.}
  3824. %
  3825. \python{and \code{pe\_stmt} functions.}
  3826. %
  3827. Once complete, add the partial evaluation pass to the front of your
  3828. compiler, and check that your compiler still passes all the
  3829. tests.
  3830. \end{exercise}
  3831. \begin{exercise}
  3832. \normalfont\normalsize
  3833. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3834. \code{pe\_add} auxiliary functions with functions that know more about
  3835. arithmetic. For example, your partial evaluator should translate
  3836. {\if\edition\racketEd
  3837. \[
  3838. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3839. \code{(+ 2 (read))}
  3840. \]
  3841. \fi}
  3842. {\if\edition\pythonEd\pythonColor
  3843. \[
  3844. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3845. \code{2 + input\_int()}
  3846. \]
  3847. \fi}
  3848. %
  3849. To accomplish this, the \code{pe\_exp} function should produce output
  3850. in the form of the $\itm{residual}$ nonterminal of the following
  3851. grammar. The idea is that when processing an addition expression, we
  3852. can always produce one of the following: (1) an integer constant, (2)
  3853. an addition expression with an integer constant on the left-hand side
  3854. but not the right-hand side, or (3) an addition expression in which
  3855. neither subexpression is a constant.
  3856. %
  3857. {\if\edition\racketEd
  3858. \[
  3859. \begin{array}{lcl}
  3860. \itm{inert} &::=& \Var
  3861. \MID \LP\key{read}\RP
  3862. \MID \LP\key{-} ~\Var\RP
  3863. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3864. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3865. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3866. \itm{residual} &::=& \Int
  3867. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3868. \MID \itm{inert}
  3869. \end{array}
  3870. \]
  3871. \fi}
  3872. {\if\edition\pythonEd\pythonColor
  3873. \[
  3874. \begin{array}{lcl}
  3875. \itm{inert} &::=& \Var
  3876. \MID \key{input\_int}\LP\RP
  3877. \MID \key{-} \Var
  3878. \MID \key{-} \key{input\_int}\LP\RP
  3879. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3880. \itm{residual} &::=& \Int
  3881. \MID \Int ~ \key{+} ~ \itm{inert}
  3882. \MID \itm{inert}
  3883. \end{array}
  3884. \]
  3885. \fi}
  3886. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3887. inputs are $\itm{residual}$ expressions and they should return
  3888. $\itm{residual}$ expressions. Once the improvements are complete,
  3889. make sure that your compiler still passes all the tests. After
  3890. all, fast code is useless if it produces incorrect results!
  3891. \end{exercise}
  3892. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3893. {\if\edition\pythonEd\pythonColor
  3894. \chapter{Parsing}
  3895. \label{ch:parsing}
  3896. \setcounter{footnote}{0}
  3897. \index{subject}{parsing}
  3898. In this chapter we learn how to use the Lark parser
  3899. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3900. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3901. You are then asked to create a parser for \LangVar{} using Lark.
  3902. We also describe the parsing algorithms used inside Lark, studying the
  3903. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3904. A parser framework such as Lark takes in a specification of the
  3905. concrete syntax and an input program and produces a parse tree. Even
  3906. though a parser framework does most of the work for us, using one
  3907. properly requires some knowledge. In particular, we must learn about
  3908. its specification languages and we must learn how to deal with
  3909. ambiguity in our language specifications. Also, some algorithms, such
  3910. as LALR(1), place restrictions on the grammars they can handle, in
  3911. which case knowing the algorithm helps with trying to decipher the
  3912. error messages.
  3913. The process of parsing is traditionally subdivided into two phases:
  3914. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3915. analysis} (also called parsing). The lexical analysis phase
  3916. translates the sequence of characters into a sequence of
  3917. \emph{tokens}, that is, words consisting of several characters. The
  3918. parsing phase organizes the tokens into a \emph{parse tree} that
  3919. captures how the tokens were matched by rules in the grammar of the
  3920. language. The reason for the subdivision into two phases is to enable
  3921. the use of a faster but less powerful algorithm for lexical analysis
  3922. and the use of a slower but more powerful algorithm for parsing.
  3923. %
  3924. %% Likewise, parser generators typical come in pairs, with separate
  3925. %% generators for the lexical analyzer (or lexer for short) and for the
  3926. %% parser. A particularly influential pair of generators were
  3927. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3928. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3929. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3930. %% Compiler Compiler.
  3931. %
  3932. The Lark parser framework that we use in this chapter includes both
  3933. lexical analyzers and parsers. The next section discusses lexical
  3934. analysis, and the remainder of the chapter discusses parsing.
  3935. \section{Lexical Analysis and Regular Expressions}
  3936. \label{sec:lex}
  3937. The lexical analyzers produced by Lark turn a sequence of characters
  3938. (a string) into a sequence of token objects. For example, a Lark
  3939. generated lexer for \LangInt{} converts the string
  3940. \begin{lstlisting}
  3941. 'print(1 + 3)'
  3942. \end{lstlisting}
  3943. \noindent into the following sequence of token objects:
  3944. \begin{center}
  3945. \begin{minipage}{0.95\textwidth}
  3946. \begin{lstlisting}
  3947. Token('PRINT', 'print')
  3948. Token('LPAR', '(')
  3949. Token('INT', '1')
  3950. Token('PLUS', '+')
  3951. Token('INT', '3')
  3952. Token('RPAR', ')')
  3953. Token('NEWLINE', '\n')
  3954. \end{lstlisting}
  3955. \end{minipage}
  3956. \end{center}
  3957. Each token includes a field for its \code{type}, such as \skey{INT},
  3958. and a field for its \code{value}, such as \skey{1}.
  3959. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3960. specification language for Lark's lexer is one regular expression for
  3961. each type of token. The term \emph{regular} comes from the term
  3962. \emph{regular languages}, which are the languages that can be
  3963. recognized by a finite state machine. A \emph{regular expression} is a
  3964. pattern formed of the following core elements:\index{subject}{regular
  3965. expression}\footnote{Regular expressions traditionally include the
  3966. empty regular expression that matches any zero-length part of a
  3967. string, but Lark does not support the empty regular expression.}
  3968. \begin{itemize}
  3969. \item A single character $c$ is a regular expression, and it matches
  3970. only itself. For example, the regular expression \code{a} matches
  3971. only the string \skey{a}.
  3972. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3973. R_2$ form a regular expression that matches any string that matches
  3974. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3975. matches the string \skey{a} and the string \skey{c}.
  3976. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3977. expression that matches any string that can be formed by
  3978. concatenating two strings, where the first string matches $R_1$ and
  3979. the second string matches $R_2$. For example, the regular expression
  3980. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3981. (Parentheses can be used to control the grouping of operators within
  3982. a regular expression.)
  3983. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3984. Kleene closure) is a regular expression that matches any string that
  3985. can be formed by concatenating zero or more strings that each match
  3986. the regular expression $R$. For example, the regular expression
  3987. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3988. \skey{abc}.
  3989. \end{itemize}
  3990. For our convenience, Lark also accepts the following extended set of
  3991. regular expressions that are automatically translated into the core
  3992. regular expressions.
  3993. \begin{itemize}
  3994. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3995. c_n]$ is a regular expression that matches any one of the
  3996. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3997. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3998. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3999. a regular expression that matches any character between $c_1$ and
  4000. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  4001. letter in the alphabet.
  4002. \item A regular expression followed by the plus symbol $R\ttm{+}$
  4003. is a regular expression that matches any string that can
  4004. be formed by concatenating one or more strings that each match $R$.
  4005. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  4006. matches \skey{b} and \skey{bzca}.
  4007. \item A regular expression followed by a question mark $R\ttm{?}$
  4008. is a regular expression that matches any string that either
  4009. matches $R$ or is the empty string.
  4010. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  4011. \end{itemize}
  4012. In a Lark grammar file, each kind of token is specified by a
  4013. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4014. that consists of the name of the terminal followed by a colon followed
  4015. by a sequence of literals. The literals include strings such as
  4016. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4017. terminal names, and literals composed using the regular expression
  4018. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4019. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4020. \begin{center}
  4021. \begin{minipage}{0.95\textwidth}
  4022. \begin{lstlisting}
  4023. DIGIT: /[0-9]/
  4024. INT: "-"? DIGIT+
  4025. NEWLINE: (/\r/? /\n/)+
  4026. \end{lstlisting}
  4027. \end{minipage}
  4028. \end{center}
  4029. \section{Grammars and Parse Trees}
  4030. \label{sec:CFG}
  4031. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4032. specify the abstract syntax of a language. We now take a closer look
  4033. at using grammar rules to specify the concrete syntax. Recall that
  4034. each rule has a left-hand side and a right-hand side, where the
  4035. left-hand side is a nonterminal and the right-hand side is a pattern
  4036. that defines what can be parsed as that nonterminal. For concrete
  4037. syntax, each right-hand side expresses a pattern for a string instead
  4038. of a pattern for an abstract syntax tree. In particular, each
  4039. right-hand side is a sequence of
  4040. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4041. terminal or a nonterminal. The nonterminals play the same role as in
  4042. the abstract syntax, defining categories of syntax. The nonterminals
  4043. of a grammar include the tokens defined in the lexer and all the
  4044. nonterminals defined by the grammar rules.
  4045. As an example, let us take a closer look at the concrete syntax of the
  4046. \LangInt{} language, repeated here.
  4047. \[
  4048. \begin{array}{l}
  4049. \LintGrammarPython \\
  4050. \begin{array}{rcl}
  4051. \LangInt{} &::=& \Stmt^{*}
  4052. \end{array}
  4053. \end{array}
  4054. \]
  4055. The Lark syntax for grammar rules differs slightly from the variant of
  4056. BNF that we use in this book. In particular, the notation $::=$ is
  4057. replaced by a single colon, and the use of typewriter font for string
  4058. literals is replaced by quotation marks. The following grammar serves
  4059. as a first draft of a Lark grammar for \LangInt{}.
  4060. \begin{center}
  4061. \begin{minipage}{0.95\textwidth}
  4062. \begin{lstlisting}[escapechar=$]
  4063. exp: INT
  4064. | "input_int" "(" ")"
  4065. | "-" exp
  4066. | exp "+" exp
  4067. | exp "-" exp
  4068. | "(" exp ")"
  4069. stmt_list:
  4070. | stmt NEWLINE stmt_list
  4071. lang_int: stmt_list
  4072. \end{lstlisting}
  4073. \end{minipage}
  4074. \end{center}
  4075. Let us begin by discussing the rule \code{exp: INT}, which says that
  4076. if the lexer matches a string to \code{INT}, then the parser also
  4077. categorizes the string as an \code{exp}. Recall that in
  4078. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4079. nonterminal with a sentence in English. Here we specify \code{INT}
  4080. more formally using a type of token \code{INT} and its regular
  4081. expression \code{"-"? DIGIT+}.
  4082. The rule \code{exp: exp "+" exp} says that any string that matches
  4083. \code{exp}, followed by the \code{+} character, followed by another
  4084. string that matches \code{exp}, is itself an \code{exp}. For example,
  4085. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4086. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4087. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4088. \code{exp}. We can visualize the application of grammar rules to parse
  4089. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4090. internal node in the tree is an application of a grammar rule and is
  4091. labeled with its left-hand side nonterminal. Each leaf node is a
  4092. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4093. shown in figure~\ref{fig:simple-parse-tree}.
  4094. \begin{figure}[tbp]
  4095. \begin{tcolorbox}[colback=white]
  4096. \centering
  4097. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4098. \end{tcolorbox}
  4099. \caption{The parse tree for \lstinline{'1+3'}.}
  4100. \label{fig:simple-parse-tree}
  4101. \end{figure}
  4102. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4103. following parse tree as represented by \code{Tree} and \code{Token}
  4104. objects.
  4105. \begin{lstlisting}
  4106. Tree('lang_int',
  4107. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4108. Tree('exp', [Token('INT', '3')])])]),
  4109. Token('NEWLINE', '\n')])
  4110. \end{lstlisting}
  4111. The nodes that come from the lexer are \code{Token} objects, whereas
  4112. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4113. object has a \code{data} field containing the name of the nonterminal
  4114. for the grammar rule that was applied. Each \code{Tree} object also
  4115. has a \code{children} field that is a list containing trees and/or
  4116. tokens. Note that Lark does not produce nodes for string literals in
  4117. the grammar. For example, the \code{Tree} node for the addition
  4118. expression has only two children for the two integers but is missing
  4119. its middle child for the \code{"+"} terminal. This would be
  4120. problematic except that Lark provides a mechanism for customizing the
  4121. \code{data} field of each \code{Tree} node on the basis of which rule was
  4122. applied. Next to each alternative in a grammar rule, write \code{->}
  4123. followed by a string that you want to appear in the \code{data}
  4124. field. The following is a second draft of a Lark grammar for
  4125. \LangInt{}, this time with more specific labels on the \code{Tree}
  4126. nodes.
  4127. \begin{center}
  4128. \begin{minipage}{0.95\textwidth}
  4129. \begin{lstlisting}[escapechar=$]
  4130. exp: INT -> int
  4131. | "input_int" "(" ")" -> input_int
  4132. | "-" exp -> usub
  4133. | exp "+" exp -> add
  4134. | exp "-" exp -> sub
  4135. | "(" exp ")" -> paren
  4136. stmt: "print" "(" exp ")" -> print
  4137. | exp -> expr
  4138. stmt_list: -> empty_stmt
  4139. | stmt NEWLINE stmt_list -> add_stmt
  4140. lang_int: stmt_list -> module
  4141. \end{lstlisting}
  4142. \end{minipage}
  4143. \end{center}
  4144. Here is the resulting parse tree.
  4145. \begin{lstlisting}
  4146. Tree('module',
  4147. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4148. Tree('int', [Token('INT', '3')])])]),
  4149. Token('NEWLINE', '\n')])
  4150. \end{lstlisting}
  4151. \section{Ambiguous Grammars}
  4152. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4153. can be parsed in more than one way. For example, consider the string
  4154. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4155. our draft grammar, resulting in the two parse trees shown in
  4156. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4157. interpreting the second parse tree would yield \code{-4} even through
  4158. the correct answer is \code{2}.
  4159. \begin{figure}[tbp]
  4160. \begin{tcolorbox}[colback=white]
  4161. \centering
  4162. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4163. \end{tcolorbox}
  4164. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4165. \label{fig:ambig-parse-tree}
  4166. \end{figure}
  4167. To deal with this problem we can change the grammar by categorizing
  4168. the syntax in a more fine-grained fashion. In this case we want to
  4169. disallow the application of the rule \code{exp: exp "-" exp} when the
  4170. child on the right is an addition. To do this we can replace the
  4171. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4172. the expressions except for addition, as in the following.
  4173. \begin{center}
  4174. \begin{minipage}{0.95\textwidth}
  4175. \begin{lstlisting}[escapechar=$]
  4176. exp: exp "-" exp_no_add -> sub
  4177. | exp "+" exp -> add
  4178. | exp_no_add
  4179. exp_no_add: INT -> int
  4180. | "input_int" "(" ")" -> input_int
  4181. | "-" exp -> usub
  4182. | exp "-" exp_no_add -> sub
  4183. | "(" exp ")" -> paren
  4184. \end{lstlisting}
  4185. \end{minipage}
  4186. \end{center}
  4187. However, there remains some ambiguity in the grammar. For example, the
  4188. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4189. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4190. (incorrect). That is, subtraction is left associative. Likewise,
  4191. addition in Python is left associative. We also need to consider the
  4192. interaction of unary subtraction with both addition and
  4193. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4194. has higher \emph{precedence}\index{subject}{precedence} than addition
  4195. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4196. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4197. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4198. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4199. all the other expressions, and it uses \code{exp\_hi} for the second
  4200. child in the rules for addition and subtraction. Furthermore, unary
  4201. subtraction uses \code{exp\_hi} for its child.
  4202. For languages with more operators and more precedence levels, one must
  4203. refine the \code{exp} nonterminal into several nonterminals, one for
  4204. each precedence level.
  4205. \begin{figure}[tbp]
  4206. \begin{tcolorbox}[colback=white]
  4207. \centering
  4208. \begin{lstlisting}[escapechar=$]
  4209. exp: exp "+" exp_hi -> add
  4210. | exp "-" exp_hi -> sub
  4211. | exp_hi
  4212. exp_hi: INT -> int
  4213. | "input_int" "(" ")" -> input_int
  4214. | "-" exp_hi -> usub
  4215. | "(" exp ")" -> paren
  4216. stmt: "print" "(" exp ")" -> print
  4217. | exp -> expr
  4218. stmt_list: -> empty_stmt
  4219. | stmt NEWLINE stmt_list -> add_stmt
  4220. lang_int: stmt_list -> module
  4221. \end{lstlisting}
  4222. \end{tcolorbox}
  4223. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4224. \label{fig:Lint-lark-grammar}
  4225. \end{figure}
  4226. \section{From Parse Trees to Abstract Syntax Trees}
  4227. As we have seen, the output of a Lark parser is a parse tree, that is,
  4228. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4229. step is to convert the parse tree to an abstract syntax tree. This can
  4230. be accomplished with a recursive function that inspects the
  4231. \code{data} field of each node and then constructs the corresponding
  4232. AST node, using recursion to handle its children. The following is an
  4233. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4234. \begin{center}
  4235. \begin{minipage}{0.95\textwidth}
  4236. \begin{lstlisting}
  4237. def parse_tree_to_ast(e):
  4238. if e.data == 'int':
  4239. return Constant(int(e.children[0].value))
  4240. elif e.data == 'input_int':
  4241. return Call(Name('input_int'), [])
  4242. elif e.data == 'add':
  4243. e1, e2 = e.children
  4244. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4245. ...
  4246. else:
  4247. raise Exception('unhandled parse tree', e)
  4248. \end{lstlisting}
  4249. \end{minipage}
  4250. \end{center}
  4251. \begin{exercise}
  4252. \normalfont\normalsize
  4253. %
  4254. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4255. default parsing algorithm (Earley) with the \code{ambiguity} option
  4256. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4257. output will include multiple parse trees that will indicate to you
  4258. that there is a problem with your grammar. Your parser should ignore
  4259. white space, so we recommend using Lark's \code{\%ignore} directive
  4260. as follows.
  4261. \begin{lstlisting}
  4262. %import common.WS_INLINE
  4263. %ignore WS_INLINE
  4264. \end{lstlisting}
  4265. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4266. Lark parser instead of using the \code{parse} function from
  4267. the \code{ast} module. Test your compiler on all the \LangVar{}
  4268. programs that you have created, and create four additional programs
  4269. that test for ambiguities in your grammar.
  4270. \end{exercise}
  4271. \section{Earley's Algorithm}
  4272. \label{sec:earley}
  4273. In this section we discuss the parsing algorithm of
  4274. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4275. algorithm is powerful in that it can handle any context-free grammar,
  4276. which makes it easy to use, but it is not a particularly
  4277. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4278. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4279. the number of tokens in the input
  4280. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4281. learn about the LALR(1) algorithm, which is more efficient but cannot
  4282. handle all context-free grammars.
  4283. Earley's algorithm can be viewed as an interpreter; it treats the
  4284. grammar as the program being interpreted, and it treats the concrete
  4285. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4286. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4287. keep track of its progress and to store its results. The chart is an
  4288. array with one slot for each position in the input string, where
  4289. position $0$ is before the first character and position $n$ is
  4290. immediately after the last character. So, the array has length $n+1$
  4291. for an input string of length $n$. Each slot in the chart contains a
  4292. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4293. with a period indicating how much of its right-hand side has already
  4294. been parsed. For example, the dotted rule
  4295. \begin{lstlisting}
  4296. exp: exp "+" . exp_hi
  4297. \end{lstlisting}
  4298. represents a partial parse that has matched an \code{exp} followed by
  4299. \code{+} but has not yet parsed an \code{exp} to the right of
  4300. \code{+}.
  4301. %
  4302. Earley's algorithm starts with an initialization phase and then
  4303. repeats three actions---prediction, scanning, and completion---for as
  4304. long as opportunities arise. We demonstrate Earley's algorithm on a
  4305. running example, parsing the following program:
  4306. \begin{lstlisting}
  4307. print(1 + 3)
  4308. \end{lstlisting}
  4309. The algorithm's initialization phase creates dotted rules for all the
  4310. grammar rules whose left-hand side is the start symbol and places them
  4311. in slot $0$ of the chart. We also record the starting position of the
  4312. dotted rule in parentheses on the right. For example, given the
  4313. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4314. \begin{lstlisting}
  4315. lang_int: . stmt_list (0)
  4316. \end{lstlisting}
  4317. in slot $0$ of the chart. The algorithm then proceeds with
  4318. \emph{prediction} actions in which it adds more dotted rules to the
  4319. chart based on the nonterminals that come immediately after a period. In
  4320. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4321. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4322. period at the beginning of their right-hand sides, as follows:
  4323. \begin{lstlisting}
  4324. stmt_list: . (0)
  4325. stmt_list: . stmt NEWLINE stmt_list (0)
  4326. \end{lstlisting}
  4327. We continue to perform prediction actions as more opportunities
  4328. arise. For example, the \code{stmt} nonterminal now appears after a
  4329. period, so we add all the rules for \code{stmt}.
  4330. \begin{lstlisting}
  4331. stmt: . "print" "(" exp ")" (0)
  4332. stmt: . exp (0)
  4333. \end{lstlisting}
  4334. This reveals yet more opportunities for prediction, so we add the grammar
  4335. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4336. \begin{lstlisting}[escapechar=$]
  4337. exp: . exp "+" exp_hi (0)
  4338. exp: . exp "-" exp_hi (0)
  4339. exp: . exp_hi (0)
  4340. exp_hi: . INT (0)
  4341. exp_hi: . "input_int" "(" ")" (0)
  4342. exp_hi: . "-" exp_hi (0)
  4343. exp_hi: . "(" exp ")" (0)
  4344. \end{lstlisting}
  4345. We have exhausted the opportunities for prediction, so the algorithm
  4346. proceeds to \emph{scanning}, in which we inspect the next input token
  4347. and look for a dotted rule at the current position that has a matching
  4348. terminal immediately following the period. In our running example, the
  4349. first input token is \code{"print"}, so we identify the rule in slot
  4350. $0$ of the chart where \code{"print"} follows the period:
  4351. \begin{lstlisting}
  4352. stmt: . "print" "(" exp ")" (0)
  4353. \end{lstlisting}
  4354. We advance the period past \code{"print"} and add the resulting rule
  4355. to slot $1$:
  4356. \begin{lstlisting}
  4357. stmt: "print" . "(" exp ")" (0)
  4358. \end{lstlisting}
  4359. If the new dotted rule had a nonterminal after the period, we would
  4360. need to carry out a prediction action, adding more dotted rules to
  4361. slot $1$. That is not the case, so we continue scanning. The next
  4362. input token is \code{"("}, so we add the following to slot $2$ of the
  4363. chart.
  4364. \begin{lstlisting}
  4365. stmt: "print" "(" . exp ")" (0)
  4366. \end{lstlisting}
  4367. Now we have a nonterminal after the period, so we carry out several
  4368. prediction actions, adding dotted rules for \code{exp} and
  4369. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4370. starting position $2$.
  4371. \begin{lstlisting}[escapechar=$]
  4372. exp: . exp "+" exp_hi (2)
  4373. exp: . exp "-" exp_hi (2)
  4374. exp: . exp_hi (2)
  4375. exp_hi: . INT (2)
  4376. exp_hi: . "input_int" "(" ")" (2)
  4377. exp_hi: . "-" exp_hi (2)
  4378. exp_hi: . "(" exp ")" (2)
  4379. \end{lstlisting}
  4380. With this prediction complete, we return to scanning, noting that the
  4381. next input token is \code{"1"}, which the lexer parses as an
  4382. \code{INT}. There is a matching rule in slot $2$:
  4383. \begin{lstlisting}
  4384. exp_hi: . INT (2)
  4385. \end{lstlisting}
  4386. so we advance the period and put the following rule into slot $3$.
  4387. \begin{lstlisting}
  4388. exp_hi: INT . (2)
  4389. \end{lstlisting}
  4390. This brings us to \emph{completion} actions. When the period reaches
  4391. the end of a dotted rule, we recognize that the substring
  4392. has matched the nonterminal on the left-hand side of the rule, in this case
  4393. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4394. rules into slot $2$ (the starting position for the finished rule) if
  4395. the period is immediately followed by \code{exp\_hi}. So we identify
  4396. \begin{lstlisting}
  4397. exp: . exp_hi (2)
  4398. \end{lstlisting}
  4399. and add the following dotted rule to slot $3$
  4400. \begin{lstlisting}
  4401. exp: exp_hi . (2)
  4402. \end{lstlisting}
  4403. This triggers another completion step for the nonterminal \code{exp},
  4404. adding two more dotted rules to slot $3$.
  4405. \begin{lstlisting}[escapechar=$]
  4406. exp: exp . "+" exp_hi (2)
  4407. exp: exp . "-" exp_hi (2)
  4408. \end{lstlisting}
  4409. Returning to scanning, the next input token is \code{"+"}, so
  4410. we add the following to slot $4$.
  4411. \begin{lstlisting}[escapechar=$]
  4412. exp: exp "+" . exp_hi (2)
  4413. \end{lstlisting}
  4414. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4415. the following dotted rules to slot $4$ of the chart.
  4416. \begin{lstlisting}[escapechar=$]
  4417. exp_hi: . INT (4)
  4418. exp_hi: . "input_int" "(" ")" (4)
  4419. exp_hi: . "-" exp_hi (4)
  4420. exp_hi: . "(" exp ")" (4)
  4421. \end{lstlisting}
  4422. The next input token is \code{"3"} which the lexer categorized as an
  4423. \code{INT}, so we advance the period past \code{INT} for the rules in
  4424. slot $4$, of which there is just one, and put the following into slot $5$.
  4425. \begin{lstlisting}[escapechar=$]
  4426. exp_hi: INT . (4)
  4427. \end{lstlisting}
  4428. The period at the end of the rule triggers a completion action for the
  4429. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4430. So we advance the period and put the following into slot $5$.
  4431. \begin{lstlisting}[escapechar=$]
  4432. exp: exp "+" exp_hi . (2)
  4433. \end{lstlisting}
  4434. This triggers another completion action for the rules in slot $2$ that
  4435. have a period before \code{exp}.
  4436. \begin{lstlisting}[escapechar=$]
  4437. stmt: "print" "(" exp . ")" (0)
  4438. exp: exp . "+" exp_hi (2)
  4439. exp: exp . "-" exp_hi (2)
  4440. \end{lstlisting}
  4441. We scan the next input token \code{")"}, placing the following dotted
  4442. rule into slot $6$.
  4443. \begin{lstlisting}[escapechar=$]
  4444. stmt: "print" "(" exp ")" . (0)
  4445. \end{lstlisting}
  4446. This triggers the completion of \code{stmt} in slot $0$
  4447. \begin{lstlisting}
  4448. stmt_list: stmt . NEWLINE stmt_list (0)
  4449. \end{lstlisting}
  4450. The last input token is a \code{NEWLINE}, so we advance the period
  4451. and place the new dotted rule into slot $7$.
  4452. \begin{lstlisting}
  4453. stmt_list: stmt NEWLINE . stmt_list (0)
  4454. \end{lstlisting}
  4455. We are close to the end of parsing the input!
  4456. The period is before the \code{stmt\_list} nonterminal, so we
  4457. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4458. \begin{lstlisting}
  4459. stmt_list: . (7)
  4460. stmt_list: . stmt NEWLINE stmt_list (7)
  4461. stmt: . "print" "(" exp ")" (7)
  4462. stmt: . exp (7)
  4463. \end{lstlisting}
  4464. There is immediately an opportunity for completion of \code{stmt\_list},
  4465. so we add the following to slot $7$.
  4466. \begin{lstlisting}
  4467. stmt_list: stmt NEWLINE stmt_list . (0)
  4468. \end{lstlisting}
  4469. This triggers another completion action for \code{stmt\_list} in slot $0$
  4470. \begin{lstlisting}
  4471. lang_int: stmt_list . (0)
  4472. \end{lstlisting}
  4473. which in turn completes \code{lang\_int}, the start symbol of the
  4474. grammar, so the parsing of the input is complete.
  4475. For reference, we give a general description of Earley's
  4476. algorithm.
  4477. \begin{enumerate}
  4478. \item The algorithm begins by initializing slot $0$ of the chart with the
  4479. grammar rule for the start symbol, placing a period at the beginning
  4480. of the right-hand side, and recording its starting position as $0$.
  4481. \item The algorithm repeatedly applies the following three kinds of
  4482. actions for as long as there are opportunities to do so.
  4483. \begin{itemize}
  4484. \item Prediction: If there is a rule in slot $k$ whose period comes
  4485. before a nonterminal, add the rules for that nonterminal into slot
  4486. $k$, placing a period at the beginning of their right-hand sides
  4487. and recording their starting position as $k$.
  4488. \item Scanning: If the token at position $k$ of the input string
  4489. matches the symbol after the period in a dotted rule in slot $k$
  4490. of the chart, advance the period in the dotted rule, adding
  4491. the result to slot $k+1$.
  4492. \item Completion: If a dotted rule in slot $k$ has a period at the
  4493. end, inspect the rules in the slot corresponding to the starting
  4494. position of the completed rule. If any of those rules have a
  4495. nonterminal following their period that matches the left-hand side
  4496. of the completed rule, then advance their period, placing the new
  4497. dotted rule in slot $k$.
  4498. \end{itemize}
  4499. While repeating these three actions, take care never to add
  4500. duplicate dotted rules to the chart.
  4501. \end{enumerate}
  4502. We have described how Earley's algorithm recognizes that an input
  4503. string matches a grammar, but we have not described how it builds a
  4504. parse tree. The basic idea is simple, but building parse trees in an
  4505. efficient way is more complex, requiring a data structure called a
  4506. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4507. to attach a partial parse tree to every dotted rule in the chart.
  4508. Initially, the node associated with a dotted rule has no
  4509. children. As the period moves to the right, the nodes from the
  4510. subparses are added as children to the node.
  4511. As mentioned at the beginning of this section, Earley's algorithm is
  4512. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4513. files that contain thousands of tokens in a reasonable amount of time,
  4514. but not millions.
  4515. %
  4516. In the next section we discuss the LALR(1) parsing algorithm, which is
  4517. efficient enough to use with even the largest of input files.
  4518. \section{The LALR(1) Algorithm}
  4519. \label{sec:lalr}
  4520. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4521. two-phase approach in which it first compiles the grammar into a state
  4522. machine and then runs the state machine to parse an input string. The
  4523. second phase has time complexity $O(n)$ where $n$ is the number of
  4524. tokens in the input, so LALR(1) is the best one could hope for with
  4525. respect to efficiency.
  4526. %
  4527. A particularly influential implementation of LALR(1) is the
  4528. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4529. \texttt{yacc} stands for ``yet another compiler compiler.''
  4530. %
  4531. The LALR(1) state machine uses a stack to record its progress in
  4532. parsing the input string. Each element of the stack is a pair: a
  4533. state number and a grammar symbol (a terminal or a nonterminal). The
  4534. symbol characterizes the input that has been parsed so far, and the
  4535. state number is used to remember how to proceed once the next
  4536. symbol's worth of input has been parsed. Each state in the machine
  4537. represents where the parser stands in the parsing process with respect
  4538. to certain grammar rules. In particular, each state is associated with
  4539. a set of dotted rules.
  4540. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4541. (also called parse table) for the following simple but ambiguous
  4542. grammar:
  4543. \begin{lstlisting}[escapechar=$]
  4544. exp: INT
  4545. | exp "+" exp
  4546. stmt: "print" exp
  4547. start: stmt
  4548. \end{lstlisting}
  4549. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4550. read in a \lstinline{"print"} token, so the top of the stack is
  4551. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4552. the input according to grammar rule 1, which is signified by showing
  4553. rule 1 with a period after the \code{"print"} token and before the
  4554. \code{exp} nonterminal. There are two rules that could apply next,
  4555. rules 2 and 3, so state 1 also shows those rules with a period at
  4556. the beginning of their right-hand sides. The edges between states
  4557. indicate which transitions the machine should make depending on the
  4558. next input token. So, for example, if the next input token is
  4559. \code{INT} then the parser will push \code{INT} and the target state 4
  4560. on the stack and transition to state 4. Suppose that we are now at the end
  4561. of the input. State 4 says that we should reduce by rule 3, so we pop
  4562. from the stack the same number of items as the number of symbols in
  4563. the right-hand side of the rule, in this case just one. We then
  4564. momentarily jump to the state at the top of the stack (state 1) and
  4565. then follow the goto edge that corresponds to the left-hand side of
  4566. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4567. state 3. (A slightly longer example parse is shown in
  4568. figure~\ref{fig:shift-reduce}.)
  4569. \begin{figure}[tbp]
  4570. \centering
  4571. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4572. \caption{An LALR(1) parse table and a trace of an example run.}
  4573. \label{fig:shift-reduce}
  4574. \end{figure}
  4575. In general, the algorithm works as follows. First, set the current state to
  4576. state $0$. Then repeat the following, looking at the next input token.
  4577. \begin{itemize}
  4578. \item If there there is a shift edge for the input token in the
  4579. current state, push the edge's target state and the input token onto
  4580. the stack and proceed to the edge's target state.
  4581. \item If there is a reduce action for the input token in the current
  4582. state, pop $k$ elements from the stack, where $k$ is the number of
  4583. symbols in the right-hand side of the rule being reduced. Jump to
  4584. the state at the top of the stack and then follow the goto edge for
  4585. the nonterminal that matches the left-hand side of the rule that we
  4586. are reducing by. Push the edge's target state and the nonterminal on the
  4587. stack.
  4588. \end{itemize}
  4589. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4590. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4591. algorithm does not know which action to take in this case. When a
  4592. state has both a shift and a reduce action for the same token, we say
  4593. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4594. will arise, for example, in trying to parse the input
  4595. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4596. the parser will be in state 6 and will not know whether to
  4597. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4598. to proceed by shifting the next \lstinline{+} from the input.
  4599. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4600. arises when there are two reduce actions in a state for the same
  4601. token. To understand which grammars give rise to shift/reduce and
  4602. reduce/reduce conflicts, it helps to know how the parse table is
  4603. generated from the grammar, which we discuss next.
  4604. The parse table is generated one state at a time. State 0 represents
  4605. the start of the parser. We add the grammar rule for the start symbol
  4606. to this state with a period at the beginning of the right-hand side,
  4607. similarly to the initialization phase of the Earley parser. If the
  4608. period appears immediately before another nonterminal, we add all the
  4609. rules with that nonterminal on the left-hand side. Again, we place a
  4610. period at the beginning of the right-hand side of each new
  4611. rule. This process, called \emph{state closure}, is continued
  4612. until there are no more rules to add (similarly to the prediction
  4613. actions of an Earley parser). We then examine each dotted rule in the
  4614. current state $I$. Suppose that a dotted rule has the form $A ::=
  4615. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4616. are sequences of symbols. We create a new state and call it $J$. If $X$
  4617. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4618. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4619. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4620. state $J$. We start by adding all dotted rules from state $I$ that
  4621. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4622. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4623. the period moved past the $X$. (This is analogous to completion in
  4624. Earley's algorithm.) We then perform state closure on $J$. This
  4625. process repeats until there are no more states or edges to add.
  4626. We then mark states as accepting states if they have a dotted rule
  4627. that is the start rule with a period at the end. Also, to add
  4628. the reduce actions, we look for any state containing a dotted rule
  4629. with a period at the end. Let $n$ be the rule number for this dotted
  4630. rule. We then put a reduce $n$ action into that state for every token
  4631. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4632. dotted rule with a period at the end. We therefore put a reduce by
  4633. rule 3 action into state 4 for every
  4634. token.
  4635. When inserting reduce actions, take care to spot any shift/reduce or
  4636. reduce/reduce conflicts. If there are any, abort the construction of
  4637. the parse table.
  4638. \begin{exercise}
  4639. \normalfont\normalsize
  4640. %
  4641. Working on paper, walk through the parse table generation process for
  4642. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4643. your results against the parse table shown in
  4644. figure~\ref{fig:shift-reduce}.
  4645. \end{exercise}
  4646. \begin{exercise}
  4647. \normalfont\normalsize
  4648. %
  4649. Change the parser in your compiler for \LangVar{} to set the
  4650. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4651. all the \LangVar{} programs that you have created. In doing so, Lark
  4652. may signal an error due to shift/reduce or reduce/reduce conflicts
  4653. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4654. remove those conflicts.
  4655. \end{exercise}
  4656. \section{Further Reading}
  4657. In this chapter we have just scratched the surface of the field of
  4658. parsing, with the study of a very general but less efficient algorithm
  4659. (Earley) and with a more limited but highly efficient algorithm
  4660. (LALR). There are many more algorithms and classes of grammars that
  4661. fall between these two ends of the spectrum. We recommend to the reader
  4662. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4663. Regarding lexical analysis, we have described the specification
  4664. language, which are the regular expressions, but not the algorithms
  4665. for recognizing them. In short, regular expressions can be translated
  4666. to nondeterministic finite automata, which in turn are translated to
  4667. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4668. all the details on lexical analysis.
  4669. \fi}
  4670. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4671. \chapter{Register Allocation}
  4672. \label{ch:register-allocation-Lvar}
  4673. \setcounter{footnote}{0}
  4674. \index{subject}{register allocation}
  4675. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4676. storing variables on the procedure call stack. The CPU may require tens
  4677. to hundreds of cycles to access a location on the stack, whereas
  4678. accessing a register takes only a single cycle. In this chapter we
  4679. improve the efficiency of our generated code by storing some variables
  4680. in registers. The goal of register allocation is to fit as many
  4681. variables into registers as possible. Some programs have more
  4682. variables than registers, so we cannot always map each variable to a
  4683. different register. Fortunately, it is common for different variables
  4684. to be in use during different periods of time during program
  4685. execution, and in those cases we can map multiple variables to the
  4686. same register.
  4687. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4688. example. The source program is on the left and the output of
  4689. instruction selection\index{subject}{instruction selection}
  4690. is on the right. The program is almost
  4691. completely in the x86 assembly language, but it still uses variables.
  4692. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4693. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4694. the other hand, is used only after this point, so \code{x} and
  4695. \code{z} could share the same register.
  4696. \begin{figure}
  4697. \begin{tcolorbox}[colback=white]
  4698. \begin{minipage}{0.45\textwidth}
  4699. Example \LangVar{} program:
  4700. % var_test_28.rkt
  4701. {\if\edition\racketEd
  4702. \begin{lstlisting}
  4703. (let ([v 1])
  4704. (let ([w 42])
  4705. (let ([x (+ v 7)])
  4706. (let ([y x])
  4707. (let ([z (+ x w)])
  4708. (+ z (- y)))))))
  4709. \end{lstlisting}
  4710. \fi}
  4711. {\if\edition\pythonEd\pythonColor
  4712. \begin{lstlisting}
  4713. v = 1
  4714. w = 42
  4715. x = v + 7
  4716. y = x
  4717. z = x + w
  4718. print(z + (- y))
  4719. \end{lstlisting}
  4720. \fi}
  4721. \end{minipage}
  4722. \begin{minipage}{0.45\textwidth}
  4723. After instruction selection:
  4724. {\if\edition\racketEd
  4725. \begin{lstlisting}
  4726. locals-types:
  4727. x : Integer, y : Integer,
  4728. z : Integer, t : Integer,
  4729. v : Integer, w : Integer
  4730. start:
  4731. movq $1, v
  4732. movq $42, w
  4733. movq v, x
  4734. addq $7, x
  4735. movq x, y
  4736. movq x, z
  4737. addq w, z
  4738. movq y, t
  4739. negq t
  4740. movq z, %rax
  4741. addq t, %rax
  4742. jmp conclusion
  4743. \end{lstlisting}
  4744. \fi}
  4745. {\if\edition\pythonEd\pythonColor
  4746. \begin{lstlisting}
  4747. movq $1, v
  4748. movq $42, w
  4749. movq v, x
  4750. addq $7, x
  4751. movq x, y
  4752. movq x, z
  4753. addq w, z
  4754. movq y, tmp_0
  4755. negq tmp_0
  4756. movq z, tmp_1
  4757. addq tmp_0, tmp_1
  4758. movq tmp_1, %rdi
  4759. callq print_int
  4760. \end{lstlisting}
  4761. \fi}
  4762. \end{minipage}
  4763. \end{tcolorbox}
  4764. \caption{A running example for register allocation.}
  4765. \label{fig:reg-eg}
  4766. \end{figure}
  4767. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4768. compute where a variable is in use. Once we have that information, we
  4769. compute which variables are in use at the same time, that is, which ones
  4770. \emph{interfere}\index{subject}{interfere} with each other, and
  4771. represent this relation as an undirected graph whose vertices are
  4772. variables and edges indicate when two variables interfere
  4773. (section~\ref{sec:build-interference}). We then model register
  4774. allocation as a graph coloring problem
  4775. (section~\ref{sec:graph-coloring}).
  4776. If we run out of registers despite these efforts, we place the
  4777. remaining variables on the stack, similarly to how we handled
  4778. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4779. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4780. location. The decision to spill a variable is handled as part of the
  4781. graph coloring process.
  4782. We make the simplifying assumption that each variable is assigned to
  4783. one location (a register or stack address). A more sophisticated
  4784. approach is to assign a variable to one or more locations in different
  4785. regions of the program. For example, if a variable is used many times
  4786. in short sequence and then used again only after many other
  4787. instructions, it could be more efficient to assign the variable to a
  4788. register during the initial sequence and then move it to the stack for
  4789. the rest of its lifetime. We refer the interested reader to
  4790. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4791. approach.
  4792. % discuss prioritizing variables based on how much they are used.
  4793. \section{Registers and Calling Conventions}
  4794. \label{sec:calling-conventions}
  4795. \index{subject}{calling conventions}
  4796. As we perform register allocation, we must be aware of the
  4797. \emph{calling conventions} \index{subject}{calling conventions} that
  4798. govern how function calls are performed in x86.
  4799. %
  4800. Even though \LangVar{} does not include programmer-defined functions,
  4801. our generated code includes a \code{main} function that is called by
  4802. the operating system and our generated code contains calls to the
  4803. \code{read\_int} function.
  4804. Function calls require coordination between two pieces of code that
  4805. may be written by different programmers or generated by different
  4806. compilers. Here we follow the System V calling conventions that are
  4807. used by the GNU C compiler on Linux and
  4808. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4809. %
  4810. The calling conventions include rules about how functions share the
  4811. use of registers. In particular, the caller is responsible for freeing
  4812. some registers prior to the function call for use by the callee.
  4813. These are called the \emph{caller-saved registers}
  4814. \index{subject}{caller-saved registers}
  4815. and they are
  4816. \begin{lstlisting}
  4817. rax rcx rdx rsi rdi r8 r9 r10 r11
  4818. \end{lstlisting}
  4819. On the other hand, the callee is responsible for preserving the values
  4820. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4821. which are
  4822. \begin{lstlisting}
  4823. rsp rbp rbx r12 r13 r14 r15
  4824. \end{lstlisting}
  4825. We can think about this caller/callee convention from two points of
  4826. view, the caller view and the callee view, as follows:
  4827. \begin{itemize}
  4828. \item The caller should assume that all the caller-saved registers get
  4829. overwritten with arbitrary values by the callee. On the other hand,
  4830. the caller can safely assume that all the callee-saved registers
  4831. retain their original values.
  4832. \item The callee can freely use any of the caller-saved registers.
  4833. However, if the callee wants to use a callee-saved register, the
  4834. callee must arrange to put the original value back in the register
  4835. prior to returning to the caller. This can be accomplished by saving
  4836. the value to the stack in the prelude of the function and restoring
  4837. the value in the conclusion of the function.
  4838. \end{itemize}
  4839. In x86, registers are also used for passing arguments to a function
  4840. and for the return value. In particular, the first six arguments of a
  4841. function are passed in the following six registers, in this order.
  4842. \begin{lstlisting}
  4843. rdi rsi rdx rcx r8 r9
  4844. \end{lstlisting}
  4845. We refer to these six registers are the argument-passing registers
  4846. \index{subject}{argument-passing registers}.
  4847. If there are more than six arguments, the convention is to use space
  4848. on the frame of the caller for the rest of the arguments. In
  4849. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4850. argument and the rest of the arguments, which simplifies the treatment
  4851. of efficient tail calls.
  4852. %
  4853. \racket{For now, the only function we care about is \code{read\_int},
  4854. which takes zero arguments.}
  4855. %
  4856. \python{For now, the only functions we care about are \code{read\_int}
  4857. and \code{print\_int}, which take zero and one argument, respectively.}
  4858. %
  4859. The register \code{rax} is used for the return value of a function.
  4860. The next question is how these calling conventions impact register
  4861. allocation. Consider the \LangVar{} program presented in
  4862. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4863. example from the caller point of view and then from the callee point
  4864. of view. We refer to a variable that is in use during a function call
  4865. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4866. The program makes two calls to \READOP{}. The variable \code{x} is
  4867. call-live because it is in use during the second call to \READOP{}; we
  4868. must ensure that the value in \code{x} does not get overwritten during
  4869. the call to \READOP{}. One obvious approach is to save all the values
  4870. that reside in caller-saved registers to the stack prior to each
  4871. function call and to restore them after each call. That way, if the
  4872. register allocator chooses to assign \code{x} to a caller-saved
  4873. register, its value will be preserved across the call to \READOP{}.
  4874. However, saving and restoring to the stack is relatively slow. If
  4875. \code{x} is not used many times, it may be better to assign \code{x}
  4876. to a stack location in the first place. Or better yet, if we can
  4877. arrange for \code{x} to be placed in a callee-saved register, then it
  4878. won't need to be saved and restored during function calls.
  4879. We recommend an approach that captures these issues in the
  4880. interference graph, without complicating the graph coloring algorithm.
  4881. During liveness analysis we know which variables are call-live because
  4882. we compute which variables are in use at every instruction
  4883. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4884. interference graph (section~\ref{sec:build-interference}), we can
  4885. place an edge in the interference graph between each call-live
  4886. variable and the caller-saved registers. This will prevent the graph
  4887. coloring algorithm from assigning call-live variables to caller-saved
  4888. registers.
  4889. On the other hand, for variables that are not call-live, we prefer
  4890. placing them in caller-saved registers to leave more room for
  4891. call-live variables in the callee-saved registers. This can also be
  4892. implemented without complicating the graph coloring algorithm. We
  4893. recommend that the graph coloring algorithm assign variables to
  4894. natural numbers, choosing the lowest number for which there is no
  4895. interference. After the coloring is complete, we map the numbers to
  4896. registers and stack locations: mapping the lowest numbers to
  4897. caller-saved registers, the next lowest to callee-saved registers, and
  4898. the largest numbers to stack locations. This ordering gives preference
  4899. to registers over stack locations and to caller-saved registers over
  4900. callee-saved registers.
  4901. Returning to the example in
  4902. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4903. generated x86 code on the right-hand side. Variable \code{x} is
  4904. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4905. in a safe place during the second call to \code{read\_int}. Next,
  4906. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4907. because \code{y} is not a call-live variable.
  4908. We have completed the analysis from the caller point of view, so now
  4909. we switch to the callee point of view, focusing on the prelude and
  4910. conclusion of the \code{main} function. As usual, the prelude begins
  4911. with saving the \code{rbp} register to the stack and setting the
  4912. \code{rbp} to the current stack pointer. We now know why it is
  4913. necessary to save the \code{rbp}: it is a callee-saved register. The
  4914. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4915. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4916. (\code{x}). The other callee-saved registers are not saved in the
  4917. prelude because they are not used. The prelude subtracts 8 bytes from
  4918. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4919. conclusion, we see that \code{rbx} is restored from the stack with a
  4920. \code{popq} instruction.
  4921. \index{subject}{prelude}\index{subject}{conclusion}
  4922. \begin{figure}[tp]
  4923. \begin{tcolorbox}[colback=white]
  4924. \begin{minipage}{0.45\textwidth}
  4925. Example \LangVar{} program:
  4926. %var_test_14.rkt
  4927. {\if\edition\racketEd
  4928. \begin{lstlisting}
  4929. (let ([x (read)])
  4930. (let ([y (read)])
  4931. (+ (+ x y) 42)))
  4932. \end{lstlisting}
  4933. \fi}
  4934. {\if\edition\pythonEd\pythonColor
  4935. \begin{lstlisting}
  4936. x = input_int()
  4937. y = input_int()
  4938. print((x + y) + 42)
  4939. \end{lstlisting}
  4940. \fi}
  4941. \end{minipage}
  4942. \begin{minipage}{0.45\textwidth}
  4943. Generated x86 assembly:
  4944. {\if\edition\racketEd
  4945. \begin{lstlisting}
  4946. start:
  4947. callq read_int
  4948. movq %rax, %rbx
  4949. callq read_int
  4950. movq %rax, %rcx
  4951. addq %rcx, %rbx
  4952. movq %rbx, %rax
  4953. addq $42, %rax
  4954. jmp conclusion
  4955. .globl main
  4956. main:
  4957. pushq %rbp
  4958. movq %rsp, %rbp
  4959. pushq %rbx
  4960. subq $8, %rsp
  4961. jmp start
  4962. conclusion:
  4963. addq $8, %rsp
  4964. popq %rbx
  4965. popq %rbp
  4966. retq
  4967. \end{lstlisting}
  4968. \fi}
  4969. {\if\edition\pythonEd\pythonColor
  4970. \begin{lstlisting}
  4971. .globl main
  4972. main:
  4973. pushq %rbp
  4974. movq %rsp, %rbp
  4975. pushq %rbx
  4976. subq $8, %rsp
  4977. callq read_int
  4978. movq %rax, %rbx
  4979. callq read_int
  4980. movq %rax, %rcx
  4981. movq %rbx, %rdx
  4982. addq %rcx, %rdx
  4983. movq %rdx, %rcx
  4984. addq $42, %rcx
  4985. movq %rcx, %rdi
  4986. callq print_int
  4987. addq $8, %rsp
  4988. popq %rbx
  4989. popq %rbp
  4990. retq
  4991. \end{lstlisting}
  4992. \fi}
  4993. \end{minipage}
  4994. \end{tcolorbox}
  4995. \caption{An example with function calls.}
  4996. \label{fig:example-calling-conventions}
  4997. \end{figure}
  4998. %\clearpage
  4999. \section{Liveness Analysis}
  5000. \label{sec:liveness-analysis-Lvar}
  5001. \index{subject}{liveness analysis}
  5002. The \code{uncover\_live} \racket{pass}\python{function} performs
  5003. \emph{liveness analysis}; that is, it discovers which variables are
  5004. in use in different regions of a program.
  5005. %
  5006. A variable or register is \emph{live} at a program point if its
  5007. current value is used at some later point in the program. We refer to
  5008. variables, stack locations, and registers collectively as
  5009. \emph{locations}.
  5010. %
  5011. Consider the following code fragment in which there are two writes to
  5012. \code{b}. Are variables \code{a} and \code{b} both live at the same
  5013. time?
  5014. \begin{center}
  5015. \begin{minipage}{0.85\textwidth}
  5016. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5017. movq $5, a
  5018. movq $30, b
  5019. movq a, c
  5020. movq $10, b
  5021. addq b, c
  5022. \end{lstlisting}
  5023. \end{minipage}
  5024. \end{center}
  5025. The answer is no, because \code{a} is live from line 1 to 3 and
  5026. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5027. line 2 is never used because it is overwritten (line 4) before the
  5028. next read (line 5).
  5029. The live locations for each instruction can be computed by traversing
  5030. the instruction sequence back to front (i.e., backward in execution
  5031. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5032. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5033. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5034. locations before instruction $I_k$. \racket{We recommend representing
  5035. these sets with the Racket \code{set} data structure described in
  5036. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5037. with the Python
  5038. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5039. data structure.}
  5040. {\if\edition\racketEd
  5041. \begin{figure}[tp]
  5042. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5043. \small
  5044. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5045. A \emph{set} is an unordered collection of elements without duplicates.
  5046. Here are some of the operations defined on sets.
  5047. \index{subject}{set}
  5048. \begin{description}
  5049. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5050. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5051. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5052. difference of the two sets.
  5053. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5054. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5055. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5056. \end{description}
  5057. \end{tcolorbox}
  5058. %\end{wrapfigure}
  5059. \caption{The \code{set} data structure.}
  5060. \label{fig:set}
  5061. \end{figure}
  5062. \fi}
  5063. % TODO: add a python version of the reference box for sets. -Jeremy
  5064. The locations that are live after an instruction are its
  5065. \emph{live-after}\index{subject}{live-after} set, and the locations
  5066. that are live before an instruction are its
  5067. \emph{live-before}\index{subject}{live-before} set. The live-after
  5068. set of an instruction is always the same as the live-before set of the
  5069. next instruction.
  5070. \begin{equation} \label{eq:live-after-before-next}
  5071. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5072. \end{equation}
  5073. To start things off, there are no live locations after the last
  5074. instruction, so
  5075. \begin{equation}\label{eq:live-last-empty}
  5076. L_{\mathsf{after}}(n) = \emptyset
  5077. \end{equation}
  5078. We then apply the following rule repeatedly, traversing the
  5079. instruction sequence back to front.
  5080. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5081. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5082. \end{equation}
  5083. where $W(k)$ are the locations written to by instruction $I_k$, and
  5084. $R(k)$ are the locations read by instruction $I_k$.
  5085. {\if\edition\racketEd
  5086. %
  5087. There is a special case for \code{jmp} instructions. The locations
  5088. that are live before a \code{jmp} should be the locations in
  5089. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5090. maintaining an alist named \code{label->live} that maps each label to
  5091. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5092. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5093. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5094. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5095. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5096. %
  5097. \fi}
  5098. Let us walk through the previous example, applying these formulas
  5099. starting with the instruction on line 5 of the code fragment. We
  5100. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5101. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5102. $\emptyset$ because it is the last instruction
  5103. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5104. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5105. variables \code{b} and \code{c}
  5106. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5107. \[
  5108. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5109. \]
  5110. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5111. the live-before set from line 5 to be the live-after set for this
  5112. instruction (formula~\eqref{eq:live-after-before-next}).
  5113. \[
  5114. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5115. \]
  5116. This move instruction writes to \code{b} and does not read from any
  5117. variables, so we have the following live-before set
  5118. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5119. \[
  5120. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5121. \]
  5122. The live-before for instruction \code{movq a, c}
  5123. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5124. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5125. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5126. variable that is not live and does not read from a variable.
  5127. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5128. because it writes to variable \code{a}.
  5129. \begin{figure}[tbp]
  5130. \centering
  5131. \begin{tcolorbox}[colback=white]
  5132. \hspace{10pt}
  5133. \begin{minipage}{0.4\textwidth}
  5134. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5135. movq $5, a
  5136. movq $30, b
  5137. movq a, c
  5138. movq $10, b
  5139. addq b, c
  5140. \end{lstlisting}
  5141. \end{minipage}
  5142. \vrule\hspace{10pt}
  5143. \begin{minipage}{0.45\textwidth}
  5144. \begin{align*}
  5145. L_{\mathsf{before}}(1)= \emptyset,
  5146. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5147. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5148. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5149. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5150. L_{\mathsf{after}}(3)= \{\ttm{c}\}\\
  5151. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5152. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5153. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5154. L_{\mathsf{after}}(5)= \emptyset
  5155. \end{align*}
  5156. \end{minipage}
  5157. \end{tcolorbox}
  5158. \caption{Example output of liveness analysis on a short example.}
  5159. \label{fig:liveness-example-0}
  5160. \end{figure}
  5161. \begin{exercise}\normalfont\normalsize
  5162. Perform liveness analysis by hand on the running example in
  5163. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5164. sets for each instruction. Compare your answers to the solution
  5165. shown in figure~\ref{fig:live-eg}.
  5166. \end{exercise}
  5167. \begin{figure}[tp]
  5168. \hspace{20pt}
  5169. \begin{minipage}{0.55\textwidth}
  5170. \begin{tcolorbox}[colback=white]
  5171. {\if\edition\racketEd
  5172. \begin{lstlisting}
  5173. |$\{\ttm{rsp}\}$|
  5174. movq $1, v
  5175. |$\{\ttm{v},\ttm{rsp}\}$|
  5176. movq $42, w
  5177. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5178. movq v, x
  5179. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5180. addq $7, x
  5181. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5182. movq x, y
  5183. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5184. movq x, z
  5185. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5186. addq w, z
  5187. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5188. movq y, t
  5189. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5190. negq t
  5191. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5192. movq z, %rax
  5193. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5194. addq t, %rax
  5195. |$\{\ttm{rax},\ttm{rsp}\}$|
  5196. jmp conclusion
  5197. \end{lstlisting}
  5198. \fi}
  5199. {\if\edition\pythonEd\pythonColor
  5200. \begin{lstlisting}
  5201. movq $1, v
  5202. |$\{\ttm{v}\}$|
  5203. movq $42, w
  5204. |$\{\ttm{w}, \ttm{v}\}$|
  5205. movq v, x
  5206. |$\{\ttm{w}, \ttm{x}\}$|
  5207. addq $7, x
  5208. |$\{\ttm{w}, \ttm{x}\}$|
  5209. movq x, y
  5210. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5211. movq x, z
  5212. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5213. addq w, z
  5214. |$\{\ttm{y}, \ttm{z}\}$|
  5215. movq y, tmp_0
  5216. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5217. negq tmp_0
  5218. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5219. movq z, tmp_1
  5220. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5221. addq tmp_0, tmp_1
  5222. |$\{\ttm{tmp\_1}\}$|
  5223. movq tmp_1, %rdi
  5224. |$\{\ttm{rdi}\}$|
  5225. callq print_int
  5226. |$\{\}$|
  5227. \end{lstlisting}
  5228. \fi}
  5229. \end{tcolorbox}
  5230. \end{minipage}
  5231. \caption{The running example annotated with live-after sets.}
  5232. \label{fig:live-eg}
  5233. \end{figure}
  5234. \begin{exercise}\normalfont\normalsize
  5235. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5236. %
  5237. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5238. field of the \code{Block} structure.}
  5239. %
  5240. \python{Return a dictionary that maps each instruction to its
  5241. live-after set.}
  5242. %
  5243. \racket{We recommend creating an auxiliary function that takes a list
  5244. of instructions and an initial live-after set (typically empty) and
  5245. returns the list of live-after sets.}
  5246. %
  5247. We recommend creating auxiliary functions to (1) compute the set
  5248. of locations that appear in an \Arg{}, (2) compute the locations read
  5249. by an instruction (the $R$ function), and (3) the locations written by
  5250. an instruction (the $W$ function). The \code{callq} instruction should
  5251. include all the caller-saved registers in its write set $W$ because
  5252. the calling convention says that those registers may be written to
  5253. during the function call. Likewise, the \code{callq} instruction
  5254. should include the appropriate argument-passing registers in its
  5255. read set $R$, depending on the arity of the function being
  5256. called. (This is why the abstract syntax for \code{callq} includes the
  5257. arity.)
  5258. \end{exercise}
  5259. %\clearpage
  5260. \section{Build the Interference Graph}
  5261. \label{sec:build-interference}
  5262. {\if\edition\racketEd
  5263. \begin{figure}[tp]
  5264. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5265. \small
  5266. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5267. A \emph{graph} is a collection of vertices and edges where each
  5268. edge connects two vertices. A graph is \emph{directed} if each
  5269. edge points from a source to a target. Otherwise the graph is
  5270. \emph{undirected}.
  5271. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5272. \begin{description}
  5273. %% We currently don't use directed graphs. We instead use
  5274. %% directed multi-graphs. -Jeremy
  5275. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5276. directed graph from a list of edges. Each edge is a list
  5277. containing the source and target vertex.
  5278. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5279. undirected graph from a list of edges. Each edge is represented by
  5280. a list containing two vertices.
  5281. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5282. inserts a vertex into the graph.
  5283. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5284. inserts an edge between the two vertices.
  5285. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5286. returns a sequence of vertices adjacent to the vertex.
  5287. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5288. returns a sequence of all vertices in the graph.
  5289. \end{description}
  5290. \end{tcolorbox}
  5291. %\end{wrapfigure}
  5292. \caption{The Racket \code{graph} package.}
  5293. \label{fig:graph}
  5294. \end{figure}
  5295. \fi}
  5296. On the basis of the liveness analysis, we know where each location is
  5297. live. However, during register allocation, we need to answer
  5298. questions of the specific form: are locations $u$ and $v$ live at the
  5299. same time? (If so, they cannot be assigned to the same register.) To
  5300. make this question more efficient to answer, we create an explicit
  5301. data structure, an \emph{interference
  5302. graph}\index{subject}{interference graph}. An interference graph is
  5303. an undirected graph that has a node for every variable and register
  5304. and has an edge between two nodes if they are
  5305. live at the same time, that is, if they interfere with each other.
  5306. %
  5307. \racket{We recommend using the Racket \code{graph} package
  5308. (figure~\ref{fig:graph}) to represent the interference graph.}
  5309. %
  5310. \python{We provide implementations of directed and undirected graph
  5311. data structures in the file \code{graph.py} of the support code.}
  5312. A straightforward way to compute the interference graph is to look at
  5313. the set of live locations between each instruction and add an edge to
  5314. the graph for every pair of variables in the same set. This approach
  5315. is less than ideal for two reasons. First, it can be expensive because
  5316. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5317. locations. Second, in the special case in which two locations hold the
  5318. same value (because one was assigned to the other), they can be live
  5319. at the same time without interfering with each other.
  5320. A better way to compute the interference graph is to focus on
  5321. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5322. must not overwrite something in a live location. So for each
  5323. instruction, we create an edge between the locations being written to
  5324. and the live locations. (However, a location never interferes with
  5325. itself.) For the \key{callq} instruction, we consider all the
  5326. caller-saved registers to have been written to, so an edge is added
  5327. between every live variable and every caller-saved register. Also, for
  5328. \key{movq} there is the special case of two variables holding the same
  5329. value. If a live variable $v$ is the same as the source of the
  5330. \key{movq}, then there is no need to add an edge between $v$ and the
  5331. destination, because they both hold the same value.
  5332. %
  5333. Hence we have the following two rules:
  5334. \begin{enumerate}
  5335. \item If instruction $I_k$ is a move instruction of the form
  5336. \key{movq} $s$\key{,} $d$, then for every $v \in
  5337. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5338. $(d,v)$.
  5339. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5340. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5341. $(d,v)$.
  5342. \end{enumerate}
  5343. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5344. these rules to each instruction. We highlight a few of the
  5345. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5346. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5347. so \code{v} interferes with \code{rsp}.}
  5348. %
  5349. \python{The first instruction is \lstinline{movq $1, v}, and the
  5350. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5351. no interference because $\ttm{v}$ is the destination of the move.}
  5352. %
  5353. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5354. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5355. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5356. %
  5357. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5358. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5359. $\ttm{x}$ interferes with \ttm{w}.}
  5360. %
  5361. \racket{The next instruction is \lstinline{movq x, y}, and the
  5362. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5363. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5364. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5365. \ttm{x} and \ttm{y} hold the same value.}
  5366. %
  5367. \python{The next instruction is \lstinline{movq x, y}, and the
  5368. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5369. applies, so \ttm{y} interferes with \ttm{w} but not
  5370. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5371. \ttm{x} and \ttm{y} hold the same value.}
  5372. %
  5373. Figure~\ref{fig:interference-results} lists the interference results
  5374. for all the instructions, and the resulting interference graph is
  5375. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5376. the interference graph in figure~\ref{fig:interfere} because there
  5377. were no interference edges involving registers and we did not wish to
  5378. clutter the graph, but in general one needs to include all the
  5379. registers in the interference graph.
  5380. \begin{figure}[tbp]
  5381. \begin{tcolorbox}[colback=white]
  5382. \begin{quote}
  5383. {\if\edition\racketEd
  5384. \begin{tabular}{ll}
  5385. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5386. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5387. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5388. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5389. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5390. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5391. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5392. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5393. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5394. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5395. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5396. \lstinline!jmp conclusion!& no interference.
  5397. \end{tabular}
  5398. \fi}
  5399. {\if\edition\pythonEd\pythonColor
  5400. \begin{tabular}{ll}
  5401. \lstinline!movq $1, v!& no interference\\
  5402. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5403. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5404. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5405. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5406. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5407. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5408. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5409. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5410. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5411. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5412. \lstinline!movq tmp_1, %rdi! & no interference \\
  5413. \lstinline!callq print_int!& no interference.
  5414. \end{tabular}
  5415. \fi}
  5416. \end{quote}
  5417. \end{tcolorbox}
  5418. \caption{Interference results for the running example.}
  5419. \label{fig:interference-results}
  5420. \end{figure}
  5421. \begin{figure}[tbp]
  5422. \begin{tcolorbox}[colback=white]
  5423. \large
  5424. {\if\edition\racketEd
  5425. \[
  5426. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5427. \node (rax) at (0,0) {$\ttm{rax}$};
  5428. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5429. \node (t1) at (0,2) {$\ttm{t}$};
  5430. \node (z) at (3,2) {$\ttm{z}$};
  5431. \node (x) at (6,2) {$\ttm{x}$};
  5432. \node (y) at (3,0) {$\ttm{y}$};
  5433. \node (w) at (6,0) {$\ttm{w}$};
  5434. \node (v) at (9,0) {$\ttm{v}$};
  5435. \draw (t1) to (rax);
  5436. \draw (t1) to (z);
  5437. \draw (z) to (y);
  5438. \draw (z) to (w);
  5439. \draw (x) to (w);
  5440. \draw (y) to (w);
  5441. \draw (v) to (w);
  5442. \draw (v) to (rsp);
  5443. \draw (w) to (rsp);
  5444. \draw (x) to (rsp);
  5445. \draw (y) to (rsp);
  5446. \path[-.,bend left=15] (z) edge node {} (rsp);
  5447. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5448. \draw (rax) to (rsp);
  5449. \end{tikzpicture}
  5450. \]
  5451. \fi}
  5452. {\if\edition\pythonEd\pythonColor
  5453. \[
  5454. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5455. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5456. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5457. \node (z) at (3,2) {$\ttm{z}$};
  5458. \node (x) at (6,2) {$\ttm{x}$};
  5459. \node (y) at (3,0) {$\ttm{y}$};
  5460. \node (w) at (6,0) {$\ttm{w}$};
  5461. \node (v) at (9,0) {$\ttm{v}$};
  5462. \draw (t0) to (t1);
  5463. \draw (t0) to (z);
  5464. \draw (z) to (y);
  5465. \draw (z) to (w);
  5466. \draw (x) to (w);
  5467. \draw (y) to (w);
  5468. \draw (v) to (w);
  5469. \end{tikzpicture}
  5470. \]
  5471. \fi}
  5472. \end{tcolorbox}
  5473. \caption{The interference graph of the example program.}
  5474. \label{fig:interfere}
  5475. \end{figure}
  5476. \begin{exercise}\normalfont\normalsize
  5477. \racket{Implement the compiler pass named \code{build\_interference} according
  5478. to the algorithm suggested here. We recommend using the Racket
  5479. \code{graph} package to create and inspect the interference graph.
  5480. The output graph of this pass should be stored in the $\itm{info}$ field of
  5481. the program, under the key \code{conflicts}.}
  5482. %
  5483. \python{Implement a function named \code{build\_interference}
  5484. according to the algorithm suggested above that
  5485. returns the interference graph.}
  5486. \end{exercise}
  5487. \section{Graph Coloring via Sudoku}
  5488. \label{sec:graph-coloring}
  5489. \index{subject}{graph coloring}
  5490. \index{subject}{sudoku}
  5491. \index{subject}{color}
  5492. We come to the main event discussed in this chapter, mapping variables
  5493. to registers and stack locations. Variables that interfere with each
  5494. other must be mapped to different locations. In terms of the
  5495. interference graph, this means that adjacent vertices must be mapped
  5496. to different locations. If we think of locations as colors, the
  5497. register allocation problem becomes the graph coloring
  5498. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5499. The reader may be more familiar with the graph coloring problem than he
  5500. or she realizes; the popular game of sudoku is an instance of the
  5501. graph coloring problem. The following describes how to build a graph
  5502. out of an initial sudoku board.
  5503. \begin{itemize}
  5504. \item There is one vertex in the graph for each sudoku square.
  5505. \item There is an edge between two vertices if the corresponding squares
  5506. are in the same row, in the same column, or in the same $3\times 3$ region.
  5507. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5508. \item On the basis of the initial assignment of numbers to squares on the
  5509. sudoku board, assign the corresponding colors to the corresponding
  5510. vertices in the graph.
  5511. \end{itemize}
  5512. If you can color the remaining vertices in the graph with the nine
  5513. colors, then you have also solved the corresponding game of sudoku.
  5514. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5515. the corresponding graph with colored vertices. Here we use a
  5516. monochrome representation of colors, mapping the sudoku number 1 to
  5517. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5518. of the vertices (the colored ones) because showing edges for all the
  5519. vertices would make the graph unreadable.
  5520. \begin{figure}[tbp]
  5521. \begin{tcolorbox}[colback=white]
  5522. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5523. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5524. \end{tcolorbox}
  5525. \caption{A sudoku game board and the corresponding colored graph.}
  5526. \label{fig:sudoku-graph}
  5527. \end{figure}
  5528. Some techniques for playing sudoku correspond to heuristics used in
  5529. graph coloring algorithms. For example, one of the basic techniques
  5530. for sudoku is called Pencil Marks. The idea is to use a process of
  5531. elimination to determine what numbers are no longer available for a
  5532. square and to write those numbers in the square (writing very
  5533. small). For example, if the number $1$ is assigned to a square, then
  5534. write the pencil mark $1$ in all the squares in the same row, column,
  5535. and region to indicate that $1$ is no longer an option for those other
  5536. squares.
  5537. %
  5538. The Pencil Marks technique corresponds to the notion of
  5539. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5540. saturation of a vertex, in sudoku terms, is the set of numbers that
  5541. are no longer available. In graph terminology, we have the following
  5542. definition:
  5543. \begin{equation*}
  5544. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5545. \text{ and } \mathrm{color}(v) = c \}
  5546. \end{equation*}
  5547. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5548. edge with $u$.
  5549. The Pencil Marks technique leads to a simple strategy for filling in
  5550. numbers: if there is a square with only one possible number left, then
  5551. choose that number! But what if there are no squares with only one
  5552. possibility left? One brute-force approach is to try them all: choose
  5553. the first one, and if that ultimately leads to a solution, great. If
  5554. not, backtrack and choose the next possibility. One good thing about
  5555. Pencil Marks is that it reduces the degree of branching in the search
  5556. tree. Nevertheless, backtracking can be terribly time consuming. One
  5557. way to reduce the amount of backtracking is to use the
  5558. most-constrained-first heuristic (aka minimum remaining
  5559. values)~\citep{Russell2003}. That is, in choosing a square, always
  5560. choose one with the fewest possibilities left (the vertex with the
  5561. highest saturation). The idea is that choosing highly constrained
  5562. squares earlier rather than later is better, because later on there may
  5563. not be any possibilities left in the highly saturated squares.
  5564. However, register allocation is easier than sudoku, because the
  5565. register allocator can fall back to assigning variables to stack
  5566. locations when the registers run out. Thus, it makes sense to replace
  5567. backtracking with greedy search: make the best choice at the time and
  5568. keep going. We still wish to minimize the number of colors needed, so
  5569. we use the most-constrained-first heuristic in the greedy search.
  5570. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5571. algorithm for register allocation based on saturation and the
  5572. most-constrained-first heuristic. It is roughly equivalent to the
  5573. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5574. sudoku, the algorithm represents colors with integers. The integers
  5575. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5576. register allocation. In particular, we recommend the following
  5577. correspondence, with $k=11$.
  5578. \begin{lstlisting}
  5579. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5580. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5581. \end{lstlisting}
  5582. The integers $k$ and larger correspond to stack locations. The
  5583. registers that are not used for register allocation, such as
  5584. \code{rax}, are assigned to negative integers. In particular, we
  5585. recommend the following correspondence.
  5586. \begin{lstlisting}
  5587. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5588. \end{lstlisting}
  5589. \begin{figure}[btp]
  5590. \begin{tcolorbox}[colback=white]
  5591. \centering
  5592. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5593. Algorithm: DSATUR
  5594. Input: A graph |$G$|
  5595. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5596. |$W \gets \mathrm{vertices}(G)$|
  5597. while |$W \neq \emptyset$| do
  5598. pick a vertex |$u$| from |$W$| with the highest saturation,
  5599. breaking ties randomly
  5600. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5601. |$\mathrm{color}[u] \gets c$|
  5602. |$W \gets W - \{u\}$|
  5603. \end{lstlisting}
  5604. \end{tcolorbox}
  5605. \caption{The saturation-based greedy graph coloring algorithm.}
  5606. \label{fig:satur-algo}
  5607. \end{figure}
  5608. {\if\edition\racketEd
  5609. With the DSATUR algorithm in hand, let us return to the running
  5610. example and consider how to color the interference graph shown in
  5611. figure~\ref{fig:interfere}.
  5612. %
  5613. We start by assigning each register node to its own color. For
  5614. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5615. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5616. (To reduce clutter in the interference graph, we elide nodes
  5617. that do not have interference edges, such as \code{rcx}.)
  5618. The variables are not yet colored, so they are annotated with a dash. We
  5619. then update the saturation for vertices that are adjacent to a
  5620. register, obtaining the following annotated graph. For example, the
  5621. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5622. \code{rax} and \code{rsp}.
  5623. \[
  5624. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5625. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5626. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5627. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5628. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5629. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5630. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5631. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5632. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5633. \draw (t1) to (rax);
  5634. \draw (t1) to (z);
  5635. \draw (z) to (y);
  5636. \draw (z) to (w);
  5637. \draw (x) to (w);
  5638. \draw (y) to (w);
  5639. \draw (v) to (w);
  5640. \draw (v) to (rsp);
  5641. \draw (w) to (rsp);
  5642. \draw (x) to (rsp);
  5643. \draw (y) to (rsp);
  5644. \path[-.,bend left=15] (z) edge node {} (rsp);
  5645. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5646. \draw (rax) to (rsp);
  5647. \end{tikzpicture}
  5648. \]
  5649. The algorithm says to select a maximally saturated vertex. So, we pick
  5650. $\ttm{t}$ and color it with the first available integer, which is
  5651. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5652. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5653. \[
  5654. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5655. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5656. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5657. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5658. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5659. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5660. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5661. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5662. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5663. \draw (t1) to (rax);
  5664. \draw (t1) to (z);
  5665. \draw (z) to (y);
  5666. \draw (z) to (w);
  5667. \draw (x) to (w);
  5668. \draw (y) to (w);
  5669. \draw (v) to (w);
  5670. \draw (v) to (rsp);
  5671. \draw (w) to (rsp);
  5672. \draw (x) to (rsp);
  5673. \draw (y) to (rsp);
  5674. \path[-.,bend left=15] (z) edge node {} (rsp);
  5675. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5676. \draw (rax) to (rsp);
  5677. \end{tikzpicture}
  5678. \]
  5679. We repeat the process, selecting a maximally saturated vertex,
  5680. choosing \code{z}, and coloring it with the first available number, which
  5681. is $1$. We add $1$ to the saturation for the neighboring vertices
  5682. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5683. \[
  5684. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5685. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5686. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5687. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5688. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5689. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5690. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5691. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5692. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5693. \draw (t1) to (rax);
  5694. \draw (t1) to (z);
  5695. \draw (z) to (y);
  5696. \draw (z) to (w);
  5697. \draw (x) to (w);
  5698. \draw (y) to (w);
  5699. \draw (v) to (w);
  5700. \draw (v) to (rsp);
  5701. \draw (w) to (rsp);
  5702. \draw (x) to (rsp);
  5703. \draw (y) to (rsp);
  5704. \path[-.,bend left=15] (z) edge node {} (rsp);
  5705. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5706. \draw (rax) to (rsp);
  5707. \end{tikzpicture}
  5708. \]
  5709. The most saturated vertices are now \code{w} and \code{y}. We color
  5710. \code{w} with the first available color, which is $0$.
  5711. \[
  5712. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5713. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5714. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5715. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5716. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5717. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5718. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5719. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5720. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5721. \draw (t1) to (rax);
  5722. \draw (t1) to (z);
  5723. \draw (z) to (y);
  5724. \draw (z) to (w);
  5725. \draw (x) to (w);
  5726. \draw (y) to (w);
  5727. \draw (v) to (w);
  5728. \draw (v) to (rsp);
  5729. \draw (w) to (rsp);
  5730. \draw (x) to (rsp);
  5731. \draw (y) to (rsp);
  5732. \path[-.,bend left=15] (z) edge node {} (rsp);
  5733. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5734. \draw (rax) to (rsp);
  5735. \end{tikzpicture}
  5736. \]
  5737. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5738. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5739. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5740. and \code{z}, whose colors are $0$ and $1$ respectively.
  5741. \[
  5742. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5743. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5744. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5745. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5746. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5747. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5748. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5749. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5750. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5751. \draw (t1) to (rax);
  5752. \draw (t1) to (z);
  5753. \draw (z) to (y);
  5754. \draw (z) to (w);
  5755. \draw (x) to (w);
  5756. \draw (y) to (w);
  5757. \draw (v) to (w);
  5758. \draw (v) to (rsp);
  5759. \draw (w) to (rsp);
  5760. \draw (x) to (rsp);
  5761. \draw (y) to (rsp);
  5762. \path[-.,bend left=15] (z) edge node {} (rsp);
  5763. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5764. \draw (rax) to (rsp);
  5765. \end{tikzpicture}
  5766. \]
  5767. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5768. \[
  5769. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5770. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5771. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5772. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5773. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5774. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5775. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5776. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5777. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5778. \draw (t1) to (rax);
  5779. \draw (t1) to (z);
  5780. \draw (z) to (y);
  5781. \draw (z) to (w);
  5782. \draw (x) to (w);
  5783. \draw (y) to (w);
  5784. \draw (v) to (w);
  5785. \draw (v) to (rsp);
  5786. \draw (w) to (rsp);
  5787. \draw (x) to (rsp);
  5788. \draw (y) to (rsp);
  5789. \path[-.,bend left=15] (z) edge node {} (rsp);
  5790. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5791. \draw (rax) to (rsp);
  5792. \end{tikzpicture}
  5793. \]
  5794. In the last step of the algorithm, we color \code{x} with $1$.
  5795. \[
  5796. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5797. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5798. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5799. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5800. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5801. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5802. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5803. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5804. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5805. \draw (t1) to (rax);
  5806. \draw (t1) to (z);
  5807. \draw (z) to (y);
  5808. \draw (z) to (w);
  5809. \draw (x) to (w);
  5810. \draw (y) to (w);
  5811. \draw (v) to (w);
  5812. \draw (v) to (rsp);
  5813. \draw (w) to (rsp);
  5814. \draw (x) to (rsp);
  5815. \draw (y) to (rsp);
  5816. \path[-.,bend left=15] (z) edge node {} (rsp);
  5817. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5818. \draw (rax) to (rsp);
  5819. \end{tikzpicture}
  5820. \]
  5821. So, we obtain the following coloring:
  5822. \[
  5823. \{
  5824. \ttm{rax} \mapsto -1,
  5825. \ttm{rsp} \mapsto -2,
  5826. \ttm{t} \mapsto 0,
  5827. \ttm{z} \mapsto 1,
  5828. \ttm{x} \mapsto 1,
  5829. \ttm{y} \mapsto 2,
  5830. \ttm{w} \mapsto 0,
  5831. \ttm{v} \mapsto 1
  5832. \}
  5833. \]
  5834. \fi}
  5835. %
  5836. {\if\edition\pythonEd\pythonColor
  5837. %
  5838. With the DSATUR algorithm in hand, let us return to the running
  5839. example and consider how to color the interference graph shown in
  5840. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5841. to indicate that it has not yet been assigned a color. Each register
  5842. node (not shown) should be assigned the number that the register
  5843. corresponds to, for example, color \code{rcx} with the number \code{0}
  5844. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5845. each node; all of them start as the empty set.
  5846. %
  5847. \[
  5848. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5849. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5850. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5851. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5852. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5853. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5854. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5855. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5856. \draw (t0) to (t1);
  5857. \draw (t0) to (z);
  5858. \draw (z) to (y);
  5859. \draw (z) to (w);
  5860. \draw (x) to (w);
  5861. \draw (y) to (w);
  5862. \draw (v) to (w);
  5863. \end{tikzpicture}
  5864. \]
  5865. The algorithm says to select a maximally saturated vertex, but they
  5866. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5867. and then we color it with the first available integer, which is $0$. We mark
  5868. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5869. they interfere with $\ttm{tmp\_0}$.
  5870. \[
  5871. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5872. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5873. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5874. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5875. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5876. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5877. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5878. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5879. \draw (t0) to (t1);
  5880. \draw (t0) to (z);
  5881. \draw (z) to (y);
  5882. \draw (z) to (w);
  5883. \draw (x) to (w);
  5884. \draw (y) to (w);
  5885. \draw (v) to (w);
  5886. \end{tikzpicture}
  5887. \]
  5888. We repeat the process. The most saturated vertices are \code{z} and
  5889. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5890. available number, which is $1$. We add $1$ to the saturation for the
  5891. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5892. \[
  5893. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5894. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5895. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5896. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5897. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5898. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5899. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5900. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5901. \draw (t0) to (t1);
  5902. \draw (t0) to (z);
  5903. \draw (z) to (y);
  5904. \draw (z) to (w);
  5905. \draw (x) to (w);
  5906. \draw (y) to (w);
  5907. \draw (v) to (w);
  5908. \end{tikzpicture}
  5909. \]
  5910. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5911. \code{y}. We color \code{w} with the first available color, which
  5912. is $0$.
  5913. \[
  5914. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5915. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5916. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5917. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5918. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5919. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5920. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5921. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5922. \draw (t0) to (t1);
  5923. \draw (t0) to (z);
  5924. \draw (z) to (y);
  5925. \draw (z) to (w);
  5926. \draw (x) to (w);
  5927. \draw (y) to (w);
  5928. \draw (v) to (w);
  5929. \end{tikzpicture}
  5930. \]
  5931. Now \code{y} is the most saturated, so we color it with $2$.
  5932. \[
  5933. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5934. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5935. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5936. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5937. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5938. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5939. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5940. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5941. \draw (t0) to (t1);
  5942. \draw (t0) to (z);
  5943. \draw (z) to (y);
  5944. \draw (z) to (w);
  5945. \draw (x) to (w);
  5946. \draw (y) to (w);
  5947. \draw (v) to (w);
  5948. \end{tikzpicture}
  5949. \]
  5950. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5951. We choose to color \code{v} with $1$.
  5952. \[
  5953. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5954. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5955. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5956. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5957. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5958. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5959. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5960. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5961. \draw (t0) to (t1);
  5962. \draw (t0) to (z);
  5963. \draw (z) to (y);
  5964. \draw (z) to (w);
  5965. \draw (x) to (w);
  5966. \draw (y) to (w);
  5967. \draw (v) to (w);
  5968. \end{tikzpicture}
  5969. \]
  5970. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5971. \[
  5972. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5973. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5974. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5975. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5976. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5977. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5978. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5979. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5980. \draw (t0) to (t1);
  5981. \draw (t0) to (z);
  5982. \draw (z) to (y);
  5983. \draw (z) to (w);
  5984. \draw (x) to (w);
  5985. \draw (y) to (w);
  5986. \draw (v) to (w);
  5987. \end{tikzpicture}
  5988. \]
  5989. So, we obtain the following coloring:
  5990. \[
  5991. \{ \ttm{tmp\_0} \mapsto 0,
  5992. \ttm{tmp\_1} \mapsto 1,
  5993. \ttm{z} \mapsto 1,
  5994. \ttm{x} \mapsto 1,
  5995. \ttm{y} \mapsto 2,
  5996. \ttm{w} \mapsto 0,
  5997. \ttm{v} \mapsto 1 \}
  5998. \]
  5999. \fi}
  6000. We recommend creating an auxiliary function named \code{color\_graph}
  6001. that takes an interference graph and a list of all the variables in
  6002. the program. This function should return a mapping of variables to
  6003. their colors (represented as natural numbers). By creating this helper
  6004. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  6005. when we add support for functions.
  6006. To prioritize the processing of highly saturated nodes inside the
  6007. \code{color\_graph} function, we recommend using the priority queue
  6008. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  6009. addition, you will need to maintain a mapping from variables to their
  6010. handles in the priority queue so that you can notify the priority
  6011. queue when their saturation changes.}
  6012. {\if\edition\racketEd
  6013. \begin{figure}[tp]
  6014. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6015. \small
  6016. \begin{tcolorbox}[title=Priority Queue]
  6017. A \emph{priority queue}\index{subject}{priority queue}
  6018. is a collection of items in which the
  6019. removal of items is governed by priority. In a \emph{min} queue,
  6020. lower priority items are removed first. An implementation is in
  6021. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6022. \begin{description}
  6023. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6024. priority queue that uses the $\itm{cmp}$ predicate to determine
  6025. whether its first argument has lower or equal priority to its
  6026. second argument.
  6027. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6028. items in the queue.
  6029. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6030. the item into the queue and returns a handle for the item in the
  6031. queue.
  6032. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6033. the lowest priority.
  6034. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6035. notifies the queue that the priority has decreased for the item
  6036. associated with the given handle.
  6037. \end{description}
  6038. \end{tcolorbox}
  6039. %\end{wrapfigure}
  6040. \caption{The priority queue data structure.}
  6041. \label{fig:priority-queue}
  6042. \end{figure}
  6043. \fi}
  6044. With the coloring complete, we finalize the assignment of variables to
  6045. registers and stack locations. We map the first $k$ colors to the $k$
  6046. registers and the rest of the colors to stack locations. Suppose for
  6047. the moment that we have just one register to use for register
  6048. allocation, \key{rcx}. Then we have the following assignment.
  6049. \[
  6050. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6051. \]
  6052. Composing this mapping with the coloring, we arrive at the following
  6053. assignment of variables to locations.
  6054. {\if\edition\racketEd
  6055. \begin{gather*}
  6056. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6057. \ttm{w} \mapsto \key{\%rcx}, \,
  6058. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6059. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6060. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6061. \ttm{t} \mapsto \key{\%rcx} \}
  6062. \end{gather*}
  6063. \fi}
  6064. {\if\edition\pythonEd\pythonColor
  6065. \begin{gather*}
  6066. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6067. \ttm{w} \mapsto \key{\%rcx}, \,
  6068. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6069. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6070. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6071. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6072. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6073. \end{gather*}
  6074. \fi}
  6075. Adapt the code from the \code{assign\_homes} pass
  6076. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6077. assigned location. Applying this assignment to our running
  6078. example shown next, on the left, yields the program on the right.
  6079. \begin{center}
  6080. {\if\edition\racketEd
  6081. \begin{minipage}{0.35\textwidth}
  6082. \begin{lstlisting}
  6083. movq $1, v
  6084. movq $42, w
  6085. movq v, x
  6086. addq $7, x
  6087. movq x, y
  6088. movq x, z
  6089. addq w, z
  6090. movq y, t
  6091. negq t
  6092. movq z, %rax
  6093. addq t, %rax
  6094. jmp conclusion
  6095. \end{lstlisting}
  6096. \end{minipage}
  6097. $\Rightarrow\qquad$
  6098. \begin{minipage}{0.45\textwidth}
  6099. \begin{lstlisting}
  6100. movq $1, -8(%rbp)
  6101. movq $42, %rcx
  6102. movq -8(%rbp), -8(%rbp)
  6103. addq $7, -8(%rbp)
  6104. movq -8(%rbp), -16(%rbp)
  6105. movq -8(%rbp), -8(%rbp)
  6106. addq %rcx, -8(%rbp)
  6107. movq -16(%rbp), %rcx
  6108. negq %rcx
  6109. movq -8(%rbp), %rax
  6110. addq %rcx, %rax
  6111. jmp conclusion
  6112. \end{lstlisting}
  6113. \end{minipage}
  6114. \fi}
  6115. {\if\edition\pythonEd\pythonColor
  6116. \begin{minipage}{0.35\textwidth}
  6117. \begin{lstlisting}
  6118. movq $1, v
  6119. movq $42, w
  6120. movq v, x
  6121. addq $7, x
  6122. movq x, y
  6123. movq x, z
  6124. addq w, z
  6125. movq y, tmp_0
  6126. negq tmp_0
  6127. movq z, tmp_1
  6128. addq tmp_0, tmp_1
  6129. movq tmp_1, %rdi
  6130. callq print_int
  6131. \end{lstlisting}
  6132. \end{minipage}
  6133. $\Rightarrow\qquad$
  6134. \begin{minipage}{0.45\textwidth}
  6135. \begin{lstlisting}
  6136. movq $1, -8(%rbp)
  6137. movq $42, %rcx
  6138. movq -8(%rbp), -8(%rbp)
  6139. addq $7, -8(%rbp)
  6140. movq -8(%rbp), -16(%rbp)
  6141. movq -8(%rbp), -8(%rbp)
  6142. addq %rcx, -8(%rbp)
  6143. movq -16(%rbp), %rcx
  6144. negq %rcx
  6145. movq -8(%rbp), -8(%rbp)
  6146. addq %rcx, -8(%rbp)
  6147. movq -8(%rbp), %rdi
  6148. callq print_int
  6149. \end{lstlisting}
  6150. \end{minipage}
  6151. \fi}
  6152. \end{center}
  6153. \begin{exercise}\normalfont\normalsize
  6154. Implement the \code{allocate\_registers} \racket{pass}\python{function}.
  6155. Create five programs that exercise all aspects of the register
  6156. allocation algorithm, including spilling variables to the stack.
  6157. %
  6158. {\if\edition\racketEd
  6159. Replace \code{assign\_homes} in the list of \code{passes} in the
  6160. \code{run-tests.rkt} script with the three new passes:
  6161. \code{uncover\_live}, \code{build\_interference}, and
  6162. \code{allocate\_registers}.
  6163. Temporarily remove the call to \code{compiler-tests}.
  6164. Run the script to test the register allocator.
  6165. \fi}
  6166. %
  6167. {\if\edition\pythonEd\pythonColor
  6168. Update the \code{assign\_homes} pass to make use of
  6169. the functions you have created to perform register allocation:
  6170. \code{uncover\_live}, \code{build\_interference}, and
  6171. \code{allocate\_registers}.
  6172. Run the \code{run-tests.py} script to check whether the
  6173. output programs produce the same result as the input programs.
  6174. Inspect the generated x86 programs to make sure that some variables
  6175. are assigned to registers.
  6176. \fi}
  6177. \end{exercise}
  6178. \section{Patch Instructions}
  6179. \label{sec:patch-instructions}
  6180. The remaining step in the compilation to x86 is to ensure that the
  6181. instructions have at most one argument that is a memory access.
  6182. %
  6183. In the running example, the instruction \code{movq -8(\%rbp),
  6184. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6185. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6186. then move \code{rax} into \code{-16(\%rbp)}.
  6187. %
  6188. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6189. problematic, but they can simply be deleted. In general, we recommend
  6190. deleting all the trivial moves whose source and destination are the
  6191. same location.
  6192. %
  6193. The following is the output of \code{patch\_instructions} on the
  6194. running example.
  6195. \begin{center}
  6196. {\if\edition\racketEd
  6197. \begin{minipage}{0.35\textwidth}
  6198. \begin{lstlisting}
  6199. movq $1, -8(%rbp)
  6200. movq $42, %rcx
  6201. movq -8(%rbp), -8(%rbp)
  6202. addq $7, -8(%rbp)
  6203. movq -8(%rbp), -16(%rbp)
  6204. movq -8(%rbp), -8(%rbp)
  6205. addq %rcx, -8(%rbp)
  6206. movq -16(%rbp), %rcx
  6207. negq %rcx
  6208. movq -8(%rbp), %rax
  6209. addq %rcx, %rax
  6210. jmp conclusion
  6211. \end{lstlisting}
  6212. \end{minipage}
  6213. $\Rightarrow\qquad$
  6214. \begin{minipage}{0.45\textwidth}
  6215. \begin{lstlisting}
  6216. movq $1, -8(%rbp)
  6217. movq $42, %rcx
  6218. addq $7, -8(%rbp)
  6219. movq -8(%rbp), %rax
  6220. movq %rax, -16(%rbp)
  6221. addq %rcx, -8(%rbp)
  6222. movq -16(%rbp), %rcx
  6223. negq %rcx
  6224. movq -8(%rbp), %rax
  6225. addq %rcx, %rax
  6226. jmp conclusion
  6227. \end{lstlisting}
  6228. \end{minipage}
  6229. \fi}
  6230. {\if\edition\pythonEd\pythonColor
  6231. \begin{minipage}{0.35\textwidth}
  6232. \begin{lstlisting}
  6233. movq $1, -8(%rbp)
  6234. movq $42, %rcx
  6235. movq -8(%rbp), -8(%rbp)
  6236. addq $7, -8(%rbp)
  6237. movq -8(%rbp), -16(%rbp)
  6238. movq -8(%rbp), -8(%rbp)
  6239. addq %rcx, -8(%rbp)
  6240. movq -16(%rbp), %rcx
  6241. negq %rcx
  6242. movq -8(%rbp), -8(%rbp)
  6243. addq %rcx, -8(%rbp)
  6244. movq -8(%rbp), %rdi
  6245. callq print_int
  6246. \end{lstlisting}
  6247. \end{minipage}
  6248. $\Rightarrow\qquad$
  6249. \begin{minipage}{0.45\textwidth}
  6250. \begin{lstlisting}
  6251. movq $1, -8(%rbp)
  6252. movq $42, %rcx
  6253. addq $7, -8(%rbp)
  6254. movq -8(%rbp), %rax
  6255. movq %rax, -16(%rbp)
  6256. addq %rcx, -8(%rbp)
  6257. movq -16(%rbp), %rcx
  6258. negq %rcx
  6259. addq %rcx, -8(%rbp)
  6260. movq -8(%rbp), %rdi
  6261. callq print_int
  6262. \end{lstlisting}
  6263. \end{minipage}
  6264. \fi}
  6265. \end{center}
  6266. \begin{exercise}\normalfont\normalsize
  6267. %
  6268. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6269. %
  6270. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6271. %in the \code{run-tests.rkt} script.
  6272. %
  6273. Run the script to test the \code{patch\_instructions} pass.
  6274. \end{exercise}
  6275. \section{Generate Prelude and Conclusion}
  6276. \label{sec:print-x86-reg-alloc}
  6277. \index{subject}{calling conventions}
  6278. \index{subject}{prelude}\index{subject}{conclusion}
  6279. Recall that this pass generates the prelude and conclusion
  6280. instructions to satisfy the x86 calling conventions
  6281. (section~\ref{sec:calling-conventions}). With the addition of the
  6282. register allocator, the callee-saved registers used by the register
  6283. allocator must be saved in the prelude and restored in the conclusion.
  6284. In the \code{allocate\_registers} pass,
  6285. %
  6286. \racket{add an entry to the \itm{info}
  6287. of \code{X86Program} named \code{used\_callee}}
  6288. %
  6289. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6290. %
  6291. that stores the set of callee-saved registers that were assigned to
  6292. variables. The \code{prelude\_and\_conclusion} pass can then access
  6293. this information to decide which callee-saved registers need to be
  6294. saved and restored.
  6295. %
  6296. When calculating the amount to adjust the \code{rsp} in the prelude,
  6297. make sure to take into account the space used for saving the
  6298. callee-saved registers. Also, remember that the frame needs to be a
  6299. multiple of 16 bytes! We recommend using the following equation for
  6300. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6301. of stack locations used by spilled variables\footnote{Sometimes two or
  6302. more spilled variables are assigned to the same stack location, so
  6303. $S$ can be less than the number of spilled variables.} and $C$ be
  6304. the number of callee-saved registers that were
  6305. allocated\index{subject}{allocate} to
  6306. variables. The $\itm{align}$ function rounds a number up to the
  6307. nearest 16 bytes.
  6308. \[
  6309. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6310. \]
  6311. The reason we subtract $8\itm{C}$ in this equation is that the
  6312. prelude uses \code{pushq} to save each of the callee-saved registers,
  6313. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6314. \racket{An overview of all the passes involved in register
  6315. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6316. {\if\edition\racketEd
  6317. \begin{figure}[tbp]
  6318. \begin{tcolorbox}[colback=white]
  6319. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6320. \node (Lvar) at (0,2) {\large \LangVar{}};
  6321. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6322. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6323. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6324. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6325. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6326. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6327. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6328. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6329. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6330. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6331. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6332. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6333. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6334. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6335. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6336. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6337. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6338. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6339. \end{tikzpicture}
  6340. \end{tcolorbox}
  6341. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6342. \label{fig:reg-alloc-passes}
  6343. \end{figure}
  6344. \fi}
  6345. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6346. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6347. use of registers and the stack, we limit the register allocator for
  6348. this example to use just two registers: \code{rcx} (color $0$) and
  6349. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6350. \code{main} function, we push \code{rbx} onto the stack because it is
  6351. a callee-saved register and it was assigned to a variable by the
  6352. register allocator. We subtract \code{8} from the \code{rsp} at the
  6353. end of the prelude to reserve space for the one spilled variable.
  6354. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6355. Moving on to the program proper, we see how the registers were
  6356. allocated.
  6357. %
  6358. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6359. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6360. %
  6361. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6362. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6363. were assigned to \code{rbx}.}
  6364. %
  6365. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6366. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6367. callee-save register \code{rbx} onto the stack. The spilled variables
  6368. must be placed lower on the stack than the saved callee-save
  6369. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6370. \code{-16(\%rbp)}.
  6371. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6372. done in the prelude. We move the stack pointer up by \code{8} bytes
  6373. (the room for spilled variables), then pop the old values of
  6374. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6375. \code{retq} to return control to the operating system.
  6376. \begin{figure}[tbp]
  6377. \begin{minipage}{0.55\textwidth}
  6378. \begin{tcolorbox}[colback=white]
  6379. % var_test_28.rkt
  6380. % (use-minimal-set-of-registers! #t)
  6381. % 0 -> rcx
  6382. % 1 -> rbx
  6383. %
  6384. % t 0 rcx
  6385. % z 1 rbx
  6386. % w 0 rcx
  6387. % y 2 rbp -16
  6388. % v 1 rbx
  6389. % x 1 rbx
  6390. {\if\edition\racketEd
  6391. \begin{lstlisting}
  6392. start:
  6393. movq $1, %rbx
  6394. movq $42, %rcx
  6395. addq $7, %rbx
  6396. movq %rbx, -16(%rbp)
  6397. addq %rcx, %rbx
  6398. movq -16(%rbp), %rcx
  6399. negq %rcx
  6400. movq %rbx, %rax
  6401. addq %rcx, %rax
  6402. jmp conclusion
  6403. .globl main
  6404. main:
  6405. pushq %rbp
  6406. movq %rsp, %rbp
  6407. pushq %rbx
  6408. subq $8, %rsp
  6409. jmp start
  6410. conclusion:
  6411. addq $8, %rsp
  6412. popq %rbx
  6413. popq %rbp
  6414. retq
  6415. \end{lstlisting}
  6416. \fi}
  6417. {\if\edition\pythonEd\pythonColor
  6418. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6419. \begin{lstlisting}
  6420. .globl main
  6421. main:
  6422. pushq %rbp
  6423. movq %rsp, %rbp
  6424. pushq %rbx
  6425. subq $8, %rsp
  6426. movq $1, %rcx
  6427. movq $42, %rbx
  6428. addq $7, %rcx
  6429. movq %rcx, -16(%rbp)
  6430. addq %rbx, -16(%rbp)
  6431. negq %rcx
  6432. movq -16(%rbp), %rbx
  6433. addq %rcx, %rbx
  6434. movq %rbx, %rdi
  6435. callq print_int
  6436. addq $8, %rsp
  6437. popq %rbx
  6438. popq %rbp
  6439. retq
  6440. \end{lstlisting}
  6441. \fi}
  6442. \end{tcolorbox}
  6443. \end{minipage}
  6444. \caption{The x86 output from the running example
  6445. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6446. and \code{rcx}.}
  6447. \label{fig:running-example-x86}
  6448. \end{figure}
  6449. \begin{exercise}\normalfont\normalsize
  6450. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6451. %
  6452. \racket{
  6453. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6454. list of passes and the call to \code{compiler-tests}.}
  6455. %
  6456. Run the script to test the complete compiler for \LangVar{} that
  6457. performs register allocation.
  6458. \end{exercise}
  6459. \section{Challenge: Move Biasing}
  6460. \label{sec:move-biasing}
  6461. \index{subject}{move biasing}
  6462. This section describes an enhancement to the register allocator,
  6463. called move biasing, for students who are looking for an extra
  6464. challenge.
  6465. {\if\edition\racketEd
  6466. To motivate the need for move biasing we return to the running example,
  6467. but this time we use all the general purpose registers. So, we have
  6468. the following mapping of color numbers to registers.
  6469. \[
  6470. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6471. \]
  6472. Using the same assignment of variables to color numbers that was
  6473. produced by the register allocator described in the last section, we
  6474. get the following program.
  6475. \begin{center}
  6476. \begin{minipage}{0.35\textwidth}
  6477. \begin{lstlisting}
  6478. movq $1, v
  6479. movq $42, w
  6480. movq v, x
  6481. addq $7, x
  6482. movq x, y
  6483. movq x, z
  6484. addq w, z
  6485. movq y, t
  6486. negq t
  6487. movq z, %rax
  6488. addq t, %rax
  6489. jmp conclusion
  6490. \end{lstlisting}
  6491. \end{minipage}
  6492. $\Rightarrow\qquad$
  6493. \begin{minipage}{0.45\textwidth}
  6494. \begin{lstlisting}
  6495. movq $1, %rdx
  6496. movq $42, %rcx
  6497. movq %rdx, %rdx
  6498. addq $7, %rdx
  6499. movq %rdx, %rsi
  6500. movq %rdx, %rdx
  6501. addq %rcx, %rdx
  6502. movq %rsi, %rcx
  6503. negq %rcx
  6504. movq %rdx, %rax
  6505. addq %rcx, %rax
  6506. jmp conclusion
  6507. \end{lstlisting}
  6508. \end{minipage}
  6509. \end{center}
  6510. In this output code there are two \key{movq} instructions that
  6511. can be removed because their source and target are the same. However,
  6512. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6513. register, we could instead remove three \key{movq} instructions. We
  6514. can accomplish this by taking into account which variables appear in
  6515. \key{movq} instructions with which other variables.
  6516. \fi}
  6517. {\if\edition\pythonEd\pythonColor
  6518. %
  6519. To motivate the need for move biasing we return to the running example
  6520. and recall that in section~\ref{sec:patch-instructions} we were able to
  6521. remove three trivial move instructions from the running
  6522. example. However, we could remove another trivial move if we were able
  6523. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6524. We say that two variables $p$ and $q$ are \emph{move
  6525. related}\index{subject}{move related} if they participate together in
  6526. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6527. \key{movq} $q$\key{,} $p$.
  6528. %
  6529. Recall that we color variables that are more saturated before coloring
  6530. variables that are less saturated, and in the case of equally
  6531. saturated variables, we choose randomly. Now we break such ties by
  6532. giving preference to variables that have an available color that is
  6533. the same as the color of a move-related variable.
  6534. %
  6535. Furthermore, when the register allocator chooses a color for a
  6536. variable, it should prefer a color that has already been used for a
  6537. move-related variable if one exists (and assuming that they do not
  6538. interfere). This preference should not override the preference for
  6539. registers over stack locations. So, this preference should be used as
  6540. a tie breaker in choosing between two registers or in choosing between
  6541. two stack locations.
  6542. We recommend representing the move relationships in a graph, similarly
  6543. to how we represented interference. The following is the \emph{move
  6544. graph} for our example.
  6545. {\if\edition\racketEd
  6546. \[
  6547. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6548. \node (rax) at (0,0) {$\ttm{rax}$};
  6549. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6550. \node (t) at (0,2) {$\ttm{t}$};
  6551. \node (z) at (3,2) {$\ttm{z}$};
  6552. \node (x) at (6,2) {$\ttm{x}$};
  6553. \node (y) at (3,0) {$\ttm{y}$};
  6554. \node (w) at (6,0) {$\ttm{w}$};
  6555. \node (v) at (9,0) {$\ttm{v}$};
  6556. \draw (v) to (x);
  6557. \draw (x) to (y);
  6558. \draw (x) to (z);
  6559. \draw (y) to (t);
  6560. \end{tikzpicture}
  6561. \]
  6562. \fi}
  6563. %
  6564. {\if\edition\pythonEd\pythonColor
  6565. \[
  6566. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6567. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6568. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6569. \node (z) at (3,2) {$\ttm{z}$};
  6570. \node (x) at (6,2) {$\ttm{x}$};
  6571. \node (y) at (3,0) {$\ttm{y}$};
  6572. \node (w) at (6,0) {$\ttm{w}$};
  6573. \node (v) at (9,0) {$\ttm{v}$};
  6574. \draw (y) to (t0);
  6575. \draw (z) to (x);
  6576. \draw (z) to (t1);
  6577. \draw (x) to (y);
  6578. \draw (x) to (v);
  6579. \end{tikzpicture}
  6580. \]
  6581. \fi}
  6582. {\if\edition\racketEd
  6583. Now we replay the graph coloring, pausing to see the coloring of
  6584. \code{y}. Recall the following configuration. The most saturated vertices
  6585. were \code{w} and \code{y}.
  6586. \[
  6587. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6588. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6589. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6590. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6591. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6592. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6593. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6594. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6595. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6596. \draw (t1) to (rax);
  6597. \draw (t1) to (z);
  6598. \draw (z) to (y);
  6599. \draw (z) to (w);
  6600. \draw (x) to (w);
  6601. \draw (y) to (w);
  6602. \draw (v) to (w);
  6603. \draw (v) to (rsp);
  6604. \draw (w) to (rsp);
  6605. \draw (x) to (rsp);
  6606. \draw (y) to (rsp);
  6607. \path[-.,bend left=15] (z) edge node {} (rsp);
  6608. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6609. \draw (rax) to (rsp);
  6610. \end{tikzpicture}
  6611. \]
  6612. %
  6613. The last time, we chose to color \code{w} with $0$. This time, we see
  6614. that \code{w} is not move-related to any vertex, but \code{y} is
  6615. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6616. the same color as \code{t}.
  6617. \[
  6618. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6619. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6620. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6621. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6622. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6623. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6624. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6625. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6626. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6627. \draw (t1) to (rax);
  6628. \draw (t1) to (z);
  6629. \draw (z) to (y);
  6630. \draw (z) to (w);
  6631. \draw (x) to (w);
  6632. \draw (y) to (w);
  6633. \draw (v) to (w);
  6634. \draw (v) to (rsp);
  6635. \draw (w) to (rsp);
  6636. \draw (x) to (rsp);
  6637. \draw (y) to (rsp);
  6638. \path[-.,bend left=15] (z) edge node {} (rsp);
  6639. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6640. \draw (rax) to (rsp);
  6641. \end{tikzpicture}
  6642. \]
  6643. Now \code{w} is the most saturated, so we color it $2$.
  6644. \[
  6645. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6646. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6647. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6648. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6649. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6650. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6651. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6652. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6653. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6654. \draw (t1) to (rax);
  6655. \draw (t1) to (z);
  6656. \draw (z) to (y);
  6657. \draw (z) to (w);
  6658. \draw (x) to (w);
  6659. \draw (y) to (w);
  6660. \draw (v) to (w);
  6661. \draw (v) to (rsp);
  6662. \draw (w) to (rsp);
  6663. \draw (x) to (rsp);
  6664. \draw (y) to (rsp);
  6665. \path[-.,bend left=15] (z) edge node {} (rsp);
  6666. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6667. \draw (rax) to (rsp);
  6668. \end{tikzpicture}
  6669. \]
  6670. At this point, vertices \code{x} and \code{v} are most saturated, but
  6671. \code{x} is move related to \code{y} and \code{z}, so we color
  6672. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6673. \[
  6674. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6675. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6676. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6677. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6678. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6679. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6680. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6681. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6682. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6683. \draw (t1) to (rax);
  6684. \draw (t) to (z);
  6685. \draw (z) to (y);
  6686. \draw (z) to (w);
  6687. \draw (x) to (w);
  6688. \draw (y) to (w);
  6689. \draw (v) to (w);
  6690. \draw (v) to (rsp);
  6691. \draw (w) to (rsp);
  6692. \draw (x) to (rsp);
  6693. \draw (y) to (rsp);
  6694. \path[-.,bend left=15] (z) edge node {} (rsp);
  6695. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6696. \draw (rax) to (rsp);
  6697. \end{tikzpicture}
  6698. \]
  6699. \fi}
  6700. %
  6701. {\if\edition\pythonEd\pythonColor
  6702. Now we replay the graph coloring, pausing before the coloring of
  6703. \code{w}. Recall the following configuration. The most saturated vertices
  6704. were \code{tmp\_1}, \code{w}, and \code{y}.
  6705. \[
  6706. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6707. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6708. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6709. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6710. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6711. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6712. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6713. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6714. \draw (t0) to (t1);
  6715. \draw (t0) to (z);
  6716. \draw (z) to (y);
  6717. \draw (z) to (w);
  6718. \draw (x) to (w);
  6719. \draw (y) to (w);
  6720. \draw (v) to (w);
  6721. \end{tikzpicture}
  6722. \]
  6723. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6724. or \code{y}. Note, however, that \code{w} is not move related to any
  6725. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6726. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6727. \code{y} and color it $0$, we can delete another move instruction.
  6728. \[
  6729. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6730. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6731. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6732. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6733. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6734. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6735. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6736. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6737. \draw (t0) to (t1);
  6738. \draw (t0) to (z);
  6739. \draw (z) to (y);
  6740. \draw (z) to (w);
  6741. \draw (x) to (w);
  6742. \draw (y) to (w);
  6743. \draw (v) to (w);
  6744. \end{tikzpicture}
  6745. \]
  6746. Now \code{w} is the most saturated, so we color it $2$.
  6747. \[
  6748. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6749. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6750. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6751. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6752. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6753. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6754. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6755. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6756. \draw (t0) to (t1);
  6757. \draw (t0) to (z);
  6758. \draw (z) to (y);
  6759. \draw (z) to (w);
  6760. \draw (x) to (w);
  6761. \draw (y) to (w);
  6762. \draw (v) to (w);
  6763. \end{tikzpicture}
  6764. \]
  6765. To finish the coloring, \code{x} and \code{v} get $0$ and
  6766. \code{tmp\_1} gets $1$.
  6767. \[
  6768. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6769. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6770. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6771. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6772. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6773. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6774. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6775. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6776. \draw (t0) to (t1);
  6777. \draw (t0) to (z);
  6778. \draw (z) to (y);
  6779. \draw (z) to (w);
  6780. \draw (x) to (w);
  6781. \draw (y) to (w);
  6782. \draw (v) to (w);
  6783. \end{tikzpicture}
  6784. \]
  6785. \fi}
  6786. So, we have the following assignment of variables to registers.
  6787. {\if\edition\racketEd
  6788. \begin{gather*}
  6789. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6790. \ttm{w} \mapsto \key{\%rsi}, \,
  6791. \ttm{x} \mapsto \key{\%rcx}, \,
  6792. \ttm{y} \mapsto \key{\%rcx}, \,
  6793. \ttm{z} \mapsto \key{\%rdx}, \,
  6794. \ttm{t} \mapsto \key{\%rcx} \}
  6795. \end{gather*}
  6796. \fi}
  6797. {\if\edition\pythonEd\pythonColor
  6798. \begin{gather*}
  6799. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6800. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6801. \ttm{x} \mapsto \key{\%rcx}, \,
  6802. \ttm{y} \mapsto \key{\%rcx}, \\
  6803. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6804. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6805. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6806. \end{gather*}
  6807. \fi}
  6808. %
  6809. We apply this register assignment to the running example shown next,
  6810. on the left, to obtain the code in the middle. The
  6811. \code{patch\_instructions} then deletes the trivial moves to obtain
  6812. the code on the right.
  6813. {\if\edition\racketEd
  6814. \begin{center}
  6815. \begin{minipage}{0.2\textwidth}
  6816. \begin{lstlisting}
  6817. movq $1, v
  6818. movq $42, w
  6819. movq v, x
  6820. addq $7, x
  6821. movq x, y
  6822. movq x, z
  6823. addq w, z
  6824. movq y, t
  6825. negq t
  6826. movq z, %rax
  6827. addq t, %rax
  6828. jmp conclusion
  6829. \end{lstlisting}
  6830. \end{minipage}
  6831. $\Rightarrow\qquad$
  6832. \begin{minipage}{0.25\textwidth}
  6833. \begin{lstlisting}
  6834. movq $1, %rcx
  6835. movq $42, %rsi
  6836. movq %rcx, %rcx
  6837. addq $7, %rcx
  6838. movq %rcx, %rcx
  6839. movq %rcx, %rdx
  6840. addq %rsi, %rdx
  6841. movq %rcx, %rcx
  6842. negq %rcx
  6843. movq %rdx, %rax
  6844. addq %rcx, %rax
  6845. jmp conclusion
  6846. \end{lstlisting}
  6847. \end{minipage}
  6848. $\Rightarrow\qquad$
  6849. \begin{minipage}{0.23\textwidth}
  6850. \begin{lstlisting}
  6851. movq $1, %rcx
  6852. movq $42, %rsi
  6853. addq $7, %rcx
  6854. movq %rcx, %rdx
  6855. addq %rsi, %rdx
  6856. negq %rcx
  6857. movq %rdx, %rax
  6858. addq %rcx, %rax
  6859. jmp conclusion
  6860. \end{lstlisting}
  6861. \end{minipage}
  6862. \end{center}
  6863. \fi}
  6864. {\if\edition\pythonEd\pythonColor
  6865. \begin{center}
  6866. \begin{minipage}{0.20\textwidth}
  6867. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6868. movq $1, v
  6869. movq $42, w
  6870. movq v, x
  6871. addq $7, x
  6872. movq x, y
  6873. movq x, z
  6874. addq w, z
  6875. movq y, tmp_0
  6876. negq tmp_0
  6877. movq z, tmp_1
  6878. addq tmp_0, tmp_1
  6879. movq tmp_1, %rdi
  6880. callq _print_int
  6881. \end{lstlisting}
  6882. \end{minipage}
  6883. ${\Rightarrow\qquad}$
  6884. \begin{minipage}{0.35\textwidth}
  6885. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6886. movq $1, %rcx
  6887. movq $42, -16(%rbp)
  6888. movq %rcx, %rcx
  6889. addq $7, %rcx
  6890. movq %rcx, %rcx
  6891. movq %rcx, -8(%rbp)
  6892. addq -16(%rbp), -8(%rbp)
  6893. movq %rcx, %rcx
  6894. negq %rcx
  6895. movq -8(%rbp), -8(%rbp)
  6896. addq %rcx, -8(%rbp)
  6897. movq -8(%rbp), %rdi
  6898. callq _print_int
  6899. \end{lstlisting}
  6900. \end{minipage}
  6901. ${\Rightarrow\qquad}$
  6902. \begin{minipage}{0.20\textwidth}
  6903. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6904. movq $1, %rcx
  6905. movq $42, -16(%rbp)
  6906. addq $7, %rcx
  6907. movq %rcx, -8(%rbp)
  6908. movq -16(%rbp), %rax
  6909. addq %rax, -8(%rbp)
  6910. negq %rcx
  6911. addq %rcx, -8(%rbp)
  6912. movq -8(%rbp), %rdi
  6913. callq print_int
  6914. \end{lstlisting}
  6915. \end{minipage}
  6916. \end{center}
  6917. \fi}
  6918. \begin{exercise}\normalfont\normalsize
  6919. Change your implementation of \code{allocate\_registers} to take move
  6920. biasing into account. Create two new tests that include at least one
  6921. opportunity for move biasing, and visually inspect the output x86
  6922. programs to make sure that your move biasing is working properly. Make
  6923. sure that your compiler still passes all the tests.
  6924. \end{exercise}
  6925. %To do: another neat challenge would be to do
  6926. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6927. %% \subsection{Output of the Running Example}
  6928. %% \label{sec:reg-alloc-output}
  6929. % challenge: prioritize variables based on execution frequencies
  6930. % and the number of uses of a variable
  6931. % challenge: enhance the coloring algorithm using Chaitin's
  6932. % approach of prioritizing high-degree variables
  6933. % by removing low-degree variables (coloring them later)
  6934. % from the interference graph
  6935. \section{Further Reading}
  6936. \label{sec:register-allocation-further-reading}
  6937. Early register allocation algorithms were developed for Fortran
  6938. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6939. of graph coloring began in the late 1970s and early 1980s with the
  6940. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6941. algorithm is based on the following observation of
  6942. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6943. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6944. $v$ removed is also $k$ colorable. To see why, suppose that the
  6945. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6946. different colors, but because there are fewer than $k$ neighbors, there
  6947. will be one or more colors left over to use for coloring $v$ in $G$.
  6948. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6949. less than $k$ from the graph and recursively colors the rest of the
  6950. graph. Upon returning from the recursion, it colors $v$ with one of
  6951. the available colors and returns. \citet{Chaitin:1982vn} augments
  6952. this algorithm to handle spilling as follows. If there are no vertices
  6953. of degree lower than $k$ then pick a vertex at random, spill it,
  6954. remove it from the graph, and proceed recursively to color the rest of
  6955. the graph.
  6956. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6957. move-related and that don't interfere with each other, in a process
  6958. called \emph{coalescing}. Although coalescing decreases the number of
  6959. moves, it can make the graph more difficult to
  6960. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6961. which two variables are merged only if they have fewer than $k$
  6962. neighbors of high degree. \citet{George:1996aa} observes that
  6963. conservative coalescing is sometimes too conservative and made it more
  6964. aggressive by iterating the coalescing with the removal of low-degree
  6965. vertices.
  6966. %
  6967. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6968. also proposed \emph{biased coloring}, in which a variable is assigned to
  6969. the same color as another move-related variable if possible, as
  6970. discussed in section~\ref{sec:move-biasing}.
  6971. %
  6972. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6973. performs coalescing, graph coloring, and spill code insertion until
  6974. all variables have been assigned a location.
  6975. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6976. spilled variables that don't have to be: a high-degree variable can be
  6977. colorable if many of its neighbors are assigned the same color.
  6978. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6979. high-degree vertex is not immediately spilled. Instead the decision is
  6980. deferred until after the recursive call, when it is apparent whether
  6981. there is an available color or not. We observe that this algorithm is
  6982. equivalent to the smallest-last ordering
  6983. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6984. be registers and the rest to be stack locations.
  6985. %% biased coloring
  6986. Earlier editions of the compiler course at Indiana University
  6987. \citep{Dybvig:2010aa} were based on the algorithm of
  6988. \citet{Briggs:1994kx}.
  6989. The smallest-last ordering algorithm is one of many \emph{greedy}
  6990. coloring algorithms. A greedy coloring algorithm visits all the
  6991. vertices in a particular order and assigns each one the first
  6992. available color. An \emph{offline} greedy algorithm chooses the
  6993. ordering up front, prior to assigning colors. The algorithm of
  6994. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6995. ordering does not depend on the colors assigned. Other orderings are
  6996. possible. For example, \citet{Chow:1984ys} ordered variables according
  6997. to an estimate of runtime cost.
  6998. An \emph{online} greedy coloring algorithm uses information about the
  6999. current assignment of colors to influence the order in which the
  7000. remaining vertices are colored. The saturation-based algorithm
  7001. described in this chapter is one such algorithm. We choose to use
  7002. saturation-based coloring because it is fun to introduce graph
  7003. coloring via sudoku!
  7004. A register allocator may choose to map each variable to just one
  7005. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  7006. variable to one or more locations. The latter can be achieved by
  7007. \emph{live range splitting}, where a variable is replaced by several
  7008. variables that each handle part of its live
  7009. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  7010. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  7011. %% replacement algorithm, bottom-up local
  7012. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  7013. %% Cooper: top-down (priority bassed), bottom-up
  7014. %% top-down
  7015. %% order variables by priority (estimated cost)
  7016. %% caveat: split variables into two groups:
  7017. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  7018. %% color the constrained ones first
  7019. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7020. %% cite J. Cocke for an algorithm that colors variables
  7021. %% in a high-degree first ordering
  7022. %Register Allocation via Usage Counts, Freiburghouse CACM
  7023. \citet{Palsberg:2007si} observes that many of the interference graphs
  7024. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7025. that is, every cycle with four or more edges has an edge that is not
  7026. part of the cycle but that connects two vertices on the cycle. Such
  7027. graphs can be optimally colored by the greedy algorithm with a vertex
  7028. ordering determined by maximum cardinality search.
  7029. In situations in which compile time is of utmost importance, such as
  7030. in just-in-time compilers, graph coloring algorithms can be too
  7031. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7032. be more appropriate.
  7033. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7034. {\if\edition\racketEd
  7035. \addtocontents{toc}{\newpage}
  7036. \fi}
  7037. \chapter{Booleans and Conditionals}
  7038. \label{ch:Lif}
  7039. \setcounter{footnote}{0}
  7040. The \LangVar{} language has only a single kind of value, the
  7041. integers. In this chapter we add a second kind of value, the Booleans,
  7042. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7043. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7044. are written
  7045. \TRUE{}\index{subject}{True@\TRUE{}} and
  7046. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7047. language includes several operations that involve Booleans
  7048. (\key{and}\index{subject}{and@\ANDNAME{}},
  7049. \key{or}\index{subject}{or@\ORNAME{}},
  7050. \key{not}\index{subject}{not@\NOTNAME{}},
  7051. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7052. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7053. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7054. conditional expression\index{subject}{conditional expression}%
  7055. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7056. With the addition of \key{if}, programs can have
  7057. nontrivial control flow\index{subject}{control flow}, which
  7058. %
  7059. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7060. %
  7061. \python{impacts liveness analysis and motivates a new pass named
  7062. \code{explicate\_control}.}
  7063. %
  7064. Also, because we now have two kinds of values, we need to handle
  7065. programs that apply an operation to the wrong kind of value, such as
  7066. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7067. There are two language design options for such situations. One option
  7068. is to signal an error and the other is to provide a wider
  7069. interpretation of the operation. \racket{The Racket
  7070. language}\python{Python} uses a mixture of these two options,
  7071. depending on the operation and the kind of value. For example, the
  7072. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7073. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7074. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7075. %
  7076. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7077. in Racket because \code{car} expects a pair.}
  7078. %
  7079. \python{On the other hand, \code{1[0]} results in a runtime error
  7080. in Python because an ``\code{int} object is not subscriptable.''}
  7081. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7082. design choices as \racket{Racket}\python{Python}, except that much of the
  7083. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7084. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7085. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7086. \python{MyPy} reports a compile-time error
  7087. %
  7088. \racket{because Racket expects the type of the argument to be of the form
  7089. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7090. %
  7091. \python{stating that a ``value of type \code{int} is not indexable.''}
  7092. The \LangIf{} language performs type checking during compilation just as
  7093. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7094. the alternative choice, that is, a dynamically typed language like
  7095. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7096. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7097. restrictive, for example, rejecting \racket{\code{(not
  7098. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7099. fairly simple because the focus of this book is on compilation and not
  7100. type systems, about which there are already several excellent
  7101. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7102. This chapter is organized as follows. We begin by defining the syntax
  7103. and interpreter for the \LangIf{} language
  7104. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7105. checking (aka semantic analysis\index{subject}{semantic analysis})
  7106. and define a type checker for \LangIf{}
  7107. (section~\ref{sec:type-check-Lif}).
  7108. %
  7109. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7110. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7111. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7112. %
  7113. The remaining sections of this chapter discuss how Booleans and
  7114. conditional control flow require changes to the existing compiler
  7115. passes and the addition of new ones. We introduce the \code{shrink}
  7116. pass to translate some operators into others, thereby reducing the
  7117. number of operators that need to be handled in later passes.
  7118. %
  7119. The main event of this chapter is the \code{explicate\_control} pass
  7120. that is responsible for translating \code{if}s into conditional
  7121. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7122. %
  7123. Regarding register allocation, there is the interesting question of
  7124. how to handle conditional \code{goto}s during liveness analysis.
  7125. \section{The \LangIf{} Language}
  7126. \label{sec:lang-if}
  7127. Definitions of the concrete syntax and abstract syntax of the
  7128. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7129. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7130. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7131. literals\index{subject}{literals}
  7132. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7133. \python{, and the \code{if} statement}. We expand the set of
  7134. operators to include
  7135. \begin{enumerate}
  7136. \item the logical operators \key{and}, \key{or}, and \key{not},
  7137. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7138. for comparing integers or Booleans for equality, and
  7139. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7140. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7141. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7142. comparing integers.
  7143. \end{enumerate}
  7144. \racket{We reorganize the abstract syntax for the primitive
  7145. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7146. rule for all of them. This means that the grammar no longer checks
  7147. whether the arity of an operator matches the number of
  7148. arguments. That responsibility is moved to the type checker for
  7149. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7150. \newcommand{\LifGrammarRacket}{
  7151. \begin{array}{lcl}
  7152. \Type &::=& \key{Boolean} \\
  7153. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7154. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7155. \Exp &::=& \itm{bool}
  7156. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7157. \MID (\key{not}\;\Exp) \\
  7158. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7159. \end{array}
  7160. }
  7161. \newcommand{\LifASTRacket}{
  7162. \begin{array}{lcl}
  7163. \Type &::=& \key{Boolean} \\
  7164. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7165. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7166. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7167. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7168. \end{array}
  7169. }
  7170. \newcommand{\LintOpAST}{
  7171. \begin{array}{rcl}
  7172. \Type &::=& \key{Integer} \\
  7173. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7174. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7175. \end{array}
  7176. }
  7177. \newcommand{\LifGrammarPython}{
  7178. \begin{array}{rcl}
  7179. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7180. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7181. \MID \key{not}~\Exp \\
  7182. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7183. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7184. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7185. \end{array}
  7186. }
  7187. \newcommand{\LifASTPython}{
  7188. \begin{array}{lcl}
  7189. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7190. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7191. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7192. \Exp &::=& \BOOL{\itm{bool}}
  7193. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7194. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7195. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7196. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7197. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7198. \end{array}
  7199. }
  7200. \begin{figure}[tp]
  7201. \centering
  7202. \begin{tcolorbox}[colback=white]
  7203. {\if\edition\racketEd
  7204. \[
  7205. \begin{array}{l}
  7206. \gray{\LintGrammarRacket{}} \\ \hline
  7207. \gray{\LvarGrammarRacket{}} \\ \hline
  7208. \LifGrammarRacket{} \\
  7209. \begin{array}{lcl}
  7210. \LangIfM{} &::=& \Exp
  7211. \end{array}
  7212. \end{array}
  7213. \]
  7214. \fi}
  7215. {\if\edition\pythonEd\pythonColor
  7216. \[
  7217. \begin{array}{l}
  7218. \gray{\LintGrammarPython} \\ \hline
  7219. \gray{\LvarGrammarPython} \\ \hline
  7220. \LifGrammarPython \\
  7221. \begin{array}{rcl}
  7222. \LangIfM{} &::=& \Stmt^{*}
  7223. \end{array}
  7224. \end{array}
  7225. \]
  7226. \fi}
  7227. \end{tcolorbox}
  7228. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7229. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7230. \label{fig:Lif-concrete-syntax}
  7231. \index{subject}{Lif@\LangIf{} concrete syntax}
  7232. \end{figure}
  7233. \begin{figure}[tp]
  7234. %\begin{minipage}{0.66\textwidth}
  7235. \begin{tcolorbox}[colback=white]
  7236. \centering
  7237. {\if\edition\racketEd
  7238. \[
  7239. \begin{array}{l}
  7240. \gray{\LintOpAST} \\ \hline
  7241. \gray{\LvarASTRacket{}} \\ \hline
  7242. \LifASTRacket{} \\
  7243. \begin{array}{lcl}
  7244. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7245. \end{array}
  7246. \end{array}
  7247. \]
  7248. \fi}
  7249. {\if\edition\pythonEd\pythonColor
  7250. \[
  7251. \begin{array}{l}
  7252. \gray{\LintASTPython} \\ \hline
  7253. \gray{\LvarASTPython} \\ \hline
  7254. \LifASTPython \\
  7255. \begin{array}{lcl}
  7256. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7257. \end{array}
  7258. \end{array}
  7259. \]
  7260. \fi}
  7261. \end{tcolorbox}
  7262. %\end{minipage}
  7263. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7264. \python{
  7265. \index{subject}{BoolOp@\texttt{BoolOp}}
  7266. \index{subject}{Compare@\texttt{Compare}}
  7267. \index{subject}{Lt@\texttt{Lt}}
  7268. \index{subject}{LtE@\texttt{LtE}}
  7269. \index{subject}{Gt@\texttt{Gt}}
  7270. \index{subject}{GtE@\texttt{GtE}}
  7271. }
  7272. \caption{The abstract syntax of \LangIf{}.}
  7273. \label{fig:Lif-syntax}
  7274. \index{subject}{Lif@\LangIf{} abstract syntax}
  7275. \end{figure}
  7276. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7277. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7278. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7279. evaluate to the corresponding Boolean values, behavior that is
  7280. inherited from the interpreter for \LangInt{}
  7281. (figure~\ref{fig:interp-Lint-class}).
  7282. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7283. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7284. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7285. \code{and}, \code{or}, and \code{not} behave according to propositional
  7286. logic. In addition, the \code{and} and \code{or} operations perform
  7287. \emph{short-circuit evaluation}.
  7288. %
  7289. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7290. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7291. %
  7292. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7293. evaluated if $e_1$ evaluates to \TRUE{}.
  7294. \racket{With the increase in the number of primitive operations, the
  7295. interpreter would become repetitive without some care. We refactor
  7296. the case for \code{Prim}, moving the code that differs with each
  7297. operation into the \code{interp\_op} method shown in
  7298. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7299. \code{or} operations separately because of their short-circuiting
  7300. behavior.}
  7301. \begin{figure}[tbp]
  7302. \begin{tcolorbox}[colback=white]
  7303. {\if\edition\racketEd
  7304. \begin{lstlisting}
  7305. (define interp-Lif-class
  7306. (class interp-Lvar-class
  7307. (super-new)
  7308. (define/public (interp_op op) ...)
  7309. (define/override ((interp_exp env) e)
  7310. (define recur (interp_exp env))
  7311. (match e
  7312. [(Bool b) b]
  7313. [(If cnd thn els)
  7314. (match (recur cnd)
  7315. [#t (recur thn)]
  7316. [#f (recur els)])]
  7317. [(Prim 'and (list e1 e2))
  7318. (match (recur e1)
  7319. [#t (match (recur e2) [#t #t] [#f #f])]
  7320. [#f #f])]
  7321. [(Prim 'or (list e1 e2))
  7322. (define v1 (recur e1))
  7323. (match v1
  7324. [#t #t]
  7325. [#f (match (recur e2) [#t #t] [#f #f])])]
  7326. [(Prim op args)
  7327. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7328. [else ((super interp_exp env) e)]))
  7329. ))
  7330. (define (interp_Lif p)
  7331. (send (new interp-Lif-class) interp_program p))
  7332. \end{lstlisting}
  7333. \fi}
  7334. {\if\edition\pythonEd\pythonColor
  7335. \begin{lstlisting}
  7336. class InterpLif(InterpLvar):
  7337. def interp_exp(self, e, env):
  7338. match e:
  7339. case IfExp(test, body, orelse):
  7340. if self.interp_exp(test, env):
  7341. return self.interp_exp(body, env)
  7342. else:
  7343. return self.interp_exp(orelse, env)
  7344. case UnaryOp(Not(), v):
  7345. return not self.interp_exp(v, env)
  7346. case BoolOp(And(), values):
  7347. if self.interp_exp(values[0], env):
  7348. return self.interp_exp(values[1], env)
  7349. else:
  7350. return False
  7351. case BoolOp(Or(), values):
  7352. if self.interp_exp(values[0], env):
  7353. return True
  7354. else:
  7355. return self.interp_exp(values[1], env)
  7356. case Compare(left, [cmp], [right]):
  7357. l = self.interp_exp(left, env)
  7358. r = self.interp_exp(right, env)
  7359. return self.interp_cmp(cmp)(l, r)
  7360. case _:
  7361. return super().interp_exp(e, env)
  7362. def interp_stmt(self, s, env, cont):
  7363. match s:
  7364. case If(test, body, orelse):
  7365. match self.interp_exp(test, env):
  7366. case True:
  7367. return self.interp_stmts(body + cont, env)
  7368. case False:
  7369. return self.interp_stmts(orelse + cont, env)
  7370. case _:
  7371. return super().interp_stmt(s, env, cont)
  7372. ...
  7373. \end{lstlisting}
  7374. \fi}
  7375. \end{tcolorbox}
  7376. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7377. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7378. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7379. \label{fig:interp-Lif}
  7380. \end{figure}
  7381. {\if\edition\racketEd
  7382. \begin{figure}[tbp]
  7383. \begin{tcolorbox}[colback=white]
  7384. \begin{lstlisting}
  7385. (define/public (interp_op op)
  7386. (match op
  7387. ['+ fx+]
  7388. ['- fx-]
  7389. ['read read-fixnum]
  7390. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7391. ['eq? (lambda (v1 v2)
  7392. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7393. (and (boolean? v1) (boolean? v2))
  7394. (and (vector? v1) (vector? v2)))
  7395. (eq? v1 v2)]))]
  7396. ['< (lambda (v1 v2)
  7397. (cond [(and (fixnum? v1) (fixnum? v2))
  7398. (< v1 v2)]))]
  7399. ['<= (lambda (v1 v2)
  7400. (cond [(and (fixnum? v1) (fixnum? v2))
  7401. (<= v1 v2)]))]
  7402. ['> (lambda (v1 v2)
  7403. (cond [(and (fixnum? v1) (fixnum? v2))
  7404. (> v1 v2)]))]
  7405. ['>= (lambda (v1 v2)
  7406. (cond [(and (fixnum? v1) (fixnum? v2))
  7407. (>= v1 v2)]))]
  7408. [else (error 'interp_op "unknown operator")]))
  7409. \end{lstlisting}
  7410. \end{tcolorbox}
  7411. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7412. \label{fig:interp-op-Lif}
  7413. \end{figure}
  7414. \fi}
  7415. {\if\edition\pythonEd\pythonColor
  7416. \begin{figure}
  7417. \begin{tcolorbox}[colback=white]
  7418. \begin{lstlisting}
  7419. class InterpLif(InterpLvar):
  7420. ...
  7421. def interp_cmp(self, cmp):
  7422. match cmp:
  7423. case Lt():
  7424. return lambda x, y: x < y
  7425. case LtE():
  7426. return lambda x, y: x <= y
  7427. case Gt():
  7428. return lambda x, y: x > y
  7429. case GtE():
  7430. return lambda x, y: x >= y
  7431. case Eq():
  7432. return lambda x, y: x == y
  7433. case NotEq():
  7434. return lambda x, y: x != y
  7435. \end{lstlisting}
  7436. \end{tcolorbox}
  7437. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7438. \label{fig:interp-cmp-Lif}
  7439. \end{figure}
  7440. \fi}
  7441. \section{Type Checking \LangIf{} Programs}
  7442. \label{sec:type-check-Lif}
  7443. It is helpful to think about type checking\index{subject}{type
  7444. checking} in two complementary ways. A type checker predicts the
  7445. type of value that will be produced by each expression in the program.
  7446. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7447. type checker should predict that {\if\edition\racketEd
  7448. \begin{lstlisting}
  7449. (+ 10 (- (+ 12 20)))
  7450. \end{lstlisting}
  7451. \fi}
  7452. {\if\edition\pythonEd\pythonColor
  7453. \begin{lstlisting}
  7454. 10 + -(12 + 20)
  7455. \end{lstlisting}
  7456. \fi}
  7457. \noindent produces a value of type \INTTY{}, whereas
  7458. {\if\edition\racketEd
  7459. \begin{lstlisting}
  7460. (and (not #f) #t)
  7461. \end{lstlisting}
  7462. \fi}
  7463. {\if\edition\pythonEd\pythonColor
  7464. \begin{lstlisting}
  7465. (not False) and True
  7466. \end{lstlisting}
  7467. \fi}
  7468. \noindent produces a value of type \BOOLTY{}.
  7469. A second way to think about type checking is that it enforces a set of
  7470. rules about which operators can be applied to which kinds of
  7471. values. For example, our type checker for \LangIf{} signals an error
  7472. for the following expression:
  7473. %
  7474. {\if\edition\racketEd
  7475. \begin{lstlisting}
  7476. (not (+ 10 (- (+ 12 20))))
  7477. \end{lstlisting}
  7478. \fi}
  7479. {\if\edition\pythonEd\pythonColor
  7480. \begin{lstlisting}
  7481. not (10 + -(12 + 20))
  7482. \end{lstlisting}
  7483. \fi}
  7484. \noindent The subexpression
  7485. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7486. \python{\code{(10 + -(12 + 20))}}
  7487. has type \INTTY{}, but the type checker enforces the rule that the
  7488. argument of \code{not} must be an expression of type \BOOLTY{}.
  7489. We implement type checking using classes and methods because they
  7490. provide the open recursion needed to reuse code as we extend the type
  7491. checker in subsequent chapters, analogous to the use of classes and methods
  7492. for the interpreters (section~\ref{sec:extensible-interp}).
  7493. We separate the type checker for the \LangVar{} subset into its own
  7494. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7495. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7496. from the type checker for \LangVar{}. These type checkers are in the
  7497. files
  7498. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7499. and
  7500. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7501. of the support code.
  7502. %
  7503. Each type checker is a structurally recursive function over the AST.
  7504. Given an input expression \code{e}, the type checker either signals an
  7505. error or returns \racket{an expression and its type.}\python{its type.}
  7506. %
  7507. \racket{It returns an expression because there are situations in which
  7508. we want to change or update the expression.}
  7509. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7510. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7511. constant is \INTTY{}. To handle variables, the type checker uses the
  7512. environment \code{env} to map variables to types.
  7513. %
  7514. \racket{Consider the case for \key{let}. We type check the
  7515. initializing expression to obtain its type \key{T} and then
  7516. associate type \code{T} with the variable \code{x} in the
  7517. environment used to type check the body of the \key{let}. Thus,
  7518. when the type checker encounters a use of variable \code{x}, it can
  7519. find its type in the environment.}
  7520. %
  7521. \python{Consider the case for assignment. We type check the
  7522. initializing expression to obtain its type \key{t}. If the variable
  7523. \code{id} is already in the environment because there was a
  7524. prior assignment, we check that this initializer has the same type
  7525. as the prior one. If this is the first assignment to the variable,
  7526. we associate type \code{t} with the variable \code{id} in the
  7527. environment. Thus, when the type checker encounters a use of
  7528. variable \code{x}, it can find its type in the environment.}
  7529. %
  7530. \racket{Regarding primitive operators, we recursively analyze the
  7531. arguments and then invoke \code{type\_check\_op} to check whether
  7532. the argument types are allowed.}
  7533. %
  7534. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7535. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7536. \racket{Several auxiliary methods are used in the type checker. The
  7537. method \code{operator-types} defines a dictionary that maps the
  7538. operator names to their parameter and return types. The
  7539. \code{type-equal?} method determines whether two types are equal,
  7540. which for now simply dispatches to \code{equal?} (deep
  7541. equality). The \code{check-type-equal?} method triggers an error if
  7542. the two types are not equal. The \code{type-check-op} method looks
  7543. up the operator in the \code{operator-types} dictionary and then
  7544. checks whether the argument types are equal to the parameter types.
  7545. The result is the return type of the operator.}
  7546. %
  7547. \python{The auxiliary method \code{check\_type\_equal} triggers
  7548. an error if the two types are not equal.}
  7549. \begin{figure}[tbp]
  7550. \begin{tcolorbox}[colback=white]
  7551. {\if\edition\racketEd
  7552. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7553. (define type-check-Lvar-class
  7554. (class object%
  7555. (super-new)
  7556. (define/public (operator-types)
  7557. '((+ . ((Integer Integer) . Integer))
  7558. (- . ((Integer Integer) . Integer))
  7559. (read . (() . Integer))))
  7560. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7561. (define/public (check-type-equal? t1 t2 e)
  7562. (unless (type-equal? t1 t2)
  7563. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7564. (define/public (type-check-op op arg-types e)
  7565. (match (dict-ref (operator-types) op)
  7566. [`(,param-types . ,return-type)
  7567. (for ([at arg-types] [pt param-types])
  7568. (check-type-equal? at pt e))
  7569. return-type]
  7570. [else (error 'type-check-op "unrecognized ~a" op)]))
  7571. (define/public (type-check-exp env)
  7572. (lambda (e)
  7573. (match e
  7574. [(Int n) (values (Int n) 'Integer)]
  7575. [(Var x) (values (Var x) (dict-ref env x))]
  7576. [(Let x e body)
  7577. (define-values (e^ Te) ((type-check-exp env) e))
  7578. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7579. (values (Let x e^ b) Tb)]
  7580. [(Prim op es)
  7581. (define-values (new-es ts)
  7582. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7583. (values (Prim op new-es) (type-check-op op ts e))]
  7584. [else (error 'type-check-exp "couldn't match" e)])))
  7585. (define/public (type-check-program e)
  7586. (match e
  7587. [(Program info body)
  7588. (define-values (body^ Tb) ((type-check-exp '()) body))
  7589. (check-type-equal? Tb 'Integer body)
  7590. (Program info body^)]
  7591. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7592. ))
  7593. (define (type-check-Lvar p)
  7594. (send (new type-check-Lvar-class) type-check-program p))
  7595. \end{lstlisting}
  7596. \fi}
  7597. {\if\edition\pythonEd\pythonColor
  7598. \begin{lstlisting}[escapechar=`]
  7599. class TypeCheckLvar:
  7600. def check_type_equal(self, t1, t2, e):
  7601. if t1 != t2:
  7602. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7603. raise Exception(msg)
  7604. def type_check_exp(self, e, env):
  7605. match e:
  7606. case BinOp(left, (Add() | Sub()), right):
  7607. l = self.type_check_exp(left, env)
  7608. check_type_equal(l, int, left)
  7609. r = self.type_check_exp(right, env)
  7610. check_type_equal(r, int, right)
  7611. return int
  7612. case UnaryOp(USub(), v):
  7613. t = self.type_check_exp(v, env)
  7614. check_type_equal(t, int, v)
  7615. return int
  7616. case Name(id):
  7617. return env[id]
  7618. case Constant(value) if isinstance(value, int):
  7619. return int
  7620. case Call(Name('input_int'), []):
  7621. return int
  7622. def type_check_stmts(self, ss, env):
  7623. if len(ss) == 0:
  7624. return
  7625. match ss[0]:
  7626. case Assign([Name(id)], value):
  7627. t = self.type_check_exp(value, env)
  7628. if id in env:
  7629. check_type_equal(env[id], t, value)
  7630. else:
  7631. env[id] = t
  7632. return self.type_check_stmts(ss[1:], env)
  7633. case Expr(Call(Name('print'), [arg])):
  7634. t = self.type_check_exp(arg, env)
  7635. check_type_equal(t, int, arg)
  7636. return self.type_check_stmts(ss[1:], env)
  7637. case Expr(value):
  7638. self.type_check_exp(value, env)
  7639. return self.type_check_stmts(ss[1:], env)
  7640. def type_check_P(self, p):
  7641. match p:
  7642. case Module(body):
  7643. self.type_check_stmts(body, {})
  7644. \end{lstlisting}
  7645. \fi}
  7646. \end{tcolorbox}
  7647. \caption{Type checker for the \LangVar{} language.}
  7648. \label{fig:type-check-Lvar}
  7649. \end{figure}
  7650. \begin{figure}[tbp]
  7651. \begin{tcolorbox}[colback=white]
  7652. {\if\edition\racketEd
  7653. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7654. (define type-check-Lif-class
  7655. (class type-check-Lvar-class
  7656. (super-new)
  7657. (inherit check-type-equal?)
  7658. (define/override (operator-types)
  7659. (append '((and . ((Boolean Boolean) . Boolean))
  7660. (or . ((Boolean Boolean) . Boolean))
  7661. (< . ((Integer Integer) . Boolean))
  7662. (<= . ((Integer Integer) . Boolean))
  7663. (> . ((Integer Integer) . Boolean))
  7664. (>= . ((Integer Integer) . Boolean))
  7665. (not . ((Boolean) . Boolean)))
  7666. (super operator-types)))
  7667. (define/override (type-check-exp env)
  7668. (lambda (e)
  7669. (match e
  7670. [(Bool b) (values (Bool b) 'Boolean)]
  7671. [(Prim 'eq? (list e1 e2))
  7672. (define-values (e1^ T1) ((type-check-exp env) e1))
  7673. (define-values (e2^ T2) ((type-check-exp env) e2))
  7674. (check-type-equal? T1 T2 e)
  7675. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7676. [(If cnd thn els)
  7677. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7678. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7679. (define-values (els^ Te) ((type-check-exp env) els))
  7680. (check-type-equal? Tc 'Boolean e)
  7681. (check-type-equal? Tt Te e)
  7682. (values (If cnd^ thn^ els^) Te)]
  7683. [else ((super type-check-exp env) e)])))
  7684. ))
  7685. (define (type-check-Lif p)
  7686. (send (new type-check-Lif-class) type-check-program p))
  7687. \end{lstlisting}
  7688. \fi}
  7689. {\if\edition\pythonEd\pythonColor
  7690. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7691. class TypeCheckLif(TypeCheckLvar):
  7692. def type_check_exp(self, e, env):
  7693. match e:
  7694. case Constant(value) if isinstance(value, bool):
  7695. return bool
  7696. case BinOp(left, Sub(), right):
  7697. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7698. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7699. return int
  7700. case UnaryOp(Not(), v):
  7701. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7702. return bool
  7703. case BoolOp(op, values):
  7704. left = values[0] ; right = values[1]
  7705. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7706. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7707. return bool
  7708. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7709. or isinstance(cmp, NotEq):
  7710. l = self.type_check_exp(left, env)
  7711. r = self.type_check_exp(right, env)
  7712. check_type_equal(l, r, e)
  7713. return bool
  7714. case Compare(left, [cmp], [right]):
  7715. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7716. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7717. return bool
  7718. case IfExp(test, body, orelse):
  7719. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7720. b = self.type_check_exp(body, env)
  7721. o = self.type_check_exp(orelse, env)
  7722. check_type_equal(b, o, e)
  7723. return b
  7724. case _:
  7725. return super().type_check_exp(e, env)
  7726. def type_check_stmts(self, ss, env):
  7727. if len(ss) == 0:
  7728. return
  7729. match ss[0]:
  7730. case If(test, body, orelse):
  7731. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7732. b = self.type_check_stmts(body, env)
  7733. o = self.type_check_stmts(orelse, env)
  7734. check_type_equal(b, o, ss[0])
  7735. return self.type_check_stmts(ss[1:], env)
  7736. case _:
  7737. return super().type_check_stmts(ss, env)
  7738. \end{lstlisting}
  7739. \fi}
  7740. \end{tcolorbox}
  7741. \caption{Type checker for the \LangIf{} language.}
  7742. \label{fig:type-check-Lif}
  7743. \end{figure}
  7744. The definition of the type checker for \LangIf{} is shown in
  7745. figure~\ref{fig:type-check-Lif}.
  7746. %
  7747. The type of a Boolean constant is \BOOLTY{}.
  7748. %
  7749. \racket{The \code{operator-types} function adds dictionary entries for
  7750. the new operators.}
  7751. %
  7752. \python{The logical \code{not} operator requires its argument to be a
  7753. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7754. and logical \code{or} operators.}
  7755. %
  7756. The equality operator requires the two arguments to have the same type,
  7757. and therefore we handle it separately from the other operators.
  7758. %
  7759. \python{The other comparisons (less-than, etc.) require their
  7760. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7761. %
  7762. The condition of an \code{if} must
  7763. be of \BOOLTY{} type, and the two branches must have the same type.
  7764. \begin{exercise}\normalfont\normalsize
  7765. Create ten new test programs in \LangIf{}. Half the programs should
  7766. have a type error.
  7767. \racket{For those programs, create an empty file with the
  7768. same base name and with file extension \code{.tyerr}. For example, if
  7769. the test \code{cond\_test\_14.rkt}
  7770. is expected to error, then create
  7771. an empty file named \code{cond\_test\_14.tyerr}.
  7772. This indicates to \code{interp-tests} and
  7773. \code{compiler-tests} that a type error is expected.}
  7774. %
  7775. The other half of the test programs should not have type errors.
  7776. %
  7777. \racket{In the \code{run-tests.rkt} script, change the second argument
  7778. of \code{interp-tests} and \code{compiler-tests} to
  7779. \code{type-check-Lif}, which causes the type checker to run prior to
  7780. the compiler passes. Temporarily change the \code{passes} to an
  7781. empty list and run the script, thereby checking that the new test
  7782. programs either type check or do not, as intended.}
  7783. %
  7784. Run the test script to check that these test programs type check as
  7785. expected.
  7786. \end{exercise}
  7787. \clearpage
  7788. \section{The \LangCIf{} Intermediate Language}
  7789. \label{sec:Cif}
  7790. {\if\edition\racketEd
  7791. %
  7792. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7793. comparison operators to the \Exp{} nonterminal and the literals
  7794. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7795. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7796. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7797. comparison operation and the branches are \code{goto} statements,
  7798. making it straightforward to compile \code{if} statements to x86. The
  7799. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7800. expressions. A \code{goto} statement transfers control to the $\Tail$
  7801. expression corresponding to its label.
  7802. %
  7803. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7804. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7805. defines its abstract syntax.
  7806. %
  7807. \fi}
  7808. %
  7809. {\if\edition\pythonEd\pythonColor
  7810. %
  7811. The output of \key{explicate\_control} is a language similar to the
  7812. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7813. \code{goto} statements, so we name it \LangCIf{}.
  7814. %
  7815. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7816. the arguments of operators are restricted to atomic expressions. The
  7817. \LangCIf{} language does not include \code{if} expressions, but it does
  7818. include a restricted form of \code{if} statement. The condition must be
  7819. a comparison, and the two branches may contain only \code{goto}
  7820. statements. These restrictions make it easier to translate \code{if}
  7821. statements to x86. The \LangCIf{} language also adds a \code{return}
  7822. statement to finish the program with a specified value.
  7823. %
  7824. The \key{CProgram} construct contains a dictionary mapping labels to
  7825. lists of statements that end with a \emph{tail} statement, which is
  7826. either a \code{return} statement, a \code{goto}, or an
  7827. \code{if} statement.
  7828. %
  7829. A \code{goto} transfers control to the sequence of statements
  7830. associated with its label.
  7831. %
  7832. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7833. and figure~\ref{fig:c1-syntax} shows its
  7834. abstract syntax.
  7835. %
  7836. \fi}
  7837. %
  7838. \newcommand{\CifGrammarRacket}{
  7839. \begin{array}{lcl}
  7840. \Atm &::=& \itm{bool} \\
  7841. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7842. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7843. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7844. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7845. \end{array}
  7846. }
  7847. \newcommand{\CifASTRacket}{
  7848. \begin{array}{lcl}
  7849. \Atm &::=& \BOOL{\itm{bool}} \\
  7850. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7851. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7852. \Tail &::= & \GOTO{\itm{label}} \\
  7853. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7854. \end{array}
  7855. }
  7856. \newcommand{\CifGrammarPython}{
  7857. \begin{array}{lcl}
  7858. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7859. \Exp &::= & \Atm \MID \CREAD{}
  7860. \MID \CUNIOP{\key{-}}{\Atm}
  7861. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7862. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7863. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7864. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7865. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7866. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7867. \end{array}
  7868. }
  7869. \newcommand{\CifASTPython}{
  7870. \begin{array}{lcl}
  7871. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7872. \Exp &::= & \Atm \MID \READ{}
  7873. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7874. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7875. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7876. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7877. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7878. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7879. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7880. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7881. \end{array}
  7882. }
  7883. \begin{figure}[tbp]
  7884. \begin{tcolorbox}[colback=white]
  7885. \small
  7886. {\if\edition\racketEd
  7887. \[
  7888. \begin{array}{l}
  7889. \gray{\CvarGrammarRacket} \\ \hline
  7890. \CifGrammarRacket \\
  7891. \begin{array}{lcl}
  7892. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7893. \end{array}
  7894. \end{array}
  7895. \]
  7896. \fi}
  7897. {\if\edition\pythonEd\pythonColor
  7898. \[
  7899. \begin{array}{l}
  7900. \CifGrammarPython \\
  7901. \begin{array}{lcl}
  7902. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7903. \end{array}
  7904. \end{array}
  7905. \]
  7906. \fi}
  7907. \end{tcolorbox}
  7908. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7909. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7910. \label{fig:c1-concrete-syntax}
  7911. \index{subject}{Cif@\LangCIf{} concrete syntax}
  7912. \end{figure}
  7913. \begin{figure}[tp]
  7914. \begin{tcolorbox}[colback=white]
  7915. \small
  7916. {\if\edition\racketEd
  7917. \[
  7918. \begin{array}{l}
  7919. \gray{\CvarASTRacket} \\ \hline
  7920. \CifASTRacket \\
  7921. \begin{array}{lcl}
  7922. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7923. \end{array}
  7924. \end{array}
  7925. \]
  7926. \fi}
  7927. {\if\edition\pythonEd\pythonColor
  7928. \[
  7929. \begin{array}{l}
  7930. \CifASTPython \\
  7931. \begin{array}{lcl}
  7932. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7933. \end{array}
  7934. \end{array}
  7935. \]
  7936. \fi}
  7937. \end{tcolorbox}
  7938. \racket{
  7939. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7940. }
  7941. \index{subject}{Goto@\texttt{Goto}}
  7942. \index{subject}{Return@\texttt{Return}}
  7943. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7944. (figure~\ref{fig:c0-syntax})}.}
  7945. \label{fig:c1-syntax}
  7946. \index{subject}{Cif@\LangCIf{} abstract syntax}
  7947. \end{figure}
  7948. \section{The \LangXIf{} Language}
  7949. \label{sec:x86-if}
  7950. \index{subject}{x86}
  7951. To implement Booleans, the new logical operations, the
  7952. comparison operations, and the \key{if} expression\python{ and
  7953. statement}, we delve further into the x86
  7954. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7955. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7956. subset of x86, which includes instructions for logical operations,
  7957. comparisons, and \racket{conditional} jumps.
  7958. %
  7959. \python{The abstract syntax for an \LangXIf{} program contains a
  7960. dictionary mapping labels to sequences of instructions, each of
  7961. which we refer to as a \emph{basic block}\index{subject}{basic
  7962. block}.}
  7963. As x86 does not provide direct support for Booleans, we take the usual
  7964. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7965. \code{False} as $0$.
  7966. Furthermore, x86 does not provide an instruction that directly
  7967. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7968. However, the \code{xorq} instruction can be used to encode \code{not}.
  7969. The \key{xorq} instruction takes two arguments, performs a pairwise
  7970. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7971. and writes the results into its second argument. Recall the following
  7972. truth table for exclusive-or:
  7973. \begin{center}
  7974. \begin{tabular}{l|cc}
  7975. & 0 & 1 \\ \hline
  7976. 0 & 0 & 1 \\
  7977. 1 & 1 & 0
  7978. \end{tabular}
  7979. \end{center}
  7980. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7981. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7982. for the bit $1$, the result is the opposite of the second bit. Thus,
  7983. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7984. the first argument, as follows, where $\Arg$ is the translation of
  7985. $\Atm$ to x86:
  7986. \[
  7987. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7988. \qquad\Rightarrow\qquad
  7989. \begin{array}{l}
  7990. \key{movq}~ \Arg\key{,} \Var\\
  7991. \key{xorq}~ \key{\$1,} \Var
  7992. \end{array}
  7993. \]
  7994. \newcommand{\GrammarXIf}{
  7995. \begin{array}{lcl}
  7996. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7997. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7998. \Arg &::=& \key{\%}\itm{bytereg}\\
  7999. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8000. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8001. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8002. \MID \key{set}cc~\Arg
  8003. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8004. &\MID& \key{j}cc~\itm{label} \\
  8005. \end{array}
  8006. }
  8007. \begin{figure}[tp]
  8008. \begin{tcolorbox}[colback=white]
  8009. \[
  8010. \begin{array}{l}
  8011. \gray{\GrammarXInt} \\ \hline
  8012. \GrammarXIf \\
  8013. \begin{array}{lcl}
  8014. \LangXIfM{} &::= & \key{.globl main} \\
  8015. & & \key{main:} \; \Instr\ldots
  8016. \end{array}
  8017. \end{array}
  8018. \]
  8019. \end{tcolorbox}
  8020. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  8021. \label{fig:x86-1-concrete}
  8022. \index{subject}{x86if@\LangXIf{} concrete syntax}
  8023. \end{figure}
  8024. \newcommand{\ASTXIfRacket}{
  8025. \begin{array}{lcl}
  8026. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8027. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8028. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8029. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8030. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8031. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8032. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8033. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8034. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8035. \end{array}
  8036. }
  8037. \newcommand{\ASTXIfPython}{
  8038. \begin{array}{lcl}
  8039. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8040. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8041. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8042. \MID \BYTEREG{\itm{bytereg}} \\
  8043. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8044. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8045. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8046. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8047. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8048. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8049. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8050. \end{array}
  8051. }
  8052. \begin{figure}[tp]
  8053. \begin{tcolorbox}[colback=white]
  8054. \small
  8055. {\if\edition\racketEd
  8056. \[\arraycolsep=3pt
  8057. \begin{array}{l}
  8058. \gray{\ASTXIntRacket} \\ \hline
  8059. \ASTXIfRacket \\
  8060. \begin{array}{lcl}
  8061. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8062. \end{array}
  8063. \end{array}
  8064. \]
  8065. \fi}
  8066. %
  8067. {\if\edition\pythonEd\pythonColor
  8068. \[
  8069. \begin{array}{l}
  8070. \gray{\ASTXIntPython} \\ \hline
  8071. \ASTXIfPython \\
  8072. \begin{array}{lcl}
  8073. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8074. \end{array}
  8075. \end{array}
  8076. \]
  8077. \fi}
  8078. \end{tcolorbox}
  8079. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8080. \label{fig:x86-1}
  8081. \index{subject}{x86if@\LangXIf{} abstract syntax}
  8082. \end{figure}
  8083. Next we consider the x86 instructions that are relevant for compiling
  8084. the comparison operations. The \key{cmpq} instruction compares its two
  8085. arguments to determine whether one argument is less than, equal to, or
  8086. greater than the other argument. The \key{cmpq} instruction is unusual
  8087. regarding the order of its arguments and where the result is
  8088. placed. The argument order is backward: if you want to test whether
  8089. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8090. \key{cmpq} is placed in the special EFLAGS register. This register
  8091. cannot be accessed directly, but it can be queried by a number of
  8092. instructions, including the \key{set} instruction. The instruction
  8093. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8094. depending on whether the contents of the EFLAGS register matches the
  8095. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8096. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8097. The \key{set} instruction has a quirk in that its destination argument
  8098. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8099. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8100. register. Thankfully, the \key{movzbq} instruction can be used to
  8101. move from a single-byte register to a normal 64-bit register. The
  8102. abstract syntax for the \code{set} instruction differs from the
  8103. concrete syntax in that it separates the instruction name from the
  8104. condition code.
  8105. \python{The x86 instructions for jumping are relevant to the
  8106. compilation of \key{if} expressions.}
  8107. %
  8108. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8109. counter to the address of the instruction after the specified
  8110. label.}
  8111. %
  8112. \racket{The x86 instruction for conditional jump is relevant to the
  8113. compilation of \key{if} expressions.}
  8114. %
  8115. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8116. counter to point to the instruction after \itm{label}, depending on
  8117. whether the result in the EFLAGS register matches the condition code
  8118. \itm{cc}; otherwise, the jump instruction falls through to the next
  8119. instruction. Like the abstract syntax for \code{set}, the abstract
  8120. syntax for conditional jump separates the instruction name from the
  8121. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8122. corresponds to \code{jle foo}. Because the conditional jump instruction
  8123. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8124. a \key{cmpq} instruction to set the EFLAGS register.
  8125. \section{Shrink the \LangIf{} Language}
  8126. \label{sec:shrink-Lif}
  8127. The \code{shrink} pass translates some of the language features into
  8128. other features, thereby reducing the kinds of expressions in the
  8129. language. For example, the short-circuiting nature of the \code{and}
  8130. and \code{or} logical operators can be expressed using \code{if} as
  8131. follows.
  8132. \begin{align*}
  8133. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8134. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8135. \end{align*}
  8136. By performing these translations in the front end of the compiler,
  8137. subsequent passes of the compiler can be shorter.
  8138. On the other hand, translations sometimes reduce the efficiency of the
  8139. generated code by increasing the number of instructions. For example,
  8140. expressing subtraction in terms of addition and negation
  8141. \[
  8142. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8143. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8144. \]
  8145. produces code with two x86 instructions (\code{negq} and \code{addq})
  8146. instead of just one (\code{subq}). Thus, we do not recommend
  8147. translating subtraction into addition and negation.
  8148. \begin{exercise}\normalfont\normalsize
  8149. %
  8150. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8151. the language by translating them to \code{if} expressions in \LangIf{}.
  8152. %
  8153. Create four test programs that involve these operators.
  8154. %
  8155. {\if\edition\racketEd
  8156. In the \code{run-tests.rkt} script, add the following entry for
  8157. \code{shrink} to the list of passes (it should be the only pass at
  8158. this point).
  8159. \begin{lstlisting}
  8160. (list "shrink" shrink interp_Lif type-check-Lif)
  8161. \end{lstlisting}
  8162. This instructs \code{interp-tests} to run the interpreter
  8163. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8164. output of \code{shrink}.
  8165. \fi}
  8166. %
  8167. Run the script to test your compiler on all the test programs.
  8168. \end{exercise}
  8169. {\if\edition\racketEd
  8170. \section{Uniquify Variables}
  8171. \label{sec:uniquify-Lif}
  8172. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8173. \code{if} expressions.
  8174. \begin{exercise}\normalfont\normalsize
  8175. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8176. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8177. \begin{lstlisting}
  8178. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8179. \end{lstlisting}
  8180. Run the script to test your compiler.
  8181. \end{exercise}
  8182. \fi}
  8183. \section{Remove Complex Operands}
  8184. \label{sec:remove-complex-opera-Lif}
  8185. The output language of \code{remove\_complex\_operands} is
  8186. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8187. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8188. but the \code{if} expression is not. All three subexpressions of an
  8189. \code{if} are allowed to be complex expressions, but the operands of
  8190. the \code{not} operator and comparison operators must be atomic.
  8191. %
  8192. \python{We add a new language form, the \code{Begin} expression, to aid
  8193. in the translation of \code{if} expressions. When we recursively
  8194. process the two branches of the \code{if}, we generate temporary
  8195. variables and their initializing expressions. However, these
  8196. expressions may contain side effects and should be executed only
  8197. when the condition of the \code{if} is true (for the ``then''
  8198. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8199. provides a way to initialize the temporary variables within the two branches
  8200. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8201. form executes the statements $ss$ and then returns the result of
  8202. expression $e$.}
  8203. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8204. the new features in \LangIf{}. In recursively processing
  8205. subexpressions, recall that you should invoke \code{rco\_atom} when
  8206. the output needs to be an \Atm{} (as specified in the grammar for
  8207. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8208. \Exp{}. Regarding \code{if}, it is particularly important
  8209. \emph{not} to replace its condition with a temporary variable, because
  8210. that would interfere with the generation of high-quality output in the
  8211. upcoming \code{explicate\_control} pass.
  8212. \newcommand{\LifMonadASTRacket}{
  8213. \begin{array}{rcl}
  8214. \Atm &::=& \BOOL{\itm{bool}}\\
  8215. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8216. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8217. \MID \IF{\Exp}{\Exp}{\Exp}
  8218. \end{array}
  8219. }
  8220. \newcommand{\LifMonadASTPython}{
  8221. \begin{array}{rcl}
  8222. \Atm &::=& \BOOL{\itm{bool}}\\
  8223. \Exp &::=& \UNIOP{\key{Not()}}{\Exp}
  8224. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8225. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8226. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8227. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8228. \end{array}
  8229. }
  8230. \begin{figure}[tp]
  8231. \centering
  8232. \begin{tcolorbox}[colback=white]
  8233. {\if\edition\racketEd
  8234. \[
  8235. \begin{array}{l}
  8236. \gray{\LvarMonadASTRacket} \\ \hline
  8237. \LifMonadASTRacket \\
  8238. \begin{array}{rcl}
  8239. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8240. \end{array}
  8241. \end{array}
  8242. \]
  8243. \fi}
  8244. {\if\edition\pythonEd\pythonColor
  8245. \[
  8246. \begin{array}{l}
  8247. \gray{\LvarMonadASTPython} \\ \hline
  8248. \LifMonadASTPython \\
  8249. \begin{array}{rcl}
  8250. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8251. \end{array}
  8252. \end{array}
  8253. \]
  8254. \fi}
  8255. \end{tcolorbox}
  8256. \python{\index{subject}{Begin@\texttt{Begin}}}
  8257. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8258. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8259. \label{fig:Lif-anf-syntax}
  8260. \index{subject}{Lifmon@\LangIfANF{} abstract syntax}
  8261. \end{figure}
  8262. \begin{exercise}\normalfont\normalsize
  8263. %
  8264. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8265. and \code{rco\_exp} functions.
  8266. %
  8267. Create three new \LangIf{} programs that exercise the interesting
  8268. code in this pass.
  8269. %
  8270. {\if\edition\racketEd
  8271. In the \code{run-tests.rkt} script, add the following entry to the
  8272. list of \code{passes} and then run the script to test your compiler.
  8273. \begin{lstlisting}
  8274. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8275. \end{lstlisting}
  8276. \fi}
  8277. \end{exercise}
  8278. \section{Explicate Control}
  8279. \label{sec:explicate-control-Lif}
  8280. \racket{Recall that the purpose of \code{explicate\_control} is to
  8281. make the order of evaluation explicit in the syntax of the program.
  8282. With the addition of \key{if}, this becomes more interesting.}
  8283. %
  8284. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8285. %
  8286. The main challenge to overcome is that the condition of an \key{if}
  8287. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8288. condition must be a comparison.
  8289. As a motivating example, consider the following program that has an
  8290. \key{if} expression nested in the condition of another \key{if}:%
  8291. \python{\footnote{Programmers rarely write nested \code{if}
  8292. expressions, but they do write nested expressions involving
  8293. logical \code{and}, which, as we have seen, translates to
  8294. \code{if}.}}
  8295. % cond_test_41.rkt, if_lt_eq.py
  8296. \begin{center}
  8297. \begin{minipage}{0.96\textwidth}
  8298. {\if\edition\racketEd
  8299. \begin{lstlisting}
  8300. (let ([x (read)])
  8301. (let ([y (read)])
  8302. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8303. (+ y 2)
  8304. (+ y 10))))
  8305. \end{lstlisting}
  8306. \fi}
  8307. {\if\edition\pythonEd\pythonColor
  8308. \begin{lstlisting}
  8309. x = input_int()
  8310. y = input_int()
  8311. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8312. \end{lstlisting}
  8313. \fi}
  8314. \end{minipage}
  8315. \end{center}
  8316. %
  8317. The naive way to compile \key{if} and the comparison operations would
  8318. be to handle each of them in isolation, regardless of their context.
  8319. Each comparison would be translated into a \key{cmpq} instruction
  8320. followed by several instructions to move the result from the EFLAGS
  8321. register into a general purpose register or stack location. Each
  8322. \key{if} would be translated into a \key{cmpq} instruction followed by
  8323. a conditional jump. The generated code for the inner \key{if} in this
  8324. example would be as follows:
  8325. \begin{center}
  8326. \begin{minipage}{0.96\textwidth}
  8327. \begin{lstlisting}
  8328. cmpq $1, x
  8329. setl %al
  8330. movzbq %al, tmp
  8331. cmpq $1, tmp
  8332. je then_branch_1
  8333. jmp else_branch_1
  8334. \end{lstlisting}
  8335. \end{minipage}
  8336. \end{center}
  8337. Notice that the three instructions starting with \code{setl} are
  8338. redundant; the conditional jump could come immediately after the first
  8339. \code{cmpq}.
  8340. Our goal is to compile \key{if} expressions so that the relevant
  8341. comparison instruction appears directly before the conditional jump.
  8342. For example, we want to generate the following code for the inner
  8343. \code{if}:
  8344. \begin{center}
  8345. \begin{minipage}{0.96\textwidth}
  8346. \begin{lstlisting}
  8347. cmpq $1, x
  8348. jl then_branch_1
  8349. jmp else_branch_1
  8350. \end{lstlisting}
  8351. \end{minipage}
  8352. \end{center}
  8353. One way to achieve this goal is to reorganize the code at the level of
  8354. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8355. the following code:
  8356. \begin{center}
  8357. \begin{minipage}{0.96\textwidth}
  8358. {\if\edition\racketEd
  8359. \begin{lstlisting}
  8360. (let ([x (read)])
  8361. (let ([y (read)])
  8362. (if (< x 1)
  8363. (if (eq? x 0)
  8364. (+ y 2)
  8365. (+ y 10))
  8366. (if (eq? x 2)
  8367. (+ y 2)
  8368. (+ y 10)))))
  8369. \end{lstlisting}
  8370. \fi}
  8371. {\if\edition\pythonEd\pythonColor
  8372. \begin{lstlisting}
  8373. x = input_int()
  8374. y = input_int()
  8375. print(((y + 2) if x == 0 else (y + 10)) \
  8376. if (x < 1) \
  8377. else ((y + 2) if (x == 2) else (y + 10)))
  8378. \end{lstlisting}
  8379. \fi}
  8380. \end{minipage}
  8381. \end{center}
  8382. Unfortunately, this approach duplicates the two branches from the
  8383. outer \code{if}, and a compiler must never duplicate code! After all,
  8384. the two branches could be very large expressions.
  8385. How can we apply this transformation without duplicating code? In
  8386. other words, how can two different parts of a program refer to one
  8387. piece of code?
  8388. %
  8389. The answer is that we must move away from abstract syntax \emph{trees}
  8390. and instead use \emph{graphs}.
  8391. %
  8392. At the level of x86 assembly, this is straightforward because we can
  8393. label the code for each branch and insert jumps in all the places that
  8394. need to execute the branch. In this way, jump instructions are edges
  8395. in the graph and the basic blocks are the nodes.
  8396. %
  8397. Likewise, our language \LangCIf{} provides the ability to label a
  8398. sequence of statements and to jump to a label via \code{goto}.
  8399. As a preview of what \code{explicate\_control} will do,
  8400. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8401. \code{explicate\_control} on this example. Note how the condition of
  8402. every \code{if} is a comparison operation and that we have not
  8403. duplicated any code but instead have used labels and \code{goto} to
  8404. enable sharing of code.
  8405. \begin{figure}[tbp]
  8406. \begin{tcolorbox}[colback=white]
  8407. {\if\edition\racketEd
  8408. \begin{tabular}{lll}
  8409. \begin{minipage}{0.4\textwidth}
  8410. % cond_test_41.rkt
  8411. \begin{lstlisting}
  8412. (let ([x (read)])
  8413. (let ([y (read)])
  8414. (if (if (< x 1)
  8415. (eq? x 0)
  8416. (eq? x 2))
  8417. (+ y 2)
  8418. (+ y 10))))
  8419. \end{lstlisting}
  8420. \end{minipage}
  8421. &
  8422. $\Rightarrow$
  8423. &
  8424. \begin{minipage}{0.55\textwidth}
  8425. \begin{lstlisting}
  8426. start:
  8427. x = (read);
  8428. y = (read);
  8429. if (< x 1)
  8430. goto block_4;
  8431. else
  8432. goto block_5;
  8433. block_4:
  8434. if (eq? x 0)
  8435. goto block_2;
  8436. else
  8437. goto block_3;
  8438. block_5:
  8439. if (eq? x 2)
  8440. goto block_2;
  8441. else
  8442. goto block_3;
  8443. block_2:
  8444. return (+ y 2);
  8445. block_3:
  8446. return (+ y 10);
  8447. \end{lstlisting}
  8448. \end{minipage}
  8449. \end{tabular}
  8450. \fi}
  8451. {\if\edition\pythonEd\pythonColor
  8452. \begin{tabular}{lll}
  8453. \begin{minipage}{0.4\textwidth}
  8454. % tests/if/if_lt_eq.py
  8455. \begin{lstlisting}
  8456. x = input_int()
  8457. y = input_int()
  8458. print(y + 2 \
  8459. if (x == 0 \
  8460. if x < 1 \
  8461. else x == 2) \
  8462. else y + 10)
  8463. \end{lstlisting}
  8464. \end{minipage}
  8465. &
  8466. $\Rightarrow\qquad$
  8467. &
  8468. \begin{minipage}{0.55\textwidth}
  8469. \begin{lstlisting}
  8470. start:
  8471. x = input_int()
  8472. y = input_int()
  8473. if x < 1:
  8474. goto block_6
  8475. else:
  8476. goto block_7
  8477. block_6:
  8478. if x == 0:
  8479. goto block_4
  8480. else:
  8481. goto block_5
  8482. block_7:
  8483. if x == 2:
  8484. goto block_4
  8485. else:
  8486. goto block_5
  8487. block_4:
  8488. tmp.82 = (y + 2)
  8489. goto block_3
  8490. block_5:
  8491. tmp.82 = (y + 10)
  8492. goto block_3
  8493. block_3:
  8494. print(tmp.82)
  8495. return 0
  8496. \end{lstlisting}
  8497. \end{minipage}
  8498. \end{tabular}
  8499. \fi}
  8500. \end{tcolorbox}
  8501. \caption{Translation from \LangIf{} to \LangCIf{}
  8502. via the \code{explicate\_control}.}
  8503. \label{fig:explicate-control-s1-38}
  8504. \end{figure}
  8505. {\if\edition\racketEd
  8506. %
  8507. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8508. \code{explicate\_control} for \LangVar{} using two recursive
  8509. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8510. former function translates expressions in tail position, whereas the
  8511. latter function translates expressions on the right-hand side of a
  8512. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8513. have a new kind of position to deal with: the predicate position of
  8514. the \key{if}. We need another function, \code{explicate\_pred}, that
  8515. decides how to compile an \key{if} by analyzing its condition. So,
  8516. \code{explicate\_pred} takes an \LangIf{} expression and two
  8517. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8518. and outputs a tail. In the following paragraphs we discuss specific
  8519. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8520. \code{explicate\_pred} functions.
  8521. %
  8522. \fi}
  8523. %
  8524. {\if\edition\pythonEd\pythonColor
  8525. %
  8526. We recommend implementing \code{explicate\_control} using the
  8527. following four auxiliary functions.
  8528. \begin{description}
  8529. \item[\code{explicate\_effect}] generates code for expressions as
  8530. statements, so their result is ignored and only their side effects
  8531. matter.
  8532. \item[\code{explicate\_assign}] generates code for expressions
  8533. on the right-hand side of an assignment.
  8534. \item[\code{explicate\_pred}] generates code for an \code{if}
  8535. expression or statement by analyzing the condition expression.
  8536. \item[\code{explicate\_stmt}] generates code for statements.
  8537. \end{description}
  8538. These four functions should build the dictionary of basic blocks. The
  8539. following auxiliary function \code{create\_block} is used to create a
  8540. new basic block from a list of statements. If the list just contains a
  8541. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8542. \code{create\_block} creates a new basic block and returns a
  8543. \code{goto} to its label.
  8544. \begin{center}
  8545. \begin{minipage}{\textwidth}
  8546. \begin{lstlisting}
  8547. def create_block(stmts, basic_blocks):
  8548. match stmts:
  8549. case [Goto(l)]:
  8550. return stmts
  8551. case _:
  8552. label = label_name(generate_name('block'))
  8553. basic_blocks[label] = stmts
  8554. return [Goto(label)]
  8555. \end{lstlisting}
  8556. \end{minipage}
  8557. \end{center}
  8558. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8559. \code{explicate\_control} pass.
  8560. The \code{explicate\_effect} function has three parameters: (1) the
  8561. expression to be compiled; (2) the already-compiled code for this
  8562. expression's \emph{continuation}, that is, the list of statements that
  8563. should execute after this expression; and (3) the dictionary of
  8564. generated basic blocks. The \code{explicate\_effect} function returns
  8565. a list of \LangCIf{} statements and it may add to the dictionary of
  8566. basic blocks.
  8567. %
  8568. Let's consider a few of the cases for the expression to be compiled.
  8569. If the expression to be compiled is a constant, then it can be
  8570. discarded because it has no side effects. If it's a \CREAD{}, then it
  8571. has a side effect and should be preserved. So the expression should be
  8572. translated into a statement using the \code{Expr} AST class. If the
  8573. expression to be compiled is an \code{if} expression, we translate the
  8574. two branches using \code{explicate\_effect} and then translate the
  8575. condition expression using \code{explicate\_pred}, which generates
  8576. code for the entire \code{if}.
  8577. The \code{explicate\_assign} function has four parameters: (1) the
  8578. right-hand side of the assignment, (2) the left-hand side of the
  8579. assignment (the variable), (3) the continuation, and (4) the dictionary
  8580. of basic blocks. The \code{explicate\_assign} function returns a list
  8581. of \LangCIf{} statements, and it may add to the dictionary of basic
  8582. blocks.
  8583. When the right-hand side is an \code{if} expression, there is some
  8584. work to do. In particular, the two branches should be translated using
  8585. \code{explicate\_assign}, and the condition expression should be
  8586. translated using \code{explicate\_pred}. Otherwise we can simply
  8587. generate an assignment statement, with the given left- and right-hand
  8588. sides, concatenated with its continuation.
  8589. \begin{figure}[tbp]
  8590. \begin{tcolorbox}[colback=white]
  8591. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8592. def explicate_effect(e, cont, basic_blocks):
  8593. match e:
  8594. case IfExp(test, body, orelse):
  8595. ...
  8596. case Call(func, args):
  8597. ...
  8598. case Begin(body, result):
  8599. ...
  8600. case _:
  8601. ...
  8602. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8603. match rhs:
  8604. case IfExp(test, body, orelse):
  8605. ...
  8606. case Begin(body, result):
  8607. ...
  8608. case _:
  8609. return [Assign([lhs], rhs)] + cont
  8610. def explicate_pred(cnd, thn, els, basic_blocks):
  8611. match cnd:
  8612. case Compare(left, [op], [right]):
  8613. goto_thn = create_block(thn, basic_blocks)
  8614. goto_els = create_block(els, basic_blocks)
  8615. return [If(cnd, goto_thn, goto_els)]
  8616. case Constant(True):
  8617. return thn;
  8618. case Constant(False):
  8619. return els;
  8620. case UnaryOp(Not(), operand):
  8621. ...
  8622. case IfExp(test, body, orelse):
  8623. ...
  8624. case Begin(body, result):
  8625. ...
  8626. case _:
  8627. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8628. create_block(els, basic_blocks),
  8629. create_block(thn, basic_blocks))]
  8630. def explicate_stmt(s, cont, basic_blocks):
  8631. match s:
  8632. case Assign([lhs], rhs):
  8633. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8634. case Expr(value):
  8635. return explicate_effect(value, cont, basic_blocks)
  8636. case If(test, body, orelse):
  8637. ...
  8638. def explicate_control(p):
  8639. match p:
  8640. case Module(body):
  8641. new_body = [Return(Constant(0))]
  8642. basic_blocks = {}
  8643. for s in reversed(body):
  8644. new_body = explicate_stmt(s, new_body, basic_blocks)
  8645. basic_blocks[label_name('start')] = new_body
  8646. return CProgram(basic_blocks)
  8647. \end{lstlisting}
  8648. \end{tcolorbox}
  8649. \caption{Skeleton for the \code{explicate\_control} pass.}
  8650. \label{fig:explicate-control-Lif}
  8651. \end{figure}
  8652. \fi}
  8653. {\if\edition\racketEd
  8654. \subsection{Explicate Tail and Assign}
  8655. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8656. additional cases for Boolean constants and \key{if}. The cases for
  8657. \code{if} should recursively compile the two branches using either
  8658. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8659. cases should then invoke \code{explicate\_pred} on the condition
  8660. expression, passing in the generated code for the two branches. For
  8661. example, consider the following program with an \code{if} in tail
  8662. position.
  8663. % cond_test_6.rkt
  8664. \begin{lstlisting}
  8665. (let ([x (read)])
  8666. (if (eq? x 0) 42 777))
  8667. \end{lstlisting}
  8668. The two branches are recursively compiled to return statements. We
  8669. then delegate to \code{explicate\_pred}, passing the condition
  8670. \code{(eq? x 0)} and the two return statements. We return to this
  8671. example shortly when we discuss \code{explicate\_pred}.
  8672. Next let us consider a program with an \code{if} on the right-hand
  8673. side of a \code{let}.
  8674. \begin{lstlisting}
  8675. (let ([y (read)])
  8676. (let ([x (if (eq? y 0) 40 777)])
  8677. (+ x 2)))
  8678. \end{lstlisting}
  8679. Note that the body of the inner \code{let} will have already been
  8680. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8681. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8682. to recursively process both branches of the \code{if}, and we do not
  8683. want to duplicate code, so we generate the following block using an
  8684. auxiliary function named \code{create\_block}, discussed in the next
  8685. section.
  8686. \begin{lstlisting}
  8687. block_6:
  8688. return (+ x 2)
  8689. \end{lstlisting}
  8690. We then use \code{goto block\_6;} as the \code{cont} argument for
  8691. compiling the branches. So the two branches compile to
  8692. \begin{center}
  8693. \begin{minipage}{0.2\textwidth}
  8694. \begin{lstlisting}
  8695. x = 40;
  8696. goto block_6;
  8697. \end{lstlisting}
  8698. \end{minipage}
  8699. \hspace{0.5in} and \hspace{0.5in}
  8700. \begin{minipage}{0.2\textwidth}
  8701. \begin{lstlisting}
  8702. x = 777;
  8703. goto block_6;
  8704. \end{lstlisting}
  8705. \end{minipage}
  8706. \end{center}
  8707. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8708. \code{(eq? y 0)} and the previously presented code for the branches.
  8709. \subsection{Create Block}
  8710. We recommend implementing the \code{create\_block} auxiliary function
  8711. as follows, using a global variable \code{basic-blocks} to store a
  8712. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8713. that \code{create\_block} generates a new label and then associates
  8714. the given \code{tail} with the new label in the \code{basic-blocks}
  8715. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8716. new label. However, if the given \code{tail} is already a \code{Goto},
  8717. then there is no need to generate a new label and entry in
  8718. \code{basic-blocks}; we can simply return that \code{Goto}.
  8719. %
  8720. \begin{lstlisting}
  8721. (define (create_block tail)
  8722. (match tail
  8723. [(Goto label) (Goto label)]
  8724. [else
  8725. (let ([label (gensym 'block)])
  8726. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8727. (Goto label))]))
  8728. \end{lstlisting}
  8729. \fi}
  8730. {\if\edition\racketEd
  8731. \subsection{Explicate Predicate}
  8732. The skeleton for the \code{explicate\_pred} function is given in
  8733. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8734. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8735. the code generated by explicate for the \emph{then} branch; and (3)
  8736. \code{els}, the code generated by explicate for the \emph{else}
  8737. branch. The \code{explicate\_pred} function should match on
  8738. \code{cnd} with a case for every kind of expression that can have type
  8739. \BOOLTY{}.
  8740. \begin{figure}[tbp]
  8741. \begin{tcolorbox}[colback=white]
  8742. \begin{lstlisting}
  8743. (define (explicate_pred cnd thn els)
  8744. (match cnd
  8745. [(Var x) ___]
  8746. [(Let x rhs body) ___]
  8747. [(Prim 'not (list e)) ___]
  8748. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8749. (IfStmt (Prim op es) (create_block thn)
  8750. (create_block els))]
  8751. [(Bool b) (if b thn els)]
  8752. [(If cnd^ thn^ els^) ___]
  8753. [else (error "explicate_pred unhandled case" cnd)]))
  8754. \end{lstlisting}
  8755. \end{tcolorbox}
  8756. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8757. \label{fig:explicate-pred}
  8758. \end{figure}
  8759. \fi}
  8760. %
  8761. {\if\edition\pythonEd\pythonColor
  8762. The \code{explicate\_pred} function has four parameters: (1) the
  8763. condition expression, (2) the generated statements for the \emph{then}
  8764. branch, (3) the generated statements for the \emph{else} branch, and
  8765. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8766. function returns a list of statements, and it adds to the dictionary
  8767. of basic blocks.
  8768. \fi}
  8769. Consider the case for comparison operators. We translate the
  8770. comparison to an \code{if} statement whose branches are \code{goto}
  8771. statements created by applying \code{create\_block} to the \code{thn}
  8772. and \code{els} parameters. Let us illustrate this translation by
  8773. returning to the program with an \code{if} expression in tail
  8774. position, shown next. We invoke \code{explicate\_pred} on its
  8775. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8776. %
  8777. {\if\edition\racketEd
  8778. \begin{lstlisting}
  8779. (let ([x (read)])
  8780. (if (eq? x 0) 42 777))
  8781. \end{lstlisting}
  8782. \fi}
  8783. %
  8784. {\if\edition\pythonEd\pythonColor
  8785. \begin{lstlisting}
  8786. x = input_int()
  8787. 42 if x == 0 else 777
  8788. \end{lstlisting}
  8789. \fi}
  8790. %
  8791. \noindent The two branches \code{42} and \code{777} were already
  8792. compiled to \code{return} statements, from which we now create the
  8793. following blocks:
  8794. %
  8795. \begin{center}
  8796. \begin{minipage}{\textwidth}
  8797. \begin{lstlisting}
  8798. block_1:
  8799. return 42;
  8800. block_2:
  8801. return 777;
  8802. \end{lstlisting}
  8803. \end{minipage}
  8804. \end{center}
  8805. %
  8806. After that, \code{explicate\_pred} compiles the comparison
  8807. \racket{\code{(eq? x 0)}}
  8808. \python{\code{x == 0}}
  8809. to the following \code{if} statement:
  8810. %
  8811. {\if\edition\racketEd
  8812. \begin{center}
  8813. \begin{minipage}{\textwidth}
  8814. \begin{lstlisting}
  8815. if (eq? x 0)
  8816. goto block_1;
  8817. else
  8818. goto block_2;
  8819. \end{lstlisting}
  8820. \end{minipage}
  8821. \end{center}
  8822. \fi}
  8823. {\if\edition\pythonEd\pythonColor
  8824. \begin{center}
  8825. \begin{minipage}{\textwidth}
  8826. \begin{lstlisting}
  8827. if x == 0:
  8828. goto block_1;
  8829. else
  8830. goto block_2;
  8831. \end{lstlisting}
  8832. \end{minipage}
  8833. \end{center}
  8834. \fi}
  8835. Next consider the case for Boolean constants. We perform a kind of
  8836. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8837. either the \code{thn} or \code{els} parameter, depending on whether the
  8838. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8839. following program:
  8840. {\if\edition\racketEd
  8841. \begin{lstlisting}
  8842. (if #t 42 777)
  8843. \end{lstlisting}
  8844. \fi}
  8845. {\if\edition\pythonEd\pythonColor
  8846. \begin{lstlisting}
  8847. 42 if True else 777
  8848. \end{lstlisting}
  8849. \fi}
  8850. %
  8851. \noindent Again, the two branches \code{42} and \code{777} were
  8852. compiled to \code{return} statements, so \code{explicate\_pred}
  8853. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8854. code for the \emph{then} branch.
  8855. \begin{lstlisting}
  8856. return 42;
  8857. \end{lstlisting}
  8858. This case demonstrates that we sometimes discard the \code{thn} or
  8859. \code{els} blocks that are input to \code{explicate\_pred}.
  8860. The case for \key{if} expressions in \code{explicate\_pred} is
  8861. particularly illuminating because it deals with the challenges
  8862. discussed previously regarding nested \key{if} expressions
  8863. (figure~\ref{fig:explicate-control-s1-38}). The
  8864. \racket{\lstinline{thn^}}\python{\code{body}} and
  8865. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8866. \key{if} inherit their context from the current one, that is,
  8867. predicate context. So, you should recursively apply
  8868. \code{explicate\_pred} to the
  8869. \racket{\lstinline{thn^}}\python{\code{body}} and
  8870. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8871. those recursive calls, pass \code{thn} and \code{els} as the extra
  8872. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8873. inside each recursive call. As discussed previously, to avoid
  8874. duplicating code, we need to add them to the dictionary of basic
  8875. blocks so that we can instead refer to them by name and execute them
  8876. with a \key{goto}.
  8877. {\if\edition\pythonEd\pythonColor
  8878. %
  8879. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8880. three parameters: (1) the statement to be compiled, (2) the code for its
  8881. continuation, and (3) the dictionary of basic blocks. The
  8882. \code{explicate\_stmt} returns a list of statements, and it may add to
  8883. the dictionary of basic blocks. The cases for assignment and an
  8884. expression-statement are given in full in the skeleton code: they
  8885. simply dispatch to \code{explicate\_assign} and
  8886. \code{explicate\_effect}, respectively. The case for \code{if}
  8887. statements is not given; it is similar to the case for \code{if}
  8888. expressions.
  8889. The \code{explicate\_control} function itself is given in
  8890. figure~\ref{fig:explicate-control-Lif}. It applies
  8891. \code{explicate\_stmt} to each statement in the program, from back to
  8892. front. Thus, the result so far, stored in \code{new\_body}, can be
  8893. used as the continuation parameter in the next call to
  8894. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8895. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8896. the dictionary of basic blocks, labeling it the ``start'' block.
  8897. %
  8898. \fi}
  8899. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8900. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8901. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8902. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8903. %% results from the two recursive calls. We complete the case for
  8904. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8905. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8906. %% the result $B_5$.
  8907. %% \[
  8908. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8909. %% \quad\Rightarrow\quad
  8910. %% B_5
  8911. %% \]
  8912. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8913. %% inherit the current context, so they are in tail position. Thus, the
  8914. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8915. %% \code{explicate\_tail}.
  8916. %% %
  8917. %% We need to pass $B_0$ as the accumulator argument for both of these
  8918. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8919. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8920. %% to the control-flow graph and obtain a promised goto $G_0$.
  8921. %% %
  8922. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8923. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8924. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8925. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8926. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8927. %% \[
  8928. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8929. %% \]
  8930. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8931. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8932. %% should not be confused with the labels for the blocks that appear in
  8933. %% the generated code. We initially construct unlabeled blocks; we only
  8934. %% attach labels to blocks when we add them to the control-flow graph, as
  8935. %% we see in the next case.
  8936. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8937. %% function. The context of the \key{if} is an assignment to some
  8938. %% variable $x$ and then the control continues to some promised block
  8939. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8940. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8941. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8942. %% branches of the \key{if} inherit the current context, so they are in
  8943. %% assignment positions. Let $B_2$ be the result of applying
  8944. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8945. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8946. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8947. %% the result of applying \code{explicate\_pred} to the predicate
  8948. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8949. %% translates to the promise $B_4$.
  8950. %% \[
  8951. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8952. %% \]
  8953. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8954. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8955. \code{remove\_complex\_operands} pass and then the
  8956. \code{explicate\_control} pass on the example program. We walk through
  8957. the output program.
  8958. %
  8959. Following the order of evaluation in the output of
  8960. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8961. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8962. in the predicate of the inner \key{if}. In the output of
  8963. \code{explicate\_control}, in the
  8964. block labeled \code{start}, two assignment statements are followed by an
  8965. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  8966. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  8967. The blocks associated with those labels contain the
  8968. translations of the code
  8969. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8970. and
  8971. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8972. respectively. In particular, we start
  8973. \racket{\code{block\_4}}\python{\code{block\_6}}
  8974. with the comparison
  8975. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8976. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  8977. or \racket{\code{block\_3}}\python{\code{block\_5}},
  8978. which correspond to the two branches of the outer \key{if}, that is,
  8979. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8980. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8981. %
  8982. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  8983. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  8984. %
  8985. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  8986. {\if\edition\racketEd
  8987. \subsection{Interactions between Explicate and Shrink}
  8988. The way in which the \code{shrink} pass transforms logical operations
  8989. such as \code{and} and \code{or} can impact the quality of code
  8990. generated by \code{explicate\_control}. For example, consider the
  8991. following program:
  8992. % cond_test_21.rkt, and_eq_input.py
  8993. \begin{lstlisting}
  8994. (if (and (eq? (read) 0) (eq? (read) 1))
  8995. 0
  8996. 42)
  8997. \end{lstlisting}
  8998. The \code{and} operation should transform into something that the
  8999. \code{explicate\_pred} function can analyze and descend through to
  9000. reach the underlying \code{eq?} conditions. Ideally, for this program
  9001. your \code{explicate\_control} pass should generate code similar to
  9002. the following:
  9003. \begin{center}
  9004. \begin{minipage}{\textwidth}
  9005. \begin{lstlisting}
  9006. start:
  9007. tmp1 = (read);
  9008. if (eq? tmp1 0) goto block40;
  9009. else goto block39;
  9010. block40:
  9011. tmp2 = (read);
  9012. if (eq? tmp2 1) goto block38;
  9013. else goto block39;
  9014. block38:
  9015. return 0;
  9016. block39:
  9017. return 42;
  9018. \end{lstlisting}
  9019. \end{minipage}
  9020. \end{center}
  9021. \fi}
  9022. \begin{exercise}\normalfont\normalsize
  9023. \racket{
  9024. Implement the pass \code{explicate\_control} by adding the cases for
  9025. Boolean constants and \key{if} to the \code{explicate\_tail} and
  9026. \code{explicate\_assign} functions. Implement the auxiliary function
  9027. \code{explicate\_pred} for predicate contexts.}
  9028. \python{Implement \code{explicate\_control} pass with its
  9029. four auxiliary functions.}
  9030. %
  9031. Create test cases that exercise all the new cases in the code for
  9032. this pass.
  9033. %
  9034. {\if\edition\racketEd
  9035. Add the following entry to the list of \code{passes} in
  9036. \code{run-tests.rkt}:
  9037. \begin{lstlisting}
  9038. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9039. \end{lstlisting}
  9040. and then run \code{run-tests.rkt} to test your compiler.
  9041. \fi}
  9042. \end{exercise}
  9043. \section{Select Instructions}
  9044. \label{sec:select-Lif}
  9045. \index{subject}{select instructions}
  9046. The \code{select\_instructions} pass translates \LangCIf{} to
  9047. \LangXIfVar{}.
  9048. %
  9049. \racket{Recall that we implement this pass using three auxiliary
  9050. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9051. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9052. %
  9053. \racket{For $\Atm$, we have new cases for the Booleans.}
  9054. %
  9055. \python{We begin with the Boolean constants.}
  9056. As previously discussed, we encode them as integers.
  9057. \[
  9058. \TRUE{} \quad\Rightarrow\quad \key{1}
  9059. \qquad\qquad
  9060. \FALSE{} \quad\Rightarrow\quad \key{0}
  9061. \]
  9062. For translating statements, we discuss some of the cases. The
  9063. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9064. discussed at the beginning of this section. Given an assignment, if
  9065. the left-hand-side variable is the same as the argument of \code{not},
  9066. then just the \code{xorq} instruction suffices.
  9067. \[
  9068. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9069. \quad\Rightarrow\quad
  9070. \key{xorq}~\key{\$}1\key{,}~\Var
  9071. \]
  9072. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9073. semantics of x86. In the following translation, let $\Arg$ be the
  9074. result of translating $\Atm$ to x86.
  9075. \[
  9076. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9077. \quad\Rightarrow\quad
  9078. \begin{array}{l}
  9079. \key{movq}~\Arg\key{,}~\Var\\
  9080. \key{xorq}~\key{\$}1\key{,}~\Var
  9081. \end{array}
  9082. \]
  9083. Next consider the cases for equality comparisons. Translating this
  9084. operation to x86 is slightly involved due to the unusual nature of the
  9085. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9086. We recommend translating an assignment with an equality on the
  9087. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9088. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9089. \begin{tabular}{lll}
  9090. \begin{minipage}{0.4\textwidth}
  9091. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9092. \end{minipage}
  9093. &
  9094. $\Rightarrow$
  9095. &
  9096. \begin{minipage}{0.4\textwidth}
  9097. \begin{lstlisting}
  9098. cmpq |$\Arg_2$|, |$\Arg_1$|
  9099. sete %al
  9100. movzbq %al, |$\Var$|
  9101. \end{lstlisting}
  9102. \end{minipage}
  9103. \end{tabular} \\
  9104. The translations for the other comparison operators are similar to
  9105. this but use different condition codes for the \code{set} instruction.
  9106. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9107. \key{goto} and \key{if} statements. Both are straightforward to
  9108. translate to x86.}
  9109. %
  9110. A \key{goto} statement becomes a jump instruction.
  9111. \[
  9112. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9113. \]
  9114. %
  9115. An \key{if} statement becomes a compare instruction followed by a
  9116. conditional jump (for the \emph{then} branch), and the fall-through is to
  9117. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9118. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9119. \begin{tabular}{lll}
  9120. \begin{minipage}{0.4\textwidth}
  9121. \begin{lstlisting}
  9122. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9123. goto |$\ell_1$||$\racket{\key{;}}$|
  9124. else|$\python{\key{:}}$|
  9125. goto |$\ell_2$||$\racket{\key{;}}$|
  9126. \end{lstlisting}
  9127. \end{minipage}
  9128. &
  9129. $\Rightarrow$
  9130. &
  9131. \begin{minipage}{0.4\textwidth}
  9132. \begin{lstlisting}
  9133. cmpq |$\Arg_2$|, |$\Arg_1$|
  9134. je |$\ell_1$|
  9135. jmp |$\ell_2$|
  9136. \end{lstlisting}
  9137. \end{minipage}
  9138. \end{tabular} \\
  9139. Again, the translations for the other comparison operators are similar to this
  9140. but use different condition codes for the conditional jump instruction.
  9141. \python{Regarding the \key{return} statement, we recommend treating it
  9142. as an assignment to the \key{rax} register followed by a jump to the
  9143. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9144. \begin{exercise}\normalfont\normalsize
  9145. Expand your \code{select\_instructions} pass to handle the new
  9146. features of the \LangCIf{} language.
  9147. %
  9148. {\if\edition\racketEd
  9149. Add the following entry to the list of \code{passes} in
  9150. \code{run-tests.rkt}
  9151. \begin{lstlisting}
  9152. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9153. \end{lstlisting}
  9154. \fi}
  9155. %
  9156. Run the script to test your compiler on all the test programs.
  9157. \end{exercise}
  9158. \section{Register Allocation}
  9159. \label{sec:register-allocation-Lif}
  9160. \index{subject}{register allocation}
  9161. The changes required for compiling \LangIf{} affect liveness analysis,
  9162. building the interference graph, and assigning homes, but the graph
  9163. coloring algorithm itself does not change.
  9164. \subsection{Liveness Analysis}
  9165. \label{sec:liveness-analysis-Lif}
  9166. \index{subject}{liveness analysis}
  9167. Recall that for \LangVar{} we implemented liveness analysis for a
  9168. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9169. the addition of \key{if} expressions to \LangIf{},
  9170. \code{explicate\_control} produces many basic blocks.
  9171. %% We recommend that you create a new auxiliary function named
  9172. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9173. %% control-flow graph.
  9174. The first question is, in what order should we process the basic blocks?
  9175. Recall that to perform liveness analysis on a basic block we need to
  9176. know the live-after set for the last instruction in the block. If a
  9177. basic block has no successors (i.e., contains no jumps to other
  9178. blocks), then it has an empty live-after set and we can immediately
  9179. apply liveness analysis to it. If a basic block has some successors,
  9180. then we need to complete liveness analysis on those blocks
  9181. first. These ordering constraints are the reverse of a
  9182. \emph{topological order}\index{subject}{topological order} on a graph
  9183. representation of the program. In particular, the \emph{control flow
  9184. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9185. of a program has a node for each basic block and an edge for each jump
  9186. from one block to another. It is straightforward to generate a CFG
  9187. from the dictionary of basic blocks. One then transposes the CFG and
  9188. applies the topological sort algorithm.
  9189. %
  9190. %
  9191. \racket{We recommend using the \code{tsort} and \code{transpose}
  9192. functions of the Racket \code{graph} package to accomplish this.}
  9193. %
  9194. \python{We provide implementations of \code{topological\_sort} and
  9195. \code{transpose} in the file \code{graph.py} of the support code.}
  9196. %
  9197. As an aside, a topological ordering is only guaranteed to exist if the
  9198. graph does not contain any cycles. This is the case for the
  9199. control-flow graphs that we generate from \LangIf{} programs.
  9200. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9201. and learn how to handle cycles in the control-flow graph.
  9202. \racket{You need to construct a directed graph to represent the
  9203. control-flow graph. Do not use the \code{directed-graph} of the
  9204. \code{graph} package because that allows at most one edge
  9205. between each pair of vertices, whereas a control-flow graph may have
  9206. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9207. file in the support code implements a graph representation that
  9208. allows multiple edges between a pair of vertices.}
  9209. {\if\edition\racketEd
  9210. The next question is how to analyze jump instructions. Recall that in
  9211. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9212. \code{label->live} that maps each label to the set of live locations
  9213. at the beginning of its block. We use \code{label->live} to determine
  9214. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9215. that we have many basic blocks, \code{label->live} needs to be updated
  9216. as we process the blocks. In particular, after performing liveness
  9217. analysis on a block, we take the live-before set of its first
  9218. instruction and associate that with the block's label in the
  9219. \code{label->live} alist.
  9220. \fi}
  9221. %
  9222. {\if\edition\pythonEd\pythonColor
  9223. %
  9224. The next question is how to analyze jump instructions. The locations
  9225. that are live before a \code{jmp} should be the locations in
  9226. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9227. maintaining a dictionary named \code{live\_before\_block} that maps each
  9228. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9229. block. After performing liveness analysis on each block, we take the
  9230. live-before set of its first instruction and associate that with the
  9231. block's label in the \code{live\_before\_block} dictionary.
  9232. %
  9233. \fi}
  9234. In \LangXIfVar{} we also have the conditional jump
  9235. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9236. this instruction is particularly interesting because during
  9237. compilation, we do not know which way a conditional jump will go. Thus
  9238. we do not know whether to use the live-before set for the block
  9239. associated with the $\itm{label}$ or the live-before set for the
  9240. following instruction. So we use both, by taking the union of the
  9241. live-before sets from the following instruction and from the mapping
  9242. for $\itm{label}$ in
  9243. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9244. The auxiliary functions for computing the variables in an
  9245. instruction's argument and for computing the variables read-from ($R$)
  9246. or written-to ($W$) by an instruction need to be updated to handle the
  9247. new kinds of arguments and instructions in \LangXIfVar{}.
  9248. \begin{exercise}\normalfont\normalsize
  9249. {\if\edition\racketEd
  9250. %
  9251. Update the \code{uncover\_live} pass to apply liveness analysis to
  9252. every basic block in the program.
  9253. %
  9254. Add the following entry to the list of \code{passes} in the
  9255. \code{run-tests.rkt} script:
  9256. \begin{lstlisting}
  9257. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9258. \end{lstlisting}
  9259. \fi}
  9260. {\if\edition\pythonEd\pythonColor
  9261. %
  9262. Update the \code{uncover\_live} function to perform liveness analysis,
  9263. in reverse topological order, on all the basic blocks in the
  9264. program.
  9265. %
  9266. \fi}
  9267. % Check that the live-after sets that you generate for
  9268. % example X matches the following... -Jeremy
  9269. \end{exercise}
  9270. \subsection{Build the Interference Graph}
  9271. \label{sec:build-interference-Lif}
  9272. Many of the new instructions in \LangXIfVar{} can be handled in the
  9273. same way as the instructions in \LangXVar{}.
  9274. % Thus, if your code was
  9275. % already quite general, it will not need to be changed to handle the
  9276. % new instructions. If your code is not general enough, we recommend that
  9277. % you change your code to be more general. For example, you can factor
  9278. % out the computing of the the read and write sets for each kind of
  9279. % instruction into auxiliary functions.
  9280. %
  9281. Some instructions, such as the \key{movzbq} instruction, require special care,
  9282. similar to the \key{movq} instruction. Refer to rule number 1 in
  9283. section~\ref{sec:build-interference}.
  9284. \begin{exercise}\normalfont\normalsize
  9285. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9286. {\if\edition\racketEd
  9287. Add the following entries to the list of \code{passes} in the
  9288. \code{run-tests.rkt} script:
  9289. \begin{lstlisting}
  9290. (list "build_interference" build_interference interp-pseudo-x86-1)
  9291. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9292. \end{lstlisting}
  9293. \fi}
  9294. % Check that the interference graph that you generate for
  9295. % example X matches the following graph G... -Jeremy
  9296. \end{exercise}
  9297. \section{Patch Instructions}
  9298. The new instructions \key{cmpq} and \key{movzbq} have some special
  9299. restrictions that need to be handled in the \code{patch\_instructions}
  9300. pass.
  9301. %
  9302. The second argument of the \key{cmpq} instruction must not be an
  9303. immediate value (such as an integer). So, if you are comparing two
  9304. immediates, we recommend inserting a \key{movq} instruction to put the
  9305. second argument in \key{rax}. On the other hand, if you implemented
  9306. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9307. update it for \LangIf{} and then this situation would not arise.
  9308. %
  9309. As usual, \key{cmpq} may have at most one memory reference.
  9310. %
  9311. The second argument of the \key{movzbq} must be a register.
  9312. \begin{exercise}\normalfont\normalsize
  9313. %
  9314. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9315. %
  9316. {\if\edition\racketEd
  9317. Add the following entry to the list of \code{passes} in
  9318. \code{run-tests.rkt}, and then run this script to test your compiler.
  9319. \begin{lstlisting}
  9320. (list "patch_instructions" patch_instructions interp-x86-1)
  9321. \end{lstlisting}
  9322. \fi}
  9323. \end{exercise}
  9324. {\if\edition\pythonEd\pythonColor
  9325. \section{Generate Prelude and Conclusion}
  9326. \label{sec:prelude-conclusion-cond}
  9327. The generation of the \code{main} function with its prelude and
  9328. conclusion must change to accommodate how the program now consists of
  9329. one or more basic blocks. After the prelude in \code{main}, jump to
  9330. the \code{start} block. Place the conclusion in a basic block labeled
  9331. with \code{conclusion}.
  9332. \fi}
  9333. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9334. \LangIf{} translated to x86, showing the results of
  9335. \code{explicate\_control}, \code{select\_instructions}, and the final
  9336. x86 assembly.
  9337. \begin{figure}[tbp]
  9338. \begin{tcolorbox}[colback=white]
  9339. {\if\edition\racketEd
  9340. \begin{tabular}{lll}
  9341. \begin{minipage}{0.4\textwidth}
  9342. % cond_test_20.rkt, eq_input.py
  9343. \begin{lstlisting}
  9344. (if (eq? (read) 1) 42 0)
  9345. \end{lstlisting}
  9346. $\Downarrow$
  9347. \begin{lstlisting}
  9348. start:
  9349. tmp7951 = (read);
  9350. if (eq? tmp7951 1)
  9351. goto block7952;
  9352. else
  9353. goto block7953;
  9354. block7952:
  9355. return 42;
  9356. block7953:
  9357. return 0;
  9358. \end{lstlisting}
  9359. $\Downarrow$
  9360. \begin{lstlisting}
  9361. start:
  9362. callq read_int
  9363. movq %rax, tmp7951
  9364. cmpq $1, tmp7951
  9365. je block7952
  9366. jmp block7953
  9367. block7953:
  9368. movq $0, %rax
  9369. jmp conclusion
  9370. block7952:
  9371. movq $42, %rax
  9372. jmp conclusion
  9373. \end{lstlisting}
  9374. \end{minipage}
  9375. &
  9376. $\Rightarrow\qquad$
  9377. \begin{minipage}{0.4\textwidth}
  9378. \begin{lstlisting}
  9379. start:
  9380. callq read_int
  9381. movq %rax, %rcx
  9382. cmpq $1, %rcx
  9383. je block7952
  9384. jmp block7953
  9385. block7953:
  9386. movq $0, %rax
  9387. jmp conclusion
  9388. block7952:
  9389. movq $42, %rax
  9390. jmp conclusion
  9391. .globl main
  9392. main:
  9393. pushq %rbp
  9394. movq %rsp, %rbp
  9395. pushq %r13
  9396. pushq %r12
  9397. pushq %rbx
  9398. pushq %r14
  9399. subq $0, %rsp
  9400. jmp start
  9401. conclusion:
  9402. addq $0, %rsp
  9403. popq %r14
  9404. popq %rbx
  9405. popq %r12
  9406. popq %r13
  9407. popq %rbp
  9408. retq
  9409. \end{lstlisting}
  9410. \end{minipage}
  9411. \end{tabular}
  9412. \fi}
  9413. {\if\edition\pythonEd\pythonColor
  9414. \begin{tabular}{lll}
  9415. \begin{minipage}{0.4\textwidth}
  9416. % cond_test_20.rkt, eq_input.py
  9417. \begin{lstlisting}
  9418. print(42 if input_int() == 1 else 0)
  9419. \end{lstlisting}
  9420. $\Downarrow$
  9421. \begin{lstlisting}
  9422. start:
  9423. tmp_0 = input_int()
  9424. if tmp_0 == 1:
  9425. goto block_3
  9426. else:
  9427. goto block_4
  9428. block_3:
  9429. tmp_1 = 42
  9430. goto block_2
  9431. block_4:
  9432. tmp_1 = 0
  9433. goto block_2
  9434. block_2:
  9435. print(tmp_1)
  9436. return 0
  9437. \end{lstlisting}
  9438. $\Downarrow$
  9439. \begin{lstlisting}
  9440. start:
  9441. callq read_int
  9442. movq %rax, tmp_0
  9443. cmpq 1, tmp_0
  9444. je block_3
  9445. jmp block_4
  9446. block_3:
  9447. movq 42, tmp_1
  9448. jmp block_2
  9449. block_4:
  9450. movq 0, tmp_1
  9451. jmp block_2
  9452. block_2:
  9453. movq tmp_1, %rdi
  9454. callq print_int
  9455. movq 0, %rax
  9456. jmp conclusion
  9457. \end{lstlisting}
  9458. \end{minipage}
  9459. &
  9460. $\Rightarrow\qquad$
  9461. \begin{minipage}{0.4\textwidth}
  9462. \begin{lstlisting}
  9463. .globl main
  9464. main:
  9465. pushq %rbp
  9466. movq %rsp, %rbp
  9467. subq $0, %rsp
  9468. jmp start
  9469. start:
  9470. callq read_int
  9471. movq %rax, %rcx
  9472. cmpq $1, %rcx
  9473. je block_3
  9474. jmp block_4
  9475. block_3:
  9476. movq $42, %rcx
  9477. jmp block_2
  9478. block_4:
  9479. movq $0, %rcx
  9480. jmp block_2
  9481. block_2:
  9482. movq %rcx, %rdi
  9483. callq print_int
  9484. movq $0, %rax
  9485. jmp conclusion
  9486. conclusion:
  9487. addq $0, %rsp
  9488. popq %rbp
  9489. retq
  9490. \end{lstlisting}
  9491. \end{minipage}
  9492. \end{tabular}
  9493. \fi}
  9494. \end{tcolorbox}
  9495. \caption{Example compilation of an \key{if} expression to x86, showing
  9496. the results of \code{explicate\_control},
  9497. \code{select\_instructions}, and the final x86 assembly code. }
  9498. \label{fig:if-example-x86}
  9499. \end{figure}
  9500. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9501. compilation of \LangIf{}.
  9502. \begin{figure}[htbp]
  9503. \begin{tcolorbox}[colback=white]
  9504. {\if\edition\racketEd
  9505. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9506. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9507. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9508. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9509. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9510. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9511. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9512. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9513. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9514. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9515. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9516. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9517. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9518. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9519. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9520. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9521. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9522. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9523. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9524. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9525. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9526. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9527. \end{tikzpicture}
  9528. \fi}
  9529. {\if\edition\pythonEd\pythonColor
  9530. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9531. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9532. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9533. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9534. \node (C-1) at (0,0) {\large \LangCIf{}};
  9535. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9536. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9537. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9538. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9539. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9540. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9541. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9542. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9543. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9544. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9545. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9546. \end{tikzpicture}
  9547. \fi}
  9548. \end{tcolorbox}
  9549. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9550. \label{fig:Lif-passes}
  9551. \end{figure}
  9552. \section{Challenge: Optimize Blocks and Remove Jumps}
  9553. \label{sec:opt-jumps}
  9554. We discuss two challenges that involve optimizing the control-flow of
  9555. the program.
  9556. \subsection{Optimize Blocks}
  9557. The algorithm for \code{explicate\_control} that we discussed in
  9558. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9559. blocks. It creates a block whenever a continuation \emph{might} get
  9560. used more than once (for example, whenever the \code{cont} parameter
  9561. is passed into two or more recursive calls). However, some
  9562. continuation arguments may not be used at all. Consider the case for
  9563. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9564. the \code{els} continuation.
  9565. %
  9566. {\if\edition\racketEd
  9567. The following example program falls into this
  9568. case, and it creates two unused blocks.
  9569. \begin{center}
  9570. \begin{tabular}{lll}
  9571. \begin{minipage}{0.4\textwidth}
  9572. % cond_test_82.rkt
  9573. \begin{lstlisting}
  9574. (let ([y (if #t
  9575. (read)
  9576. (if (eq? (read) 0)
  9577. 777
  9578. (let ([x (read)])
  9579. (+ 1 x))))])
  9580. (+ y 2))
  9581. \end{lstlisting}
  9582. \end{minipage}
  9583. &
  9584. $\Rightarrow$
  9585. &
  9586. \begin{minipage}{0.4\textwidth}
  9587. \begin{lstlisting}
  9588. start:
  9589. y = (read);
  9590. goto block_5;
  9591. block_5:
  9592. return (+ y 2);
  9593. block_6:
  9594. y = 777;
  9595. goto block_5;
  9596. block_7:
  9597. x = (read);
  9598. y = (+ 1 x2);
  9599. goto block_5;
  9600. \end{lstlisting}
  9601. \end{minipage}
  9602. \end{tabular}
  9603. \end{center}
  9604. \fi}
  9605. {\if\edition\pythonEd
  9606. The following example program falls into this
  9607. case, and it creates the unused \code{block\_9}.
  9608. \begin{center}
  9609. \begin{minipage}{0.4\textwidth}
  9610. % if/if_true.py
  9611. \begin{lstlisting}
  9612. if True:
  9613. print(0)
  9614. else:
  9615. x = 1 if False else 2
  9616. print(x)
  9617. \end{lstlisting}
  9618. \end{minipage}
  9619. $\Rightarrow\qquad\qquad$
  9620. \begin{minipage}{0.4\textwidth}
  9621. \begin{lstlisting}
  9622. start:
  9623. print(0)
  9624. goto block_8
  9625. block_9:
  9626. print(x)
  9627. goto block_8
  9628. block_8:
  9629. return 0
  9630. \end{lstlisting}
  9631. \end{minipage}
  9632. \end{center}
  9633. \fi}
  9634. The question is, how can we decide whether to create a basic block?
  9635. \emph{Lazy evaluation}\index{subject}{lazy
  9636. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9637. delaying the creation of a basic block until the point in time at which
  9638. we know that it will be used.
  9639. %
  9640. {\if\edition\racketEd
  9641. %
  9642. Racket provides support for
  9643. lazy evaluation with the
  9644. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9645. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9646. \index{subject}{delay} creates a
  9647. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9648. expressions is postponed. When \key{(force}
  9649. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9650. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9651. result of $e_n$ is cached in the promise and returned. If \code{force}
  9652. is applied again to the same promise, then the cached result is
  9653. returned. If \code{force} is applied to an argument that is not a
  9654. promise, \code{force} simply returns the argument.
  9655. %
  9656. \fi}
  9657. %
  9658. {\if\edition\pythonEd\pythonColor
  9659. %
  9660. Although Python does not provide direct support for lazy evaluation,
  9661. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9662. by wrapping it inside a function with no parameters. We \emph{force}
  9663. its evaluation by calling the function. However, we might need to
  9664. force multiple times, so we store the result of calling the
  9665. function instead of recomputing it each time. The following
  9666. \code{Promise} class handles this memoization process.
  9667. \begin{minipage}{0.8\textwidth}
  9668. \begin{lstlisting}
  9669. @dataclass
  9670. class Promise:
  9671. fun : typing.Any
  9672. cache : list[stmt] = None
  9673. def force(self):
  9674. if self.cache is None:
  9675. self.cache = self.fun(); return self.cache
  9676. else:
  9677. return self.cache
  9678. \end{lstlisting}
  9679. \end{minipage}
  9680. \noindent However, in some cases of \code{explicate\_pred}, we return
  9681. a list of statements, and in other cases we return a function that
  9682. computes a list of statements. To uniformly deal with both regular
  9683. data and promises, we define the following \code{force} function that
  9684. checks whether its input is delayed (i.e., whether it is a
  9685. \code{Promise}) and then either (1) forces the promise or (2) returns
  9686. the input.
  9687. %
  9688. \begin{lstlisting}
  9689. def force(promise):
  9690. if isinstance(promise, Promise):
  9691. return promise.force()
  9692. else:
  9693. return promise
  9694. \end{lstlisting}
  9695. %
  9696. \fi}
  9697. We use promises for the input and output of the functions
  9698. \code{explicate\_pred}, \code{explicate\_assign},
  9699. %
  9700. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9701. %
  9702. So, instead of taking and returning \racket{$\Tail$
  9703. expressions}\python{lists of statements}, they take and return
  9704. promises. Furthermore, when we come to a situation in which a
  9705. continuation might be used more than once, as in the case for
  9706. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9707. that creates a basic block for each continuation (if there is not
  9708. already one) and then returns a \code{goto} statement to that basic
  9709. block. When we come to a situation in which we have a promise but need an
  9710. actual piece of code, for example, to create a larger piece of code with a
  9711. constructor such as \code{Seq}, then insert a call to \code{force}.
  9712. %
  9713. {\if\edition\racketEd
  9714. %
  9715. Also, we must modify the \code{create\_block} function to begin with
  9716. \code{delay} to create a promise. When forced, this promise forces the
  9717. original promise. If that returns a \code{Goto} (because the block was
  9718. already added to \code{basic-blocks}), then we return the
  9719. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9720. return a \code{Goto} to the new label.
  9721. \begin{center}
  9722. \begin{minipage}{\textwidth}
  9723. \begin{lstlisting}
  9724. (define (create_block tail)
  9725. (delay
  9726. (define t (force tail))
  9727. (match t
  9728. [(Goto label) (Goto label)]
  9729. [else
  9730. (let ([label (gensym 'block)])
  9731. (set! basic-blocks (cons (cons label t) basic-blocks))
  9732. (Goto label))])))
  9733. \end{lstlisting}
  9734. \end{minipage}
  9735. \end{center}
  9736. \fi}
  9737. {\if\edition\pythonEd\pythonColor
  9738. %
  9739. Here is the new version of the \code{create\_block} auxiliary function
  9740. that delays the creation of the new basic block.\\
  9741. \begin{minipage}{\textwidth}
  9742. \begin{lstlisting}
  9743. def create_block(promise, basic_blocks):
  9744. def delay():
  9745. stmts = force(promise)
  9746. match stmts:
  9747. case [Goto(l)]:
  9748. return [Goto(l)]
  9749. case _:
  9750. label = label_name(generate_name('block'))
  9751. basic_blocks[label] = stmts
  9752. return [Goto(label)]
  9753. return Promise(delay)
  9754. \end{lstlisting}
  9755. \end{minipage}
  9756. \fi}
  9757. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9758. improved \code{explicate\_control} on this example.
  9759. \racket{As you can see, the number of basic blocks has been reduced
  9760. from four blocks to two blocks.}%
  9761. \python{As you can see, the number of basic blocks has been reduced
  9762. from three blocks to two blocks.}
  9763. \begin{figure}[tbp]
  9764. \begin{tcolorbox}[colback=white]
  9765. {\if\edition\racketEd
  9766. \begin{tabular}{lll}
  9767. \begin{minipage}{0.45\textwidth}
  9768. % cond_test_82.rkt
  9769. \begin{lstlisting}
  9770. (let ([y (if #t
  9771. (read)
  9772. (if (eq? (read) 0)
  9773. 777
  9774. (let ([x (read)])
  9775. (+ 1 x))))])
  9776. (+ y 2))
  9777. \end{lstlisting}
  9778. \end{minipage}
  9779. &
  9780. $\quad\Rightarrow\quad$
  9781. &
  9782. \begin{minipage}{0.4\textwidth}
  9783. \begin{lstlisting}
  9784. start:
  9785. y = (read);
  9786. goto block_5;
  9787. block_5:
  9788. return (+ y 2);
  9789. \end{lstlisting}
  9790. \end{minipage}
  9791. \end{tabular}
  9792. \fi}
  9793. {\if\edition\pythonEd\pythonColor
  9794. \begin{tabular}{lll}
  9795. \begin{minipage}{0.4\textwidth}
  9796. % if/if_true.py
  9797. \begin{lstlisting}
  9798. if True:
  9799. print(0)
  9800. else:
  9801. x = 1 if False else 2
  9802. print(x)
  9803. \end{lstlisting}
  9804. \end{minipage}
  9805. &
  9806. $\Rightarrow$
  9807. &
  9808. \begin{minipage}{0.55\textwidth}
  9809. \begin{lstlisting}
  9810. start:
  9811. print(0)
  9812. goto block_4
  9813. block_4:
  9814. return 0
  9815. \end{lstlisting}
  9816. \end{minipage}
  9817. \end{tabular}
  9818. \fi}
  9819. \end{tcolorbox}
  9820. \caption{Translation from \LangIf{} to \LangCIf{}
  9821. via the improved \code{explicate\_control}.}
  9822. \label{fig:explicate-control-challenge}
  9823. \end{figure}
  9824. %% Recall that in the example output of \code{explicate\_control} in
  9825. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9826. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9827. %% block. The first goal of this challenge assignment is to remove those
  9828. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9829. %% \code{explicate\_control} on the left and shows the result of bypassing
  9830. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9831. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9832. %% \code{block55}. The optimized code on the right of
  9833. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9834. %% \code{then} branch jumping directly to \code{block55}. The story is
  9835. %% similar for the \code{else} branch, as well as for the two branches in
  9836. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9837. %% have been optimized in this way, there are no longer any jumps to
  9838. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9839. %% \begin{figure}[tbp]
  9840. %% \begin{tabular}{lll}
  9841. %% \begin{minipage}{0.4\textwidth}
  9842. %% \begin{lstlisting}
  9843. %% block62:
  9844. %% tmp54 = (read);
  9845. %% if (eq? tmp54 2) then
  9846. %% goto block59;
  9847. %% else
  9848. %% goto block60;
  9849. %% block61:
  9850. %% tmp53 = (read);
  9851. %% if (eq? tmp53 0) then
  9852. %% goto block57;
  9853. %% else
  9854. %% goto block58;
  9855. %% block60:
  9856. %% goto block56;
  9857. %% block59:
  9858. %% goto block55;
  9859. %% block58:
  9860. %% goto block56;
  9861. %% block57:
  9862. %% goto block55;
  9863. %% block56:
  9864. %% return (+ 700 77);
  9865. %% block55:
  9866. %% return (+ 10 32);
  9867. %% start:
  9868. %% tmp52 = (read);
  9869. %% if (eq? tmp52 1) then
  9870. %% goto block61;
  9871. %% else
  9872. %% goto block62;
  9873. %% \end{lstlisting}
  9874. %% \end{minipage}
  9875. %% &
  9876. %% $\Rightarrow$
  9877. %% &
  9878. %% \begin{minipage}{0.55\textwidth}
  9879. %% \begin{lstlisting}
  9880. %% block62:
  9881. %% tmp54 = (read);
  9882. %% if (eq? tmp54 2) then
  9883. %% goto block55;
  9884. %% else
  9885. %% goto block56;
  9886. %% block61:
  9887. %% tmp53 = (read);
  9888. %% if (eq? tmp53 0) then
  9889. %% goto block55;
  9890. %% else
  9891. %% goto block56;
  9892. %% block56:
  9893. %% return (+ 700 77);
  9894. %% block55:
  9895. %% return (+ 10 32);
  9896. %% start:
  9897. %% tmp52 = (read);
  9898. %% if (eq? tmp52 1) then
  9899. %% goto block61;
  9900. %% else
  9901. %% goto block62;
  9902. %% \end{lstlisting}
  9903. %% \end{minipage}
  9904. %% \end{tabular}
  9905. %% \caption{Optimize jumps by removing trivial blocks.}
  9906. %% \label{fig:optimize-jumps}
  9907. %% \end{figure}
  9908. %% The name of this pass is \code{optimize-jumps}. We recommend
  9909. %% implementing this pass in two phases. The first phrase builds a hash
  9910. %% table that maps labels to possibly improved labels. The second phase
  9911. %% changes the target of each \code{goto} to use the improved label. If
  9912. %% the label is for a trivial block, then the hash table should map the
  9913. %% label to the first non-trivial block that can be reached from this
  9914. %% label by jumping through trivial blocks. If the label is for a
  9915. %% non-trivial block, then the hash table should map the label to itself;
  9916. %% we do not want to change jumps to non-trivial blocks.
  9917. %% The first phase can be accomplished by constructing an empty hash
  9918. %% table, call it \code{short-cut}, and then iterating over the control
  9919. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9920. %% then update the hash table, mapping the block's source to the target
  9921. %% of the \code{goto}. Also, the hash table may already have mapped some
  9922. %% labels to the block's source, to you must iterate through the hash
  9923. %% table and update all of those so that they instead map to the target
  9924. %% of the \code{goto}.
  9925. %% For the second phase, we recommend iterating through the $\Tail$ of
  9926. %% each block in the program, updating the target of every \code{goto}
  9927. %% according to the mapping in \code{short-cut}.
  9928. \begin{exercise}\normalfont\normalsize
  9929. Implement the improvements to the \code{explicate\_control} pass.
  9930. Check that it removes trivial blocks in a few example programs. Then
  9931. check that your compiler still passes all your tests.
  9932. \end{exercise}
  9933. \subsection{Remove Jumps}
  9934. There is an opportunity for removing jumps that is apparent in the
  9935. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9936. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9937. and there are no other jumps to
  9938. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9939. In this situation we can avoid the runtime overhead of this jump by merging
  9940. \racket{\code{block\_5}}\python{\code{block\_4}}
  9941. into the preceding block, which in this case is the \code{start} block.
  9942. Figure~\ref{fig:remove-jumps} shows the output of
  9943. \code{allocate\_registers} on the left and the result of this
  9944. optimization on the right.
  9945. \begin{figure}[tbp]
  9946. \begin{tcolorbox}[colback=white]
  9947. {\if\edition\racketEd
  9948. \begin{tabular}{lll}
  9949. \begin{minipage}{0.5\textwidth}
  9950. % cond_test_82.rkt
  9951. \begin{lstlisting}
  9952. start:
  9953. callq read_int
  9954. movq %rax, %rcx
  9955. jmp block_5
  9956. block_5:
  9957. movq %rcx, %rax
  9958. addq $2, %rax
  9959. jmp conclusion
  9960. \end{lstlisting}
  9961. \end{minipage}
  9962. &
  9963. $\Rightarrow\qquad$
  9964. \begin{minipage}{0.4\textwidth}
  9965. \begin{lstlisting}
  9966. start:
  9967. callq read_int
  9968. movq %rax, %rcx
  9969. movq %rcx, %rax
  9970. addq $2, %rax
  9971. jmp conclusion
  9972. \end{lstlisting}
  9973. \end{minipage}
  9974. \end{tabular}
  9975. \fi}
  9976. {\if\edition\pythonEd\pythonColor
  9977. \begin{tabular}{lll}
  9978. \begin{minipage}{0.5\textwidth}
  9979. % cond_test_20.rkt
  9980. \begin{lstlisting}
  9981. start:
  9982. callq read_int
  9983. movq %rax, tmp_0
  9984. cmpq 1, tmp_0
  9985. je block_3
  9986. jmp block_4
  9987. block_3:
  9988. movq 42, tmp_1
  9989. jmp block_2
  9990. block_4:
  9991. movq 0, tmp_1
  9992. jmp block_2
  9993. block_2:
  9994. movq tmp_1, %rdi
  9995. callq print_int
  9996. movq 0, %rax
  9997. jmp conclusion
  9998. \end{lstlisting}
  9999. \end{minipage}
  10000. &
  10001. $\Rightarrow\qquad$
  10002. \begin{minipage}{0.4\textwidth}
  10003. \begin{lstlisting}
  10004. start:
  10005. callq read_int
  10006. movq %rax, tmp_0
  10007. cmpq 1, tmp_0
  10008. je block_3
  10009. movq 0, tmp_1
  10010. jmp block_2
  10011. block_3:
  10012. movq 42, tmp_1
  10013. jmp block_2
  10014. block_2:
  10015. movq tmp_1, %rdi
  10016. callq print_int
  10017. movq 0, %rax
  10018. jmp conclusion
  10019. \end{lstlisting}
  10020. \end{minipage}
  10021. \end{tabular}
  10022. \fi}
  10023. \end{tcolorbox}
  10024. \caption{Merging basic blocks by removing unnecessary jumps.}
  10025. \label{fig:remove-jumps}
  10026. \end{figure}
  10027. \begin{exercise}\normalfont\normalsize
  10028. %
  10029. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10030. into their preceding basic block, when there is only one preceding
  10031. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10032. %
  10033. {\if\edition\racketEd
  10034. In the \code{run-tests.rkt} script, add the following entry to the
  10035. list of \code{passes} between \code{allocate\_registers}
  10036. and \code{patch\_instructions}:
  10037. \begin{lstlisting}
  10038. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10039. \end{lstlisting}
  10040. \fi}
  10041. %
  10042. Run the script to test your compiler.
  10043. %
  10044. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10045. blocks on several test programs.
  10046. \end{exercise}
  10047. \section{Further Reading}
  10048. \label{sec:cond-further-reading}
  10049. The algorithm for \code{explicate\_control} is based on the
  10050. \code{expose-basic-blocks} pass in the course notes of
  10051. \citet{Dybvig:2010aa}.
  10052. %
  10053. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10054. \citet{Appel:2003fk}, and is related to translations into continuation
  10055. passing
  10056. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10057. %
  10058. The treatment of conditionals in the \code{explicate\_control} pass is
  10059. similar to short-cut Boolean
  10060. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10061. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10062. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10063. \chapter{Loops and Dataflow Analysis}
  10064. \label{ch:Lwhile}
  10065. \setcounter{footnote}{0}
  10066. % TODO: define R'_8
  10067. % TODO: multi-graph
  10068. {\if\edition\racketEd
  10069. %
  10070. In this chapter we study two features that are the hallmarks of
  10071. imperative programming languages: loops and assignments to local
  10072. variables. The following example demonstrates these new features by
  10073. computing the sum of the first five positive integers:
  10074. % similar to loop_test_1.rkt
  10075. \begin{lstlisting}
  10076. (let ([sum 0])
  10077. (let ([i 5])
  10078. (begin
  10079. (while (> i 0)
  10080. (begin
  10081. (set! sum (+ sum i))
  10082. (set! i (- i 1))))
  10083. sum)))
  10084. \end{lstlisting}
  10085. The \code{while} loop consists of a condition and a
  10086. body.\footnote{The \code{while} loop is not a built-in
  10087. feature of the Racket language, but Racket includes many looping
  10088. constructs and it is straightforward to define \code{while} as a
  10089. macro.} The body is evaluated repeatedly so long as the condition
  10090. remains true.
  10091. %
  10092. The \code{set!} consists of a variable and a right-hand side
  10093. expression. The \code{set!} updates value of the variable to the
  10094. value of the right-hand side.
  10095. %
  10096. The primary purpose of both the \code{while} loop and \code{set!} is
  10097. to cause side effects, so they do not give a meaningful result
  10098. value. Instead, their result is the \code{\#<void>} value. The
  10099. expression \code{(void)} is an explicit way to create the
  10100. \code{\#<void>} value, and it has type \code{Void}. The
  10101. \code{\#<void>} value can be passed around just like other values
  10102. inside an \LangLoop{} program, and it can be compared for equality with
  10103. another \code{\#<void>} value. However, there are no other operations
  10104. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10105. Racket defines the \code{void?} predicate that returns \code{\#t}
  10106. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10107. %
  10108. \footnote{Racket's \code{Void} type corresponds to what is often
  10109. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10110. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10111. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10112. %
  10113. With the addition of side effect-producing features such as
  10114. \code{while} loop and \code{set!}, it is helpful to include a language
  10115. feature for sequencing side effects: the \code{begin} expression. It
  10116. consists of one or more subexpressions that are evaluated
  10117. left to right.
  10118. %
  10119. \fi}
  10120. {\if\edition\pythonEd\pythonColor
  10121. %
  10122. In this chapter we study loops, one of the hallmarks of imperative
  10123. programming languages. The following example demonstrates the
  10124. \code{while} loop by computing the sum of the first five positive
  10125. integers.
  10126. \begin{lstlisting}
  10127. sum = 0
  10128. i = 5
  10129. while i > 0:
  10130. sum = sum + i
  10131. i = i - 1
  10132. print(sum)
  10133. \end{lstlisting}
  10134. The \code{while} loop consists of a condition and a body (a sequence
  10135. of statements). The body is evaluated repeatedly so long as the
  10136. condition remains true.
  10137. %
  10138. \fi}
  10139. \section{The \LangLoop{} Language}
  10140. \newcommand{\LwhileGrammarRacket}{
  10141. \begin{array}{lcl}
  10142. \Type &::=& \key{Void}\\
  10143. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10144. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10145. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10146. \end{array}
  10147. }
  10148. \newcommand{\LwhileASTRacket}{
  10149. \begin{array}{lcl}
  10150. \Type &::=& \key{Void}\\
  10151. \Exp &::=& \SETBANG{\Var}{\Exp}
  10152. \MID \BEGIN{\Exp^{*}}{\Exp}
  10153. \MID \WHILE{\Exp}{\Exp}
  10154. \MID \VOID{}
  10155. \end{array}
  10156. }
  10157. \newcommand{\LwhileGrammarPython}{
  10158. \begin{array}{rcl}
  10159. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10160. \end{array}
  10161. }
  10162. \newcommand{\LwhileASTPython}{
  10163. \begin{array}{lcl}
  10164. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10165. \end{array}
  10166. }
  10167. \begin{figure}[tp]
  10168. \centering
  10169. \begin{tcolorbox}[colback=white]
  10170. \small
  10171. {\if\edition\racketEd
  10172. \[
  10173. \begin{array}{l}
  10174. \gray{\LintGrammarRacket{}} \\ \hline
  10175. \gray{\LvarGrammarRacket{}} \\ \hline
  10176. \gray{\LifGrammarRacket{}} \\ \hline
  10177. \LwhileGrammarRacket \\
  10178. \begin{array}{lcl}
  10179. \LangLoopM{} &::=& \Exp
  10180. \end{array}
  10181. \end{array}
  10182. \]
  10183. \fi}
  10184. {\if\edition\pythonEd\pythonColor
  10185. \[
  10186. \begin{array}{l}
  10187. \gray{\LintGrammarPython} \\ \hline
  10188. \gray{\LvarGrammarPython} \\ \hline
  10189. \gray{\LifGrammarPython} \\ \hline
  10190. \LwhileGrammarPython \\
  10191. \begin{array}{rcl}
  10192. \LangLoopM{} &::=& \Stmt^{*}
  10193. \end{array}
  10194. \end{array}
  10195. \]
  10196. \fi}
  10197. \end{tcolorbox}
  10198. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10199. \label{fig:Lwhile-concrete-syntax}
  10200. \index{subject}{Lwhile@\LangLoop{} concrete syntax}
  10201. \end{figure}
  10202. \begin{figure}[tp]
  10203. \centering
  10204. \begin{tcolorbox}[colback=white]
  10205. \small
  10206. {\if\edition\racketEd
  10207. \[
  10208. \begin{array}{l}
  10209. \gray{\LintOpAST} \\ \hline
  10210. \gray{\LvarASTRacket{}} \\ \hline
  10211. \gray{\LifASTRacket{}} \\ \hline
  10212. \LwhileASTRacket{} \\
  10213. \begin{array}{lcl}
  10214. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10215. \end{array}
  10216. \end{array}
  10217. \]
  10218. \fi}
  10219. {\if\edition\pythonEd\pythonColor
  10220. \[
  10221. \begin{array}{l}
  10222. \gray{\LintASTPython} \\ \hline
  10223. \gray{\LvarASTPython} \\ \hline
  10224. \gray{\LifASTPython} \\ \hline
  10225. \LwhileASTPython \\
  10226. \begin{array}{lcl}
  10227. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10228. \end{array}
  10229. \end{array}
  10230. \]
  10231. \fi}
  10232. \end{tcolorbox}
  10233. \python{
  10234. \index{subject}{While@\texttt{While}}
  10235. }
  10236. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10237. \label{fig:Lwhile-syntax}
  10238. \index{subject}{Lwhile@\LangLoop{} abstract syntax}
  10239. \end{figure}
  10240. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10241. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10242. shows the definition of its abstract syntax.
  10243. %
  10244. The definitional interpreter for \LangLoop{} is shown in
  10245. figure~\ref{fig:interp-Lwhile}.
  10246. %
  10247. {\if\edition\racketEd
  10248. %
  10249. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10250. and \code{Void}, and we make changes to the cases for \code{Var} and
  10251. \code{Let} regarding variables. To support assignment to variables and
  10252. to make their lifetimes indefinite (see the second example in
  10253. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10254. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10255. value.
  10256. %
  10257. Now we discuss the new cases. For \code{SetBang}, we find the
  10258. variable in the environment to obtain a boxed value, and then we change
  10259. it using \code{set-box!} to the result of evaluating the right-hand
  10260. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10261. %
  10262. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10263. if the result is true, (2) evaluate the body.
  10264. The result value of a \code{while} loop is also \code{\#<void>}.
  10265. %
  10266. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10267. subexpressions \itm{es} for their effects and then evaluates
  10268. and returns the result from \itm{body}.
  10269. %
  10270. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10271. %
  10272. \fi}
  10273. {\if\edition\pythonEd\pythonColor
  10274. %
  10275. We add a new case for \code{While} in the \code{interp\_stmts}
  10276. function, in which we repeatedly interpret the \code{body} so long as the
  10277. \code{test} expression remains true.
  10278. %
  10279. \fi}
  10280. \begin{figure}[tbp]
  10281. \begin{tcolorbox}[colback=white]
  10282. {\if\edition\racketEd
  10283. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10284. (define interp-Lwhile-class
  10285. (class interp-Lif-class
  10286. (super-new)
  10287. (define/override ((interp-exp env) e)
  10288. (define recur (interp-exp env))
  10289. (match e
  10290. [(Let x e body)
  10291. (define new-env (dict-set env x (box (recur e))))
  10292. ((interp-exp new-env) body)]
  10293. [(Var x) (unbox (dict-ref env x))]
  10294. [(SetBang x rhs)
  10295. (set-box! (dict-ref env x) (recur rhs))]
  10296. [(WhileLoop cnd body)
  10297. (define (loop)
  10298. (cond [(recur cnd) (recur body) (loop)]
  10299. [else (void)]))
  10300. (loop)]
  10301. [(Begin es body)
  10302. (for ([e es]) (recur e))
  10303. (recur body)]
  10304. [(Void) (void)]
  10305. [else ((super interp-exp env) e)]))
  10306. ))
  10307. (define (interp-Lwhile p)
  10308. (send (new interp-Lwhile-class) interp-program p))
  10309. \end{lstlisting}
  10310. \fi}
  10311. {\if\edition\pythonEd\pythonColor
  10312. \begin{lstlisting}
  10313. class InterpLwhile(InterpLif):
  10314. def interp_stmt(self, s, env, cont):
  10315. match s:
  10316. case While(test, body, []):
  10317. if self.interp_exp(test, env):
  10318. self.interp_stmts(body + [s] + cont, env)
  10319. else:
  10320. return self.interp_stmts(cont, env)
  10321. case _:
  10322. return super().interp_stmt(s, env, cont)
  10323. \end{lstlisting}
  10324. \fi}
  10325. \end{tcolorbox}
  10326. \caption{Interpreter for \LangLoop{}.}
  10327. \label{fig:interp-Lwhile}
  10328. \end{figure}
  10329. The definition of the type checker for \LangLoop{} is shown in
  10330. figure~\ref{fig:type-check-Lwhile}.
  10331. %
  10332. {\if\edition\racketEd
  10333. %
  10334. The type checking of the \code{SetBang} expression requires the type
  10335. of the variable and the right-hand side to agree. The result type is
  10336. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10337. and the result type is \code{Void}. For \code{Begin}, the result type
  10338. is the type of its last subexpression.
  10339. %
  10340. \fi}
  10341. %
  10342. {\if\edition\pythonEd\pythonColor
  10343. %
  10344. A \code{while} loop is well typed if the type of the \code{test}
  10345. expression is \code{bool} and the statements in the \code{body} are
  10346. well typed.
  10347. %
  10348. \fi}
  10349. \begin{figure}[tbp]
  10350. \begin{tcolorbox}[colback=white]
  10351. {\if\edition\racketEd
  10352. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10353. (define type-check-Lwhile-class
  10354. (class type-check-Lif-class
  10355. (super-new)
  10356. (inherit check-type-equal?)
  10357. (define/override (type-check-exp env)
  10358. (lambda (e)
  10359. (define recur (type-check-exp env))
  10360. (match e
  10361. [(SetBang x rhs)
  10362. (define-values (rhs^ rhsT) (recur rhs))
  10363. (define varT (dict-ref env x))
  10364. (check-type-equal? rhsT varT e)
  10365. (values (SetBang x rhs^) 'Void)]
  10366. [(WhileLoop cnd body)
  10367. (define-values (cnd^ Tc) (recur cnd))
  10368. (check-type-equal? Tc 'Boolean e)
  10369. (define-values (body^ Tbody) ((type-check-exp env) body))
  10370. (values (WhileLoop cnd^ body^) 'Void)]
  10371. [(Begin es body)
  10372. (define-values (es^ ts)
  10373. (for/lists (l1 l2) ([e es]) (recur e)))
  10374. (define-values (body^ Tbody) (recur body))
  10375. (values (Begin es^ body^) Tbody)]
  10376. [else ((super type-check-exp env) e)])))
  10377. ))
  10378. (define (type-check-Lwhile p)
  10379. (send (new type-check-Lwhile-class) type-check-program p))
  10380. \end{lstlisting}
  10381. \fi}
  10382. {\if\edition\pythonEd\pythonColor
  10383. \begin{lstlisting}
  10384. class TypeCheckLwhile(TypeCheckLif):
  10385. def type_check_stmts(self, ss, env):
  10386. if len(ss) == 0:
  10387. return
  10388. match ss[0]:
  10389. case While(test, body, []):
  10390. test_t = self.type_check_exp(test, env)
  10391. check_type_equal(bool, test_t, test)
  10392. body_t = self.type_check_stmts(body, env)
  10393. return self.type_check_stmts(ss[1:], env)
  10394. case _:
  10395. return super().type_check_stmts(ss, env)
  10396. \end{lstlisting}
  10397. \fi}
  10398. \end{tcolorbox}
  10399. \caption{Type checker for the \LangLoop{} language.}
  10400. \label{fig:type-check-Lwhile}
  10401. \end{figure}
  10402. {\if\edition\racketEd
  10403. %
  10404. At first glance, the translation of these language features to x86
  10405. seems straightforward because the \LangCIf{} intermediate language
  10406. already supports all the ingredients that we need: assignment,
  10407. \code{goto}, conditional branching, and sequencing. However,
  10408. complications arise, which we discuss in the next section. After
  10409. that we introduce the changes necessary to the existing passes.
  10410. %
  10411. \fi}
  10412. {\if\edition\pythonEd\pythonColor
  10413. %
  10414. At first glance, the translation of \code{while} loops to x86 seems
  10415. straightforward because the \LangCIf{} intermediate language already
  10416. supports \code{goto} and conditional branching. However, there are
  10417. complications that arise, which we discuss in the next section. After
  10418. that we introduce the changes necessary to the existing passes.
  10419. %
  10420. \fi}
  10421. \section{Cyclic Control Flow and Dataflow Analysis}
  10422. \label{sec:dataflow-analysis}
  10423. Up until this point, the programs generated in
  10424. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10425. \code{while} loop introduces a cycle. Does that matter?
  10426. %
  10427. Indeed, it does. Recall that for register allocation, the compiler
  10428. performs liveness analysis to determine which variables can share the
  10429. same register. To accomplish this, we analyzed the control-flow graph
  10430. in reverse topological order
  10431. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10432. well defined only for acyclic graphs.
  10433. Let us return to the example of computing the sum of the first five
  10434. positive integers. Here is the program after instruction
  10435. selection\index{subject}{instruction selection} but before register
  10436. allocation.
  10437. \begin{center}
  10438. {\if\edition\racketEd
  10439. \begin{minipage}{0.45\textwidth}
  10440. \begin{lstlisting}
  10441. (define (main) : Integer
  10442. mainstart:
  10443. movq $0, sum
  10444. movq $5, i
  10445. jmp block5
  10446. block5:
  10447. movq i, tmp3
  10448. cmpq tmp3, $0
  10449. jl block7
  10450. jmp block8
  10451. \end{lstlisting}
  10452. \end{minipage}
  10453. \begin{minipage}{0.45\textwidth}
  10454. \begin{lstlisting}
  10455. block7:
  10456. addq i, sum
  10457. movq $1, tmp4
  10458. negq tmp4
  10459. addq tmp4, i
  10460. jmp block5
  10461. block8:
  10462. movq $27, %rax
  10463. addq sum, %rax
  10464. jmp mainconclusion)
  10465. \end{lstlisting}
  10466. \end{minipage}
  10467. \fi}
  10468. {\if\edition\pythonEd\pythonColor
  10469. \begin{minipage}{0.45\textwidth}
  10470. \begin{lstlisting}
  10471. mainstart:
  10472. movq $0, sum
  10473. movq $5, i
  10474. jmp block5
  10475. block5:
  10476. cmpq $0, i
  10477. jg block7
  10478. jmp block8
  10479. \end{lstlisting}
  10480. \end{minipage}
  10481. \begin{minipage}{0.45\textwidth}
  10482. \begin{lstlisting}
  10483. block7:
  10484. addq i, sum
  10485. subq $1, i
  10486. jmp block5
  10487. block8:
  10488. movq sum, %rdi
  10489. callq print_int
  10490. movq $0, %rax
  10491. jmp mainconclusion
  10492. \end{lstlisting}
  10493. \end{minipage}
  10494. \fi}
  10495. \end{center}
  10496. Recall that liveness analysis works backward, starting at the end
  10497. of each function. For this example we could start with \code{block8}
  10498. because we know what is live at the beginning of the conclusion:
  10499. only \code{rax} and \code{rsp}. So the live-before set
  10500. for \code{block8} is \code{\{rsp,sum\}}.
  10501. %
  10502. Next we might try to analyze \code{block5} or \code{block7}, but
  10503. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10504. we are stuck.
  10505. The way out of this impasse is to realize that we can compute an
  10506. underapproximation of each live-before set by starting with empty
  10507. live-after sets. By \emph{underapproximation}, we mean that the set
  10508. contains only variables that are live for some execution of the
  10509. program, but the set may be missing some variables that are live.
  10510. Next, the underapproximations for each block can be improved by (1)
  10511. updating the live-after set for each block using the approximate
  10512. live-before sets from the other blocks, and (2) performing liveness
  10513. analysis again on each block. In fact, by iterating this process, the
  10514. underapproximations eventually become the correct solutions!
  10515. %
  10516. This approach of iteratively analyzing a control-flow graph is
  10517. applicable to many static analysis problems and goes by the name
  10518. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10519. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10520. Washington.
  10521. Let us apply this approach to the previously presented example. We use
  10522. the empty set for the initial live-before set for each block. Let
  10523. $m_0$ be the following mapping from label names to sets of locations
  10524. (variables and registers):
  10525. \begin{center}
  10526. \begin{lstlisting}
  10527. mainstart: {}, block5: {}, block7: {}, block8: {}
  10528. \end{lstlisting}
  10529. \end{center}
  10530. Using the above live-before approximations, we determine the
  10531. live-after for each block and then apply liveness analysis to each
  10532. block. This produces our next approximation $m_1$ of the live-before
  10533. sets.
  10534. \begin{center}
  10535. \begin{lstlisting}
  10536. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10537. \end{lstlisting}
  10538. \end{center}
  10539. For the second round, the live-after for \code{mainstart} is the
  10540. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10541. the liveness analysis for \code{mainstart} computes the empty set. The
  10542. live-after for \code{block5} is the union of the live-before sets for
  10543. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10544. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10545. sum\}}. The live-after for \code{block7} is the live-before for
  10546. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10547. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10548. Together these yield the following approximation $m_2$ of
  10549. the live-before sets:
  10550. \begin{center}
  10551. \begin{lstlisting}
  10552. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10553. \end{lstlisting}
  10554. \end{center}
  10555. In the preceding iteration, only \code{block5} changed, so we can
  10556. limit our attention to \code{mainstart} and \code{block7}, the two
  10557. blocks that jump to \code{block5}. As a result, the live-before sets
  10558. for \code{mainstart} and \code{block7} are updated to include
  10559. \code{rsp}, yielding the following approximation $m_3$:
  10560. \begin{center}
  10561. \begin{lstlisting}
  10562. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10563. \end{lstlisting}
  10564. \end{center}
  10565. Because \code{block7} changed, we analyze \code{block5} once more, but
  10566. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10567. our approximations have converged, so $m_3$ is the solution.
  10568. This iteration process is guaranteed to converge to a solution by the
  10569. Kleene fixed-point theorem, a general theorem about functions on
  10570. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10571. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10572. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10573. join operator
  10574. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10575. will be working with join semilattices.} When two elements are
  10576. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10577. as much information as $m_i$, so we can think of $m_j$ as a
  10578. better-than-or-equal-to approximation in relation to $m_i$. The
  10579. bottom element $\bot$ represents the complete lack of information,
  10580. that is, the worst approximation. The join operator takes two lattice
  10581. elements and combines their information; that is, it produces the
  10582. least upper bound of the two.\index{subject}{least upper bound}
  10583. A dataflow analysis typically involves two lattices: one lattice to
  10584. represent abstract states and another lattice that aggregates the
  10585. abstract states of all the blocks in the control-flow graph. For
  10586. liveness analysis, an abstract state is a set of locations. We form
  10587. the lattice $L$ by taking its elements to be sets of locations, the
  10588. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10589. set, and the join operator to be set union.
  10590. %
  10591. We form a second lattice $M$ by taking its elements to be mappings
  10592. from the block labels to sets of locations (elements of $L$). We
  10593. order the mappings point-wise, using the ordering of $L$. So, given any
  10594. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10595. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10596. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10597. to the empty set, $\bot_M(\ell) = \emptyset$.
  10598. We can think of one iteration of liveness analysis applied to the
  10599. whole program as being a function $f$ on the lattice $M$. It takes a
  10600. mapping as input and computes a new mapping.
  10601. \[
  10602. f(m_i) = m_{i+1}
  10603. \]
  10604. Next let us think for a moment about what a final solution $m_s$
  10605. should look like. If we perform liveness analysis using the solution
  10606. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10607. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10608. \[
  10609. f(m_s) = m_s
  10610. \]
  10611. Furthermore, the solution should include only locations that are
  10612. forced to be there by performing liveness analysis on the program, so
  10613. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10614. The Kleene fixed-point theorem states that if a function $f$ is
  10615. monotone (better inputs produce better outputs), then the least fixed
  10616. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10617. chain} that starts at $\bot$ and iterates $f$ as
  10618. follows:\index{subject}{Kleene fixed-point theorem}
  10619. \[
  10620. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10621. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10622. \]
  10623. When a lattice contains only finitely long ascending chains, then
  10624. every Kleene chain tops out at some fixed point after some number of
  10625. iterations of $f$.
  10626. \[
  10627. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10628. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10629. \]
  10630. The liveness analysis is indeed a monotone function and the lattice
  10631. $M$ has finitely long ascending chains because there are only a
  10632. finite number of variables and blocks in the program. Thus we are
  10633. guaranteed that iteratively applying liveness analysis to all blocks
  10634. in the program will eventually produce the least fixed point solution.
  10635. Next let us consider dataflow analysis in general and discuss the
  10636. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10637. %
  10638. The algorithm has four parameters: the control-flow graph \code{G}, a
  10639. function \code{transfer} that applies the analysis to one block, and the
  10640. \code{bottom} and \code{join} operators for the lattice of abstract
  10641. states. The \code{analyze\_dataflow} function is formulated as a
  10642. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10643. function come from the predecessor nodes in the control-flow
  10644. graph. However, liveness analysis is a \emph{backward} dataflow
  10645. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10646. function with the transpose of the control-flow graph.
  10647. The algorithm begins by creating the bottom mapping, represented by a
  10648. hash table. It then pushes all the nodes in the control-flow graph
  10649. onto the work list (a queue). The algorithm repeats the \code{while}
  10650. loop as long as there are items in the work list. In each iteration, a
  10651. node is popped from the work list and processed. The \code{input} for
  10652. the node is computed by taking the join of the abstract states of all
  10653. the predecessor nodes. The \code{transfer} function is then applied to
  10654. obtain the \code{output} abstract state. If the output differs from
  10655. the previous state for this block, the mapping for this block is
  10656. updated and its successor nodes are pushed onto the work list.
  10657. \begin{figure}[tb]
  10658. \begin{tcolorbox}[colback=white]
  10659. {\if\edition\racketEd
  10660. \begin{lstlisting}
  10661. (define (analyze_dataflow G transfer bottom join)
  10662. (define mapping (make-hash))
  10663. (for ([v (in-vertices G)])
  10664. (dict-set! mapping v bottom))
  10665. (define worklist (make-queue))
  10666. (for ([v (in-vertices G)])
  10667. (enqueue! worklist v))
  10668. (define trans-G (transpose G))
  10669. (while (not (queue-empty? worklist))
  10670. (define node (dequeue! worklist))
  10671. (define input (for/fold ([state bottom])
  10672. ([pred (in-neighbors trans-G node)])
  10673. (join state (dict-ref mapping pred))))
  10674. (define output (transfer node input))
  10675. (cond [(not (equal? output (dict-ref mapping node)))
  10676. (dict-set! mapping node output)
  10677. (for ([v (in-neighbors G node)])
  10678. (enqueue! worklist v))]))
  10679. mapping)
  10680. \end{lstlisting}
  10681. \fi}
  10682. {\if\edition\pythonEd\pythonColor
  10683. \begin{lstlisting}
  10684. def analyze_dataflow(G, transfer, bottom, join):
  10685. trans_G = transpose(G)
  10686. mapping = dict((v, bottom) for v in G.vertices())
  10687. worklist = deque(G.vertices)
  10688. while worklist:
  10689. node = worklist.pop()
  10690. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10691. input = reduce(join, inputs, bottom)
  10692. output = transfer(node, input)
  10693. if output != mapping[node]:
  10694. mapping[node] = output
  10695. worklist.extend(G.adjacent(node))
  10696. \end{lstlisting}
  10697. \fi}
  10698. \end{tcolorbox}
  10699. \caption{Generic work list algorithm for dataflow analysis.}
  10700. \label{fig:generic-dataflow}
  10701. \end{figure}
  10702. {\if\edition\racketEd
  10703. \section{Mutable Variables and Remove Complex Operands}
  10704. There is a subtle interaction between the
  10705. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10706. and the left-to-right order of evaluation of Racket. Consider the
  10707. following example:
  10708. \begin{lstlisting}
  10709. (let ([x 2])
  10710. (+ x (begin (set! x 40) x)))
  10711. \end{lstlisting}
  10712. The result of this program is \code{42} because the first read from
  10713. \code{x} produces \code{2} and the second produces \code{40}. However,
  10714. if we naively apply the \code{remove\_complex\_operands} pass to this
  10715. example we obtain the following program whose result is \code{80}!
  10716. \begin{lstlisting}
  10717. (let ([x 2])
  10718. (let ([tmp (begin (set! x 40) x)])
  10719. (+ x tmp)))
  10720. \end{lstlisting}
  10721. The problem is that with mutable variables, the ordering between
  10722. reads and writes is important, and the
  10723. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10724. before the first read of \code{x}.
  10725. We recommend solving this problem by giving special treatment to reads
  10726. from mutable variables, that is, variables that occur on the left-hand
  10727. side of a \code{set!}. We mark each read from a mutable variable with
  10728. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10729. that the read operation is effectful in that it can produce different
  10730. results at different points in time. Let's apply this idea to the
  10731. following variation that also involves a variable that is not mutated:
  10732. % loop_test_24.rkt
  10733. \begin{lstlisting}
  10734. (let ([x 2])
  10735. (let ([y 0])
  10736. (+ y (+ x (begin (set! x 40) x)))))
  10737. \end{lstlisting}
  10738. We first analyze this program to discover that variable \code{x}
  10739. is mutable but \code{y} is not. We then transform the program as
  10740. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10741. \begin{lstlisting}
  10742. (let ([x 2])
  10743. (let ([y 0])
  10744. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10745. \end{lstlisting}
  10746. Now that we have a clear distinction between reads from mutable and
  10747. immutable variables, we can apply the \code{remove\_complex\_operands}
  10748. pass, where reads from immutable variables are still classified as
  10749. atomic expressions but reads from mutable variables are classified as
  10750. complex. Thus, \code{remove\_complex\_operands} yields the following
  10751. program:\\
  10752. \begin{minipage}{\textwidth}
  10753. \begin{lstlisting}
  10754. (let ([x 2])
  10755. (let ([y 0])
  10756. (let ([t1 x])
  10757. (let ([t2 (begin (set! x 40) x)])
  10758. (let ([t3 (+ t1 t2)])
  10759. (+ y t3))))))
  10760. \end{lstlisting}
  10761. \end{minipage}
  10762. The temporary variable \code{t1} gets the value of \code{x} before the
  10763. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10764. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10765. do not generate a temporary variable for the occurrence of \code{y}
  10766. because it's an immutable variable. We want to avoid such unnecessary
  10767. extra temporaries because they would needlessly increase the number of
  10768. variables, making it more likely for some of them to be spilled. The
  10769. result of this program is \code{42}, the same as the result prior to
  10770. \code{remove\_complex\_operands}.
  10771. The approach that we've sketched requires only a small
  10772. modification to \code{remove\_complex\_operands} to handle
  10773. \code{get!}. However, it requires a new pass, called
  10774. \code{uncover-get!}, that we discuss in
  10775. section~\ref{sec:uncover-get-bang}.
  10776. As an aside, this problematic interaction between \code{set!} and the
  10777. pass \code{remove\_complex\_operands} is particular to Racket and not
  10778. its predecessor, the Scheme language. The key difference is that
  10779. Scheme does not specify an order of evaluation for the arguments of an
  10780. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10781. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10782. would be correct results for the example program. Interestingly,
  10783. Racket is implemented on top of the Chez Scheme
  10784. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10785. presented in this section (using extra \code{let} bindings to control
  10786. the order of evaluation) is used in the translation from Racket to
  10787. Scheme~\citep{Flatt:2019tb}.
  10788. \fi} % racket
  10789. Having discussed the complications that arise from adding support for
  10790. assignment and loops, we turn to discussing the individual compilation
  10791. passes.
  10792. {\if\edition\racketEd
  10793. \section{Uncover \texttt{get!}}
  10794. \label{sec:uncover-get-bang}
  10795. The goal of this pass is to mark uses of mutable variables so that
  10796. \code{remove\_complex\_operands} can treat them as complex expressions
  10797. and thereby preserve their ordering relative to the side effects in
  10798. other operands. So, the first step is to collect all the mutable
  10799. variables. We recommend creating an auxiliary function for this,
  10800. named \code{collect-set!}, that recursively traverses expressions,
  10801. returning the set of all variables that occur on the left-hand side of a
  10802. \code{set!}. Here's an excerpt of its implementation.
  10803. \begin{center}
  10804. \begin{minipage}{\textwidth}
  10805. \begin{lstlisting}
  10806. (define (collect-set! e)
  10807. (match e
  10808. [(Var x) (set)]
  10809. [(Int n) (set)]
  10810. [(Let x rhs body)
  10811. (set-union (collect-set! rhs) (collect-set! body))]
  10812. [(SetBang var rhs)
  10813. (set-union (set var) (collect-set! rhs))]
  10814. ...))
  10815. \end{lstlisting}
  10816. \end{minipage}
  10817. \end{center}
  10818. By placing this pass after \code{uniquify}, we need not worry about
  10819. variable shadowing, and our logic for \code{Let} can remain simple, as
  10820. in this excerpt.
  10821. The second step is to mark the occurrences of the mutable variables
  10822. with the new \code{GetBang} AST node (\code{get!} in concrete
  10823. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10824. function, which takes two parameters: the set of mutable variables
  10825. \code{set!-vars} and the expression \code{e} to be processed. The
  10826. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10827. mutable variable or leaves it alone if not.
  10828. \begin{center}
  10829. \begin{minipage}{\textwidth}
  10830. \begin{lstlisting}
  10831. (define ((uncover-get!-exp set!-vars) e)
  10832. (match e
  10833. [(Var x)
  10834. (if (set-member? set!-vars x)
  10835. (GetBang x)
  10836. (Var x))]
  10837. ...))
  10838. \end{lstlisting}
  10839. \end{minipage}
  10840. \end{center}
  10841. To wrap things up, define the \code{uncover-get!} function for
  10842. processing a whole program, using \code{collect-set!} to obtain the
  10843. set of mutable variables and then \code{uncover-get!-exp} to replace
  10844. their occurrences with \code{GetBang}.
  10845. \fi}
  10846. \section{Remove Complex Operands}
  10847. \label{sec:rco-loop}
  10848. {\if\edition\racketEd
  10849. %
  10850. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10851. \code{while} are all complex expressions. The subexpressions of
  10852. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10853. %
  10854. \fi}
  10855. {\if\edition\pythonEd\pythonColor
  10856. %
  10857. The change needed for this pass is to add a case for the \code{while}
  10858. statement. The condition of a loop is allowed to be a complex
  10859. expression, just like the condition of the \code{if} statement.
  10860. %
  10861. \fi}
  10862. %
  10863. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10864. \LangLoopANF{} of this pass.
  10865. \newcommand{\LwhileMonadASTRacket}{
  10866. \begin{array}{rcl}
  10867. \Atm &::=& \VOID{} \\
  10868. \Exp &::=& \GETBANG{\Var}
  10869. \MID \SETBANG{\Var}{\Exp}
  10870. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10871. &\MID& \WHILE{\Exp}{\Exp}
  10872. \end{array}
  10873. }
  10874. \newcommand{\LwhileMonadASTPython}{
  10875. \begin{array}{rcl}
  10876. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10877. \end{array}
  10878. }
  10879. \begin{figure}[tp]
  10880. \centering
  10881. \begin{tcolorbox}[colback=white]
  10882. \small
  10883. {\if\edition\racketEd
  10884. \[
  10885. \begin{array}{l}
  10886. \gray{\LvarMonadASTRacket} \\ \hline
  10887. \gray{\LifMonadASTRacket} \\ \hline
  10888. \LwhileMonadASTRacket \\
  10889. \begin{array}{rcl}
  10890. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10891. \end{array}
  10892. \end{array}
  10893. \]
  10894. \fi}
  10895. {\if\edition\pythonEd\pythonColor
  10896. \[
  10897. \begin{array}{l}
  10898. \gray{\LvarMonadASTPython} \\ \hline
  10899. \gray{\LifMonadASTPython} \\ \hline
  10900. \LwhileMonadASTPython \\
  10901. \begin{array}{rcl}
  10902. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10903. \end{array}
  10904. \end{array}
  10905. \]
  10906. \fi}
  10907. \end{tcolorbox}
  10908. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10909. \label{fig:Lwhile-anf-syntax}
  10910. \index{subject}{Lwhilemon@\LangLoopANF{} abstract syntax}
  10911. \end{figure}
  10912. {\if\edition\racketEd
  10913. %
  10914. As usual, when a complex expression appears in a grammar position that
  10915. needs to be atomic, such as the argument of a primitive operator, we
  10916. must introduce a temporary variable and bind it to the complex
  10917. expression. This approach applies, unchanged, to handle the new
  10918. language forms. For example, in the following code there are two
  10919. \code{begin} expressions appearing as arguments to the \code{+}
  10920. operator. The output of \code{rco\_exp} is then shown, in which the
  10921. \code{begin} expressions have been bound to temporary
  10922. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10923. allowed to have arbitrary expressions in their right-hand side
  10924. expression, so it is fine to place \code{begin} there.
  10925. %
  10926. \begin{center}
  10927. \begin{tabular}{lcl}
  10928. \begin{minipage}{0.4\textwidth}
  10929. \begin{lstlisting}
  10930. (let ([x2 10])
  10931. (let ([y3 0])
  10932. (+ (+ (begin
  10933. (set! y3 (read))
  10934. (get! x2))
  10935. (begin
  10936. (set! x2 (read))
  10937. (get! y3)))
  10938. (get! x2))))
  10939. \end{lstlisting}
  10940. \end{minipage}
  10941. &
  10942. $\Rightarrow$
  10943. &
  10944. \begin{minipage}{0.4\textwidth}
  10945. \begin{lstlisting}
  10946. (let ([x2 10])
  10947. (let ([y3 0])
  10948. (let ([tmp4 (begin
  10949. (set! y3 (read))
  10950. x2)])
  10951. (let ([tmp5 (begin
  10952. (set! x2 (read))
  10953. y3)])
  10954. (let ([tmp6 (+ tmp4 tmp5)])
  10955. (let ([tmp7 x2])
  10956. (+ tmp6 tmp7)))))))
  10957. \end{lstlisting}
  10958. \end{minipage}
  10959. \end{tabular}
  10960. \end{center}
  10961. \fi}
  10962. \section{Explicate Control \racket{and \LangCLoop{}}}
  10963. \label{sec:explicate-loop}
  10964. \newcommand{\CloopASTRacket}{
  10965. \begin{array}{lcl}
  10966. \Atm &::=& \VOID \\
  10967. \Stmt &::=& \READ{}
  10968. \end{array}
  10969. }
  10970. {\if\edition\racketEd
  10971. Recall that in the \code{explicate\_control} pass we define one helper
  10972. function for each kind of position in the program. For the \LangVar{}
  10973. language of integers and variables, we needed assignment and tail
  10974. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10975. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10976. another kind of position: effect position. Except for the last
  10977. subexpression, the subexpressions inside a \code{begin} are evaluated
  10978. only for their effect. Their result values are discarded. We can
  10979. generate better code by taking this fact into account.
  10980. The output language of \code{explicate\_control} is \LangCLoop{}
  10981. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10982. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10983. and that \code{read} may appear as a statement. The most significant
  10984. difference between the programs generated by \code{explicate\_control}
  10985. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10986. chapter is that the control-flow graphs of the latter may contain
  10987. cycles.
  10988. \begin{figure}[tp]
  10989. \begin{tcolorbox}[colback=white]
  10990. \small
  10991. \[
  10992. \begin{array}{l}
  10993. \gray{\CvarASTRacket} \\ \hline
  10994. \gray{\CifASTRacket} \\ \hline
  10995. \CloopASTRacket \\
  10996. \begin{array}{lcl}
  10997. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10998. \end{array}
  10999. \end{array}
  11000. \]
  11001. \end{tcolorbox}
  11002. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  11003. \label{fig:c7-syntax}
  11004. \index{subject}{Cwhile@\LangCLoop{} abstract syntax}
  11005. \end{figure}
  11006. The new auxiliary function \code{explicate\_effect} takes an
  11007. expression (in an effect position) and the code for its
  11008. continuation. The function returns a $\Tail$ that includes the
  11009. generated code for the input expression followed by the
  11010. continuation. If the expression is obviously pure, that is, never
  11011. causes side effects, then the expression can be removed, so the result
  11012. is just the continuation.
  11013. %
  11014. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  11015. interesting; the generated code is depicted in the following diagram:
  11016. \begin{center}
  11017. \begin{minipage}{0.3\textwidth}
  11018. \xymatrix{
  11019. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  11020. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  11021. & *+[F]{\txt{\itm{cont}}} \\
  11022. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  11023. }
  11024. \end{minipage}
  11025. \end{center}
  11026. We start by creating a fresh label $\itm{loop}$ for the top of the
  11027. loop. Next, recursively process the \itm{body} (in effect position)
  11028. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  11029. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  11030. \itm{body'} as the \emph{then} branch and the continuation block as the
  11031. \emph{else} branch. The result should be added to the dictionary of
  11032. \code{basic-blocks} with the label \itm{loop}. The result for the
  11033. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11034. The auxiliary functions for tail, assignment, and predicate positions
  11035. need to be updated. The three new language forms, \code{while},
  11036. \code{set!}, and \code{begin}, can appear in assignment and tail
  11037. positions. Only \code{begin} may appear in predicate positions; the
  11038. other two have result type \code{Void}.
  11039. \fi}
  11040. %
  11041. {\if\edition\pythonEd\pythonColor
  11042. %
  11043. The output of this pass is the language \LangCIf{}. No new language
  11044. features are needed in the output, because a \code{while} loop can be
  11045. expressed in terms of \code{goto} and \code{if} statements, which are
  11046. already in \LangCIf{}.
  11047. %
  11048. Add a case for the \code{while} statement to the
  11049. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11050. the condition expression.
  11051. %
  11052. \fi}
  11053. {\if\edition\racketEd
  11054. \section{Select Instructions}
  11055. \label{sec:select-instructions-loop}
  11056. \index{subject}{select instructions}
  11057. Only two small additions are needed in the \code{select\_instructions}
  11058. pass to handle the changes to \LangCLoop{}. First, to handle the
  11059. addition of \VOID{} we simply translate it to \code{0}. Second,
  11060. \code{read} may appear as a stand-alone statement instead of
  11061. appearing only on the right-hand side of an assignment statement. The code
  11062. generation is nearly identical to the one for assignment; just leave
  11063. off the instruction for moving the result into the left-hand side.
  11064. \fi}
  11065. \section{Register Allocation}
  11066. \label{sec:register-allocation-loop}
  11067. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11068. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11069. which complicates the liveness analysis needed for register
  11070. allocation.
  11071. %
  11072. We recommend using the generic \code{analyze\_dataflow} function that
  11073. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11074. perform liveness analysis, replacing the code in
  11075. \code{uncover\_live} that processed the basic blocks in topological
  11076. order (section~\ref{sec:liveness-analysis-Lif}).
  11077. The \code{analyze\_dataflow} function has the following four parameters.
  11078. \begin{enumerate}
  11079. \item The first parameter \code{G} should be passed the transpose
  11080. of the control-flow graph.
  11081. \item The second parameter \code{transfer} should be passed a function
  11082. that applies liveness analysis to a basic block. It takes two
  11083. parameters: the label for the block to analyze and the live-after
  11084. set for that block. The transfer function should return the
  11085. live-before set for the block.
  11086. %
  11087. \racket{Also, as a side effect, it should update the block's
  11088. $\itm{info}$ with the liveness information for each instruction.}
  11089. %
  11090. \python{Also, as a side effect, it should update the live-before and
  11091. live-after sets for each instruction.}
  11092. %
  11093. To implement the \code{transfer} function, you should be able to
  11094. reuse the code you already have for analyzing basic blocks.
  11095. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11096. \code{bottom} and \code{join} for the lattice of abstract states,
  11097. that is, sets of locations. For liveness analysis, the bottom of the
  11098. lattice is the empty set, and the join operator is set union.
  11099. \end{enumerate}
  11100. \begin{figure}[tp]
  11101. \begin{tcolorbox}[colback=white]
  11102. {\if\edition\racketEd
  11103. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11104. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11105. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11106. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11107. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11108. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11109. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11110. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11111. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11112. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11113. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11114. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11115. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11116. \path[->,bend left=15] (Lfun) edge [above] node
  11117. {\ttfamily\footnotesize shrink} (Lfun-2);
  11118. \path[->,bend left=15] (Lfun-2) edge [above] node
  11119. {\ttfamily\footnotesize uniquify} (F1-4);
  11120. \path[->,bend left=15] (F1-4) edge [above] node
  11121. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11122. \path[->,bend left=15] (F1-5) edge [left] node
  11123. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11124. \path[->,bend left=10] (F1-6) edge [above] node
  11125. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11126. \path[->,bend left=15] (C3-2) edge [right] node
  11127. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11128. \path[->,bend right=15] (x86-2) edge [right] node
  11129. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11130. \path[->,bend right=15] (x86-2-1) edge [below] node
  11131. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11132. \path[->,bend right=15] (x86-2-2) edge [right] node
  11133. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11134. \path[->,bend left=15] (x86-3) edge [above] node
  11135. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11136. \path[->,bend left=15] (x86-4) edge [right] node
  11137. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11138. \end{tikzpicture}
  11139. \fi}
  11140. {\if\edition\pythonEd\pythonColor
  11141. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11142. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11143. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11144. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11145. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11146. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11147. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11148. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11149. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11150. \path[->,bend left=15] (Lfun) edge [above] node
  11151. {\ttfamily\footnotesize shrink} (Lfun-2);
  11152. \path[->,bend left=15] (Lfun-2) edge [above] node
  11153. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11154. \path[->,bend left=10] (F1-6) edge [right] node
  11155. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11156. \path[->,bend right=15] (C3-2) edge [right] node
  11157. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11158. \path[->,bend right=15] (x86-2) edge [below] node
  11159. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11160. \path[->,bend left=15] (x86-3) edge [above] node
  11161. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11162. \path[->,bend right=15] (x86-4) edge [below] node
  11163. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11164. \end{tikzpicture}
  11165. \fi}
  11166. \end{tcolorbox}
  11167. \caption{Diagram of the passes for \LangLoop{}.}
  11168. \label{fig:Lwhile-passes}
  11169. \end{figure}
  11170. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11171. for the compilation of \LangLoop{}.
  11172. % Further Reading: dataflow analysis
  11173. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11174. \chapter{Tuples and Garbage Collection}
  11175. \label{ch:Lvec}
  11176. \index{subject}{tuple}
  11177. \index{subject}{vector}
  11178. \setcounter{footnote}{0}
  11179. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11180. %% all the IR grammars are spelled out! \\ --Jeremy}
  11181. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11182. %% the root stack. \\ --Jeremy}
  11183. In this chapter we study the implementation of tuples\racket{, called
  11184. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11185. in which each element may have a different type.
  11186. %
  11187. This language feature is the first to use the computer's
  11188. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11189. indefinite; that is, a tuple lives forever from the programmer's
  11190. viewpoint. Of course, from an implementer's viewpoint, it is important
  11191. to reclaim the space associated with a tuple when it is no longer
  11192. needed, which is why we also study \emph{garbage collection}
  11193. \index{subject}{garbage collection} techniques in this chapter.
  11194. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11195. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11196. language (chapter~\ref{ch:Lwhile}) with tuples.
  11197. %
  11198. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11199. copying live tuples back and forth between two halves of the heap. The
  11200. garbage collector requires coordination with the compiler so that it
  11201. can find all the live tuples.
  11202. %
  11203. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11204. discuss the necessary changes and additions to the compiler passes,
  11205. including a new compiler pass named \code{expose\_allocation}.
  11206. \section{The \LangVec{} Language}
  11207. \label{sec:r3}
  11208. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11209. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11210. the definition of the abstract syntax.
  11211. %
  11212. \racket{The \LangVec{} language includes the forms \code{vector} for
  11213. creating a tuple, \code{vector-ref} for reading an element of a
  11214. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11215. \code{vector-length} for obtaining the number of elements of a
  11216. tuple.}
  11217. %
  11218. \python{The \LangVec{} language adds (1) tuple creation via a
  11219. comma-separated list of expressions; (2) accessing an element of a
  11220. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11221. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11222. comparison operator; and (4) obtaining the number of elements (the
  11223. length) of a tuple. In this chapter, we restrict access indices to
  11224. constant integers.}
  11225. %
  11226. The following program shows an example of the use of tuples. It creates a tuple
  11227. \code{t} containing the elements \code{40},
  11228. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11229. contains just \code{2}. The element at index $1$ of \code{t} is
  11230. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11231. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11232. to which we add \code{2}, the element at index $0$ of the tuple.
  11233. The result of the program is \code{42}.
  11234. %
  11235. {\if\edition\racketEd
  11236. \begin{lstlisting}
  11237. (let ([t (vector 40 #t (vector 2))])
  11238. (if (vector-ref t 1)
  11239. (+ (vector-ref t 0)
  11240. (vector-ref (vector-ref t 2) 0))
  11241. 44))
  11242. \end{lstlisting}
  11243. \fi}
  11244. {\if\edition\pythonEd\pythonColor
  11245. \begin{lstlisting}
  11246. t = 40, True, (2,)
  11247. print(t[0] + t[2][0] if t[1] else 44)
  11248. \end{lstlisting}
  11249. \fi}
  11250. \newcommand{\LtupGrammarRacket}{
  11251. \begin{array}{lcl}
  11252. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11253. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11254. \MID \LP\key{vector-length}\;\Exp\RP \\
  11255. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11256. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11257. \end{array}
  11258. }
  11259. \newcommand{\LtupASTRacket}{
  11260. \begin{array}{lcl}
  11261. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11262. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11263. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11264. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11265. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11266. \end{array}
  11267. }
  11268. \newcommand{\LtupGrammarPython}{
  11269. \begin{array}{rcl}
  11270. \itm{cmp} &::= & \key{is} \\
  11271. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11272. \end{array}
  11273. }
  11274. \newcommand{\LtupASTPython}{
  11275. \begin{array}{lcl}
  11276. \itm{cmp} &::= & \code{Is()} \\
  11277. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11278. &\MID& \LEN{\Exp}
  11279. \end{array}
  11280. }
  11281. \begin{figure}[tbp]
  11282. \centering
  11283. \begin{tcolorbox}[colback=white]
  11284. \small
  11285. {\if\edition\racketEd
  11286. \[
  11287. \begin{array}{l}
  11288. \gray{\LintGrammarRacket{}} \\ \hline
  11289. \gray{\LvarGrammarRacket{}} \\ \hline
  11290. \gray{\LifGrammarRacket{}} \\ \hline
  11291. \gray{\LwhileGrammarRacket} \\ \hline
  11292. \LtupGrammarRacket \\
  11293. \begin{array}{lcl}
  11294. \LangVecM{} &::=& \Exp
  11295. \end{array}
  11296. \end{array}
  11297. \]
  11298. \fi}
  11299. {\if\edition\pythonEd\pythonColor
  11300. \[
  11301. \begin{array}{l}
  11302. \gray{\LintGrammarPython{}} \\ \hline
  11303. \gray{\LvarGrammarPython{}} \\ \hline
  11304. \gray{\LifGrammarPython{}} \\ \hline
  11305. \gray{\LwhileGrammarPython} \\ \hline
  11306. \LtupGrammarPython \\
  11307. \begin{array}{rcl}
  11308. \LangVecM{} &::=& \Stmt^{*}
  11309. \end{array}
  11310. \end{array}
  11311. \]
  11312. \fi}
  11313. \end{tcolorbox}
  11314. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11315. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11316. \label{fig:Lvec-concrete-syntax}
  11317. \index{subject}{Ltup@\LangVec{} concrete syntax}
  11318. \end{figure}
  11319. \begin{figure}[tp]
  11320. \centering
  11321. \begin{tcolorbox}[colback=white]
  11322. \small
  11323. {\if\edition\racketEd
  11324. \[
  11325. \begin{array}{l}
  11326. \gray{\LintOpAST} \\ \hline
  11327. \gray{\LvarASTRacket{}} \\ \hline
  11328. \gray{\LifASTRacket{}} \\ \hline
  11329. \gray{\LwhileASTRacket{}} \\ \hline
  11330. \LtupASTRacket{} \\
  11331. \begin{array}{lcl}
  11332. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11333. \end{array}
  11334. \end{array}
  11335. \]
  11336. \fi}
  11337. {\if\edition\pythonEd\pythonColor
  11338. \[
  11339. \begin{array}{l}
  11340. \gray{\LintASTPython} \\ \hline
  11341. \gray{\LvarASTPython} \\ \hline
  11342. \gray{\LifASTPython} \\ \hline
  11343. \gray{\LwhileASTPython} \\ \hline
  11344. \LtupASTPython \\
  11345. \begin{array}{lcl}
  11346. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11347. \end{array}
  11348. \end{array}
  11349. \]
  11350. \fi}
  11351. \end{tcolorbox}
  11352. \caption{The abstract syntax of \LangVec{}.}
  11353. \label{fig:Lvec-syntax}
  11354. \index{subject}{Ltup@\LangVec{} abstract syntax}
  11355. \end{figure}
  11356. Tuples raise several interesting new issues. First, variable binding
  11357. performs a shallow copy in dealing with tuples, which means that
  11358. different variables can refer to the same tuple; that is, two
  11359. variables can be \emph{aliases}\index{subject}{alias} for the same
  11360. entity. Consider the following example, in which \code{t1} and
  11361. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11362. different tuple value with equal elements. The result of the
  11363. program is \code{42}.
  11364. \begin{center}
  11365. \begin{minipage}{0.96\textwidth}
  11366. {\if\edition\racketEd
  11367. \begin{lstlisting}
  11368. (let ([t1 (vector 3 7)])
  11369. (let ([t2 t1])
  11370. (let ([t3 (vector 3 7)])
  11371. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11372. 42
  11373. 0))))
  11374. \end{lstlisting}
  11375. \fi}
  11376. {\if\edition\pythonEd\pythonColor
  11377. \begin{lstlisting}
  11378. t1 = 3, 7
  11379. t2 = t1
  11380. t3 = 3, 7
  11381. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11382. \end{lstlisting}
  11383. \fi}
  11384. \end{minipage}
  11385. \end{center}
  11386. {\if\edition\racketEd
  11387. Whether two variables are aliased or not affects what happens
  11388. when the underlying tuple is mutated\index{subject}{mutation}.
  11389. Consider the following example in which \code{t1} and \code{t2}
  11390. again refer to the same tuple value.
  11391. \begin{center}
  11392. \begin{minipage}{0.96\textwidth}
  11393. \begin{lstlisting}
  11394. (let ([t1 (vector 3 7)])
  11395. (let ([t2 t1])
  11396. (let ([_ (vector-set! t2 0 42)])
  11397. (vector-ref t1 0))))
  11398. \end{lstlisting}
  11399. \end{minipage}
  11400. \end{center}
  11401. The mutation through \code{t2} is visible in referencing the tuple
  11402. from \code{t1}, so the result of this program is \code{42}.
  11403. \fi}
  11404. The next issue concerns the lifetime of tuples. When does a tuple's
  11405. lifetime end? Notice that \LangVec{} does not include an operation
  11406. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11407. to any notion of static scoping.
  11408. %
  11409. {\if\edition\racketEd
  11410. %
  11411. For example, the following program returns \code{42} even though the
  11412. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11413. that reads from the vector to which it was bound.
  11414. \begin{center}
  11415. \begin{minipage}{0.96\textwidth}
  11416. \begin{lstlisting}
  11417. (let ([v (vector (vector 44))])
  11418. (let ([x (let ([w (vector 42)])
  11419. (let ([_ (vector-set! v 0 w)])
  11420. 0))])
  11421. (+ x (vector-ref (vector-ref v 0) 0))))
  11422. \end{lstlisting}
  11423. \end{minipage}
  11424. \end{center}
  11425. \fi}
  11426. %
  11427. {\if\edition\pythonEd\pythonColor
  11428. %
  11429. For example, the following program returns \code{42} even though the
  11430. variable \code{x} goes out of scope when the function returns, prior
  11431. to reading the tuple element at index $0$. (We study the compilation
  11432. of functions in chapter~\ref{ch:Lfun}.)
  11433. %
  11434. \begin{center}
  11435. \begin{minipage}{0.96\textwidth}
  11436. \begin{lstlisting}
  11437. def f():
  11438. x = 42, 43
  11439. return x
  11440. t = f()
  11441. print(t[0])
  11442. \end{lstlisting}
  11443. \end{minipage}
  11444. \end{center}
  11445. \fi}
  11446. %
  11447. From the perspective of programmer-observable behavior, tuples live
  11448. forever. However, if they really lived forever then many long-running
  11449. programs would run out of memory. To solve this problem, the
  11450. language's runtime system performs automatic garbage collection.
  11451. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11452. \LangVec{} language.
  11453. %
  11454. \racket{We define the \code{vector}, \code{vector-ref},
  11455. \code{vector-set!}, and \code{vector-length} operations for
  11456. \LangVec{} in terms of the corresponding operations in Racket. One
  11457. subtle point is that the \code{vector-set!} operation returns the
  11458. \code{\#<void>} value.}
  11459. %
  11460. \python{We represent tuples with Python lists in the interpreter
  11461. because we need to write to them
  11462. (section~\ref{sec:expose-allocation}). (Python tuples are
  11463. immutable.) We define element access, the \code{is} operator, and
  11464. the \code{len} operator for \LangVec{} in terms of the corresponding
  11465. operations in Python.}
  11466. \begin{figure}[tbp]
  11467. \begin{tcolorbox}[colback=white]
  11468. {\if\edition\racketEd
  11469. \begin{lstlisting}
  11470. (define interp-Lvec-class
  11471. (class interp-Lwhile-class
  11472. (super-new)
  11473. (define/override (interp-op op)
  11474. (match op
  11475. ['eq? (lambda (v1 v2)
  11476. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11477. (and (boolean? v1) (boolean? v2))
  11478. (and (vector? v1) (vector? v2))
  11479. (and (void? v1) (void? v2)))
  11480. (eq? v1 v2)]))]
  11481. ['vector vector]
  11482. ['vector-length vector-length]
  11483. ['vector-ref vector-ref]
  11484. ['vector-set! vector-set!]
  11485. [else (super interp-op op)]
  11486. ))
  11487. (define/override ((interp-exp env) e)
  11488. (match e
  11489. [(HasType e t) ((interp-exp env) e)]
  11490. [else ((super interp-exp env) e)]
  11491. ))
  11492. ))
  11493. (define (interp-Lvec p)
  11494. (send (new interp-Lvec-class) interp-program p))
  11495. \end{lstlisting}
  11496. \fi}
  11497. %
  11498. {\if\edition\pythonEd\pythonColor
  11499. \begin{lstlisting}
  11500. class InterpLtup(InterpLwhile):
  11501. def interp_cmp(self, cmp):
  11502. match cmp:
  11503. case Is():
  11504. return lambda x, y: x is y
  11505. case _:
  11506. return super().interp_cmp(cmp)
  11507. def interp_exp(self, e, env):
  11508. match e:
  11509. case Tuple(es, Load()):
  11510. return tuple([self.interp_exp(e, env) for e in es])
  11511. case Subscript(tup, index, Load()):
  11512. t = self.interp_exp(tup, env)
  11513. n = self.interp_exp(index, env)
  11514. return t[n]
  11515. case _:
  11516. return super().interp_exp(e, env)
  11517. \end{lstlisting}
  11518. \fi}
  11519. \end{tcolorbox}
  11520. \caption{Interpreter for the \LangVec{} language.}
  11521. \label{fig:interp-Lvec}
  11522. \end{figure}
  11523. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11524. \LangVec{}.
  11525. %
  11526. The type of a tuple is a
  11527. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11528. type for each of its elements.
  11529. %
  11530. \racket{To create the s-expression for the \code{Vector} type, we use the
  11531. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11532. operator} \code{,@} to insert the list \code{t*} without its usual
  11533. start and end parentheses. \index{subject}{unquote-splicing}}
  11534. %
  11535. The type of accessing the ith element of a tuple is the ith element
  11536. type of the tuple's type, if there is one. If not, an error is
  11537. signaled. Note that the index \code{i} is required to be a constant
  11538. integer (and not, for example, a call to
  11539. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11540. can determine the element's type given the tuple type.
  11541. %
  11542. \racket{
  11543. Regarding writing an element to a tuple, the element's type must
  11544. be equal to the ith element type of the tuple's type.
  11545. The result type is \code{Void}.}
  11546. %% When allocating a tuple,
  11547. %% we need to know which elements of the tuple are themselves tuples for
  11548. %% the purposes of garbage collection. We can obtain this information
  11549. %% during type checking. The type checker shown in
  11550. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11551. %% expression; it also
  11552. %% %
  11553. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11554. %% where $T$ is the tuple's type.
  11555. %
  11556. %records the type of each tuple expression in a new field named \code{has\_type}.
  11557. \begin{figure}[tp]
  11558. \begin{tcolorbox}[colback=white]
  11559. {\if\edition\racketEd
  11560. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11561. (define type-check-Lvec-class
  11562. (class type-check-Lif-class
  11563. (super-new)
  11564. (inherit check-type-equal?)
  11565. (define/override (type-check-exp env)
  11566. (lambda (e)
  11567. (define recur (type-check-exp env))
  11568. (match e
  11569. [(Prim 'vector es)
  11570. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11571. (define t `(Vector ,@t*))
  11572. (values (Prim 'vector e*) t)]
  11573. [(Prim 'vector-ref (list e1 (Int i)))
  11574. (define-values (e1^ t) (recur e1))
  11575. (match t
  11576. [`(Vector ,ts ...)
  11577. (unless (and (0 . <= . i) (i . < . (length ts)))
  11578. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11579. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11580. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11581. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11582. (define-values (e-vec t-vec) (recur e1))
  11583. (define-values (e-elt^ t-elt) (recur elt))
  11584. (match t-vec
  11585. [`(Vector ,ts ...)
  11586. (unless (and (0 . <= . i) (i . < . (length ts)))
  11587. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11588. (check-type-equal? (list-ref ts i) t-elt e)
  11589. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11590. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11591. [(Prim 'vector-length (list e))
  11592. (define-values (e^ t) (recur e))
  11593. (match t
  11594. [`(Vector ,ts ...)
  11595. (values (Prim 'vector-length (list e^)) 'Integer)]
  11596. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11597. [(Prim 'eq? (list arg1 arg2))
  11598. (define-values (e1 t1) (recur arg1))
  11599. (define-values (e2 t2) (recur arg2))
  11600. (match* (t1 t2)
  11601. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11602. [(other wise) (check-type-equal? t1 t2 e)])
  11603. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11604. [else ((super type-check-exp env) e)]
  11605. )))
  11606. ))
  11607. (define (type-check-Lvec p)
  11608. (send (new type-check-Lvec-class) type-check-program p))
  11609. \end{lstlisting}
  11610. \fi}
  11611. {\if\edition\pythonEd\pythonColor
  11612. \begin{lstlisting}
  11613. class TypeCheckLtup(TypeCheckLwhile):
  11614. def type_check_exp(self, e, env):
  11615. match e:
  11616. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11617. l = self.type_check_exp(left, env)
  11618. r = self.type_check_exp(right, env)
  11619. check_type_equal(l, r, e)
  11620. return bool
  11621. case Tuple(es, Load()):
  11622. ts = [self.type_check_exp(e, env) for e in es]
  11623. e.has_type = TupleType(ts)
  11624. return e.has_type
  11625. case Subscript(tup, Constant(i), Load()):
  11626. tup_ty = self.type_check_exp(tup, env)
  11627. i_ty = self.type_check_exp(Constant(i), env)
  11628. check_type_equal(i_ty, int, i)
  11629. match tup_ty:
  11630. case TupleType(ts):
  11631. return ts[i]
  11632. case _:
  11633. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11634. case _:
  11635. return super().type_check_exp(e, env)
  11636. \end{lstlisting}
  11637. \fi}
  11638. \end{tcolorbox}
  11639. \caption{Type checker for the \LangVec{} language.}
  11640. \label{fig:type-check-Lvec}
  11641. \end{figure}
  11642. \section{Garbage Collection}
  11643. \label{sec:GC}
  11644. Garbage collection is a runtime technique for reclaiming space on the
  11645. heap that will not be used in the future of the running program. We
  11646. use the term \emph{object}\index{subject}{object} to refer to any
  11647. value that is stored in the heap, which for now includes only
  11648. tuples.%
  11649. %
  11650. \footnote{The term \emph{object} as it is used in the context of
  11651. object-oriented programming has a more specific meaning than the
  11652. way in which we use the term here.}
  11653. %
  11654. Unfortunately, it is impossible to know precisely which objects will
  11655. be accessed in the future and which will not. Instead, garbage
  11656. collectors overapproximate the set of objects that will be accessed by
  11657. identifying which objects can possibly be accessed. The running
  11658. program can directly access objects that are in registers and on the
  11659. procedure call stack. It can also transitively access the elements of
  11660. tuples, starting with a tuple whose address is in a register or on the
  11661. procedure call stack. We define the \emph{root
  11662. set}\index{subject}{root set} to be all the tuple addresses that are
  11663. in registers or on the procedure call stack. We define the \emph{live
  11664. objects}\index{subject}{live objects} to be the objects that are
  11665. reachable from the root set. Garbage collectors reclaim the space that
  11666. is allocated to objects that are no longer live. \index{subject}{allocate}
  11667. That means that some objects may not get reclaimed as soon as they could be,
  11668. but at least
  11669. garbage collectors do not reclaim the space dedicated to objects that
  11670. will be accessed in the future! The programmer can influence which
  11671. objects get reclaimed by causing them to become unreachable.
  11672. So the goal of the garbage collector is twofold:
  11673. \begin{enumerate}
  11674. \item to preserve all the live objects, and
  11675. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11676. \end{enumerate}
  11677. \subsection{Two-Space Copying Collector}
  11678. Here we study a relatively simple algorithm for garbage collection
  11679. that is the basis of many state-of-the-art garbage
  11680. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11681. particular, we describe a two-space copying
  11682. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11683. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11684. collector} \index{subject}{two-space copying collector}
  11685. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11686. what happens in a two-space collector, showing two time steps, prior
  11687. to garbage collection (on the top) and after garbage collection (on
  11688. the bottom). In a two-space collector, the heap is divided into two
  11689. parts named the FromSpace\index{subject}{FromSpace} and the
  11690. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11691. FromSpace until there is not enough room for the next allocation
  11692. request. At that point, the garbage collector goes to work to make
  11693. room for the next allocation.
  11694. A copying collector makes more room by copying all the live objects
  11695. from the FromSpace into the ToSpace and then performs a sleight of
  11696. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11697. as the new ToSpace. In the example shown in
  11698. figure~\ref{fig:copying-collector}, the root set consists of three
  11699. pointers, one in a register and two on the stack. All the live
  11700. objects have been copied to the ToSpace (the right-hand side of
  11701. figure~\ref{fig:copying-collector}) in a way that preserves the
  11702. pointer relationships. For example, the pointer in the register still
  11703. points to a tuple that in turn points to two other tuples. There are
  11704. four tuples that are not reachable from the root set and therefore do
  11705. not get copied into the ToSpace.
  11706. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11707. created by a well-typed program in \LangVec{} because it contains a
  11708. cycle. However, creating cycles will be possible once we get to
  11709. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11710. to deal with cycles to begin with, so we will not need to revisit this
  11711. issue.
  11712. \begin{figure}[tbp]
  11713. \centering
  11714. \begin{tcolorbox}[colback=white]
  11715. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11716. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11717. \\[5ex]
  11718. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11719. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11720. \end{tcolorbox}
  11721. \caption{A copying collector in action.}
  11722. \label{fig:copying-collector}
  11723. \end{figure}
  11724. \subsection{Graph Copying via Cheney's Algorithm}
  11725. \label{sec:cheney}
  11726. \index{subject}{Cheney's algorithm}
  11727. Let us take a closer look at the copying of the live objects. The
  11728. allocated\index{subject}{allocate} objects and pointers can be viewed
  11729. as a graph, and we need to copy the part of the graph that is
  11730. reachable from the root set. To make sure that we copy all the
  11731. reachable vertices in the graph, we need an exhaustive graph traversal
  11732. algorithm, such as depth-first search or breadth-first
  11733. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11734. take into account the possibility of cycles by marking which vertices
  11735. have already been visited, so to ensure termination of the
  11736. algorithm. These search algorithms also use a data structure such as a
  11737. stack or queue as a to-do list to keep track of the vertices that need
  11738. to be visited. We use breadth-first search and a trick due to
  11739. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11740. copying tuples into the ToSpace.
  11741. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11742. copy progresses. The queue is represented by a chunk of contiguous
  11743. memory at the beginning of the ToSpace, using two pointers to track
  11744. the front and the back of the queue, called the \emph{free pointer}
  11745. and the \emph{scan pointer}, respectively. The algorithm starts by
  11746. copying all tuples that are immediately reachable from the root set
  11747. into the ToSpace to form the initial queue. When we copy a tuple, we
  11748. mark the old tuple to indicate that it has been visited. We discuss
  11749. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11750. that any pointers inside the copied tuples in the queue still point
  11751. back to the FromSpace. Once the initial queue has been created, the
  11752. algorithm enters a loop in which it repeatedly processes the tuple at
  11753. the front of the queue and pops it off the queue. To process a tuple,
  11754. the algorithm copies all the objects that are directly reachable from it
  11755. to the ToSpace, placing them at the back of the queue. The algorithm
  11756. then updates the pointers in the popped tuple so that they point to the
  11757. newly copied objects.
  11758. \begin{figure}[tbp]
  11759. \centering
  11760. \begin{tcolorbox}[colback=white]
  11761. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11762. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11763. \end{tcolorbox}
  11764. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11765. \label{fig:cheney}
  11766. \end{figure}
  11767. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11768. tuple whose second element is $42$ to the back of the queue. The other
  11769. pointer goes to a tuple that has already been copied, so we do not
  11770. need to copy it again, but we do need to update the pointer to the new
  11771. location. This can be accomplished by storing a \emph{forwarding
  11772. pointer}\index{subject}{forwarding pointer} to the new location in the
  11773. old tuple, when we initially copied the tuple into the
  11774. ToSpace. This completes one step of the algorithm. The algorithm
  11775. continues in this way until the queue is empty; that is, when the scan
  11776. pointer catches up with the free pointer.
  11777. \subsection{Data Representation}
  11778. \label{sec:data-rep-gc}
  11779. The garbage collector places some requirements on the data
  11780. representations used by our compiler. First, the garbage collector
  11781. needs to distinguish between pointers and other kinds of data such as
  11782. integers. The following are three ways to accomplish this:
  11783. \begin{enumerate}
  11784. \item Attach a tag to each object that identifies what type of
  11785. object it is~\citep{McCarthy:1960dz}.
  11786. \item Store different types of objects in different
  11787. regions~\citep{Steele:1977ab}.
  11788. \item Use type information from the program to either (a) generate
  11789. type-specific code for collecting, or (b) generate tables that
  11790. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11791. \end{enumerate}
  11792. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11793. need to tag objects in any case, so option 1 is a natural choice for those
  11794. languages. However, \LangVec{} is a statically typed language, so it
  11795. would be unfortunate to require tags on every object, especially small
  11796. and pervasive objects like integers and Booleans. Option 3 is the
  11797. best-performing choice for statically typed languages, but it comes with
  11798. a relatively high implementation complexity. To keep this chapter
  11799. within a reasonable scope of complexity, we recommend a combination of options
  11800. 1 and 2, using separate strategies for the stack and the heap.
  11801. Regarding the stack, we recommend using a separate stack for pointers,
  11802. which we call the \emph{root stack}\index{subject}{root stack}
  11803. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11804. That is, when a local variable needs to be spilled and is of type
  11805. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11806. root stack instead of putting it on the procedure call
  11807. stack. Furthermore, we always spill tuple-typed variables if they are
  11808. live during a call to the collector, thereby ensuring that no pointers
  11809. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11810. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11811. contrasts it with the data layout using a root stack. The root stack
  11812. contains the two pointers from the regular stack and also the pointer
  11813. in the second register.
  11814. \begin{figure}[tbp]
  11815. \centering
  11816. \begin{tcolorbox}[colback=white]
  11817. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11818. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11819. \end{tcolorbox}
  11820. \caption{Maintaining a root stack to facilitate garbage collection.}
  11821. \label{fig:shadow-stack}
  11822. \end{figure}
  11823. The problem of distinguishing between pointers and other kinds of data
  11824. also arises inside each tuple on the heap. We solve this problem by
  11825. attaching a tag, an extra 64 bits, to each
  11826. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11827. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11828. Note that we have drawn the bits in a big-endian way, from right to left,
  11829. with bit location 0 (the least significant bit) on the far right,
  11830. which corresponds to the direction of the x86 shifting instructions
  11831. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11832. is dedicated to specifying which elements of the tuple are pointers,
  11833. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11834. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11835. data. The pointer mask starts at bit location 7. We limit tuples to a
  11836. maximum size of fifty elements, so we need 50 bits for the pointer
  11837. mask.%
  11838. %
  11839. \footnote{A production-quality compiler would handle
  11840. arbitrarily sized tuples and use a more complex approach.}
  11841. %
  11842. The tag also contains two other pieces of information. The length of
  11843. the tuple (number of elements) is stored in bits at locations 1 through
  11844. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11845. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11846. has not yet been copied. If the bit has value 0, then the entire tag
  11847. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11848. zero in any case, because our tuples are 8-byte aligned.)
  11849. \begin{figure}[tbp]
  11850. \centering
  11851. \begin{tcolorbox}[colback=white]
  11852. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11853. \end{tcolorbox}
  11854. \caption{Representation of tuples in the heap.}
  11855. \label{fig:tuple-rep}
  11856. \end{figure}
  11857. \subsection{Implementation of the Garbage Collector}
  11858. \label{sec:organize-gz}
  11859. \index{subject}{prelude}
  11860. An implementation of the copying collector is provided in the
  11861. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11862. interface to the garbage collector that is used by the compiler. The
  11863. \code{initialize} function creates the FromSpace, ToSpace, and root
  11864. stack and should be called in the prelude of the \code{main}
  11865. function. The arguments of \code{initialize} are the root stack size
  11866. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11867. good choice for both. The \code{initialize} function puts the address
  11868. of the beginning of the FromSpace into the global variable
  11869. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11870. the address that is one past the last element of the FromSpace. We use
  11871. half-open intervals to represent chunks of
  11872. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11873. points to the first element of the root stack.
  11874. As long as there is room left in the FromSpace, your generated code
  11875. can allocate\index{subject}{allocate} tuples simply by moving the
  11876. \code{free\_ptr} forward.
  11877. %
  11878. The amount of room left in the FromSpace is the difference between the
  11879. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11880. function should be called when there is not enough room left in the
  11881. FromSpace for the next allocation. The \code{collect} function takes
  11882. a pointer to the current top of the root stack (one past the last item
  11883. that was pushed) and the number of bytes that need to be
  11884. allocated. The \code{collect} function performs the copying collection
  11885. and leaves the heap in a state such that there is enough room for the
  11886. next allocation.
  11887. \begin{figure}[tbp]
  11888. \begin{tcolorbox}[colback=white]
  11889. \begin{lstlisting}
  11890. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11891. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11892. int64_t* free_ptr;
  11893. int64_t* fromspace_begin;
  11894. int64_t* fromspace_end;
  11895. int64_t** rootstack_begin;
  11896. \end{lstlisting}
  11897. \end{tcolorbox}
  11898. \caption{The compiler's interface to the garbage collector.}
  11899. \label{fig:gc-header}
  11900. \end{figure}
  11901. %% \begin{exercise}
  11902. %% In the file \code{runtime.c} you will find the implementation of
  11903. %% \code{initialize} and a partial implementation of \code{collect}.
  11904. %% The \code{collect} function calls another function, \code{cheney},
  11905. %% to perform the actual copy, and that function is left to the reader
  11906. %% to implement. The following is the prototype for \code{cheney}.
  11907. %% \begin{lstlisting}
  11908. %% static void cheney(int64_t** rootstack_ptr);
  11909. %% \end{lstlisting}
  11910. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11911. %% rootstack (which is an array of pointers). The \code{cheney} function
  11912. %% also communicates with \code{collect} through the global
  11913. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11914. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11915. %% the ToSpace:
  11916. %% \begin{lstlisting}
  11917. %% static int64_t* tospace_begin;
  11918. %% static int64_t* tospace_end;
  11919. %% \end{lstlisting}
  11920. %% The job of the \code{cheney} function is to copy all the live
  11921. %% objects (reachable from the root stack) into the ToSpace, update
  11922. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11923. %% update the root stack so that it points to the objects in the
  11924. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11925. %% and ToSpace.
  11926. %% \end{exercise}
  11927. The introduction of garbage collection has a nontrivial impact on our
  11928. compiler passes. We introduce a new compiler pass named
  11929. \code{expose\_allocation} that elaborates the code for allocating
  11930. tuples. We also make significant changes to
  11931. \code{select\_instructions}, \code{build\_interference},
  11932. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11933. make minor changes in several more passes.
  11934. The following program serves as our running example. It creates
  11935. two tuples, one nested inside the other. Both tuples have length
  11936. one. The program accesses the element in the inner tuple.
  11937. % tests/vectors_test_17.rkt
  11938. {\if\edition\racketEd
  11939. \begin{lstlisting}
  11940. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11941. \end{lstlisting}
  11942. \fi}
  11943. % tests/tuple/get_get.py
  11944. {\if\edition\pythonEd\pythonColor
  11945. \begin{lstlisting}
  11946. v1 = (42,)
  11947. v2 = (v1,)
  11948. print(v2[0][0])
  11949. \end{lstlisting}
  11950. \fi}
  11951. %% {\if\edition\racketEd
  11952. %% \section{Shrink}
  11953. %% \label{sec:shrink-Lvec}
  11954. %% Recall that the \code{shrink} pass translates the primitives operators
  11955. %% into a smaller set of primitives.
  11956. %% %
  11957. %% This pass comes after type checking, and the type checker adds a
  11958. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11959. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11960. %% \fi}
  11961. \section{Expose Allocation}
  11962. \label{sec:expose-allocation}
  11963. The pass \code{expose\_allocation} lowers tuple creation into making a
  11964. conditional call to the collector followed by allocating the
  11965. appropriate amount of memory and initializing it. We choose to place
  11966. the \code{expose\_allocation} pass before
  11967. \code{remove\_complex\_operands} because it generates code that
  11968. contains complex operands. However, with some care it can also be
  11969. placed after \code{remove\_complex\_operands}, which would simplify
  11970. tuple creation by removing the need to assign the initializing
  11971. expressions to temporary variables (see below).
  11972. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11973. that replaces tuple creation with new lower-level forms that we use in the
  11974. translation of tuple creation\index{subject}{Lalloc@\LangAlloc{}}.
  11975. %
  11976. {\if\edition\racketEd
  11977. \[
  11978. \begin{array}{lcl}
  11979. \Exp &::=& (\key{collect} \,\itm{int})
  11980. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11981. \MID (\key{global-value} \,\itm{name})
  11982. \end{array}
  11983. \]
  11984. \fi}
  11985. {\if\edition\pythonEd\pythonColor
  11986. \[
  11987. \begin{array}{lcl}
  11988. \Exp &::=& \key{collect}(\itm{int})
  11989. \MID \key{allocate}(\itm{int},\itm{type})
  11990. \MID \key{global\_value}(\itm{name}) \\
  11991. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11992. \end{array}
  11993. \]
  11994. \fi}
  11995. %
  11996. The \CCOLLECT{$n$} form runs the garbage collector, requesting that
  11997. there be $n$ bytes ready to be allocated. During instruction
  11998. selection\index{subject}{instruction selection}, the \CCOLLECT{$n$}
  11999. form will become a call to the \code{collect} function in
  12000. \code{runtime.c}.
  12001. %
  12002. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  12003. space at the front for the 64-bit tag), but the elements are not
  12004. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  12005. of the tuple:
  12006. %
  12007. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  12008. %
  12009. where $\Type_i$ is the type of the $i$th element.
  12010. %
  12011. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  12012. variable, such as \code{free\_ptr}.
  12013. \racket{
  12014. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  12015. can be obtained by running the
  12016. \code{type-check-Lvec-has-type} type checker immediately before the
  12017. \code{expose\_allocation} pass. This version of the type checker
  12018. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  12019. around each tuple creation. The concrete syntax
  12020. for \code{HasType} is \code{has-type}.}
  12021. The following shows the transformation of tuple creation into (1) a
  12022. sequence of temporary variable bindings for the initializing
  12023. expressions, (2) a conditional call to \code{collect}, (3) a call to
  12024. \code{allocate}, and (4) the initialization of the tuple. The
  12025. \itm{len} placeholder refers to the length of the tuple, and
  12026. \itm{bytes} is the total number of bytes that need to be allocated for
  12027. the tuple, which is 8 for the tag plus \itm{len} times 8.
  12028. %
  12029. \python{The \itm{type} needed for the second argument of the
  12030. \code{allocate} form can be obtained from the \code{has\_type} field
  12031. of the tuple AST node, which is stored there by running the type
  12032. checker for \LangVec{} immediately before this pass.}
  12033. %
  12034. \begin{center}
  12035. \begin{minipage}{\textwidth}
  12036. {\if\edition\racketEd
  12037. \begin{lstlisting}
  12038. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12039. |$\Longrightarrow$|
  12040. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12041. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12042. (global-value fromspace_end))
  12043. (void)
  12044. (collect |\itm{bytes}|))])
  12045. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12046. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12047. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12048. |$v$|) ... )))) ...)
  12049. \end{lstlisting}
  12050. \fi}
  12051. {\if\edition\pythonEd\pythonColor
  12052. \begin{lstlisting}
  12053. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12054. |$\Longrightarrow$|
  12055. begin:
  12056. |$x_0$| = |$e_0$|
  12057. |$\vdots$|
  12058. |$x_{n-1}$| = |$e_{n-1}$|
  12059. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12060. 0
  12061. else:
  12062. collect(|\itm{bytes}|)
  12063. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12064. |$v$|[0] = |$x_0$|
  12065. |$\vdots$|
  12066. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12067. |$v$|
  12068. \end{lstlisting}
  12069. \fi}
  12070. \end{minipage}
  12071. \end{center}
  12072. %
  12073. \noindent The sequencing of the initializing expressions
  12074. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12075. they may trigger garbage collection and we cannot have an allocated
  12076. but uninitialized tuple on the heap during a collection.
  12077. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12078. \code{expose\_allocation} pass on our running example.
  12079. \begin{figure}[tbp]
  12080. \begin{tcolorbox}[colback=white]
  12081. % tests/s2_17.rkt
  12082. {\if\edition\racketEd
  12083. \begin{lstlisting}
  12084. (vector-ref
  12085. (vector-ref
  12086. (let ([vecinit6
  12087. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12088. (global-value fromspace_end))
  12089. (void)
  12090. (collect 16))])
  12091. (let ([alloc2 (allocate 1 (Vector Integer))])
  12092. (let ([_3 (vector-set! alloc2 0 42)])
  12093. alloc2)))])
  12094. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12095. (global-value fromspace_end))
  12096. (void)
  12097. (collect 16))])
  12098. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12099. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12100. alloc5))))
  12101. 0)
  12102. 0)
  12103. \end{lstlisting}
  12104. \fi}
  12105. {\if\edition\pythonEd\pythonColor
  12106. \begin{lstlisting}
  12107. v1 = begin:
  12108. init.514 = 42
  12109. if (free_ptr + 16) < fromspace_end:
  12110. else:
  12111. collect(16)
  12112. alloc.513 = allocate(1,tuple[int])
  12113. alloc.513[0] = init.514
  12114. alloc.513
  12115. v2 = begin:
  12116. init.516 = v1
  12117. if (free_ptr + 16) < fromspace_end:
  12118. else:
  12119. collect(16)
  12120. alloc.515 = allocate(1,tuple[tuple[int]])
  12121. alloc.515[0] = init.516
  12122. alloc.515
  12123. print(v2[0][0])
  12124. \end{lstlisting}
  12125. \fi}
  12126. \end{tcolorbox}
  12127. \caption{Output of the \code{expose\_allocation} pass.}
  12128. \label{fig:expose-alloc-output}
  12129. \end{figure}
  12130. \section{Remove Complex Operands}
  12131. \label{sec:remove-complex-opera-Lvec}
  12132. {\if\edition\racketEd
  12133. %
  12134. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12135. should be treated as complex operands.
  12136. %
  12137. \fi}
  12138. %
  12139. {\if\edition\pythonEd\pythonColor
  12140. %
  12141. The expressions \code{allocate}, \code{begin},
  12142. and tuple access should be treated as complex operands. The
  12143. subexpressions of tuple access must be atomic.
  12144. The \code{global\_value} AST node is atomic.
  12145. %
  12146. \fi}
  12147. %% A new case for
  12148. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12149. %% handled carefully to prevent the \code{Prim} node from being separated
  12150. %% from its enclosing \code{HasType}.
  12151. Figure~\ref{fig:Lvec-anf-syntax}
  12152. shows the grammar for the output language \LangAllocANF{} of this
  12153. pass, which is \LangAlloc{} in monadic normal form.
  12154. \newcommand{\LtupMonadASTRacket}{
  12155. \begin{array}{rcl}
  12156. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12157. \MID \GLOBALVALUE{\Var}
  12158. \end{array}
  12159. }
  12160. \newcommand{\LtupMonadASTPython}{
  12161. \begin{array}{rcl}
  12162. \Atm &::=& \GLOBALVALUE{\Var} \\
  12163. \Exp &::=& \GET{\Atm}{\Atm}
  12164. \MID \LEN{\Atm}\\
  12165. &\MID& \ALLOCATE{\Int}{\Type}\\
  12166. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12167. &\MID& \COLLECT{\Int}
  12168. \end{array}
  12169. }
  12170. \begin{figure}[tp]
  12171. \centering
  12172. \begin{tcolorbox}[colback=white]
  12173. \small
  12174. {\if\edition\racketEd
  12175. \[
  12176. \begin{array}{l}
  12177. \gray{\LvarMonadASTRacket} \\ \hline
  12178. \gray{\LifMonadASTRacket} \\ \hline
  12179. \gray{\LwhileMonadASTRacket} \\ \hline
  12180. \LtupMonadASTRacket \\
  12181. \begin{array}{rcl}
  12182. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12183. \end{array}
  12184. \end{array}
  12185. \]
  12186. \fi}
  12187. {\if\edition\pythonEd\pythonColor
  12188. \[
  12189. \begin{array}{l}
  12190. \gray{\LvarMonadASTPython} \\ \hline
  12191. \gray{\LifMonadASTPython} \\ \hline
  12192. \gray{\LwhileMonadASTPython} \\ \hline
  12193. \LtupMonadASTPython \\
  12194. \begin{array}{rcl}
  12195. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12196. \end{array}
  12197. \end{array}
  12198. \]
  12199. \fi}
  12200. \end{tcolorbox}
  12201. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12202. \label{fig:Lvec-anf-syntax}
  12203. \index{subject}{Ltupmon@\LangAllocANF{} abstract syntax}
  12204. \end{figure}
  12205. \section{Explicate Control and the \LangCVec{} Language}
  12206. \label{sec:explicate-control-r3}
  12207. \newcommand{\CtupASTRacket}{
  12208. \begin{array}{lcl}
  12209. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12210. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12211. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12212. &\MID& \VECLEN{\Atm} \\
  12213. &\MID& \GLOBALVALUE{\Var} \\
  12214. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12215. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12216. \end{array}
  12217. }
  12218. \newcommand{\CtupASTPython}{
  12219. \begin{array}{lcl}
  12220. \Atm &::=& \GLOBALVALUE{\Var} \\
  12221. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12222. &\MID& \LEN{\Atm} \\
  12223. \Stmt &::=& \COLLECT{\Int}
  12224. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12225. \end{array}
  12226. }
  12227. \begin{figure}[tp]
  12228. \begin{tcolorbox}[colback=white]
  12229. \small
  12230. {\if\edition\racketEd
  12231. \[
  12232. \begin{array}{l}
  12233. \gray{\CvarASTRacket} \\ \hline
  12234. \gray{\CifASTRacket} \\ \hline
  12235. \gray{\CloopASTRacket} \\ \hline
  12236. \CtupASTRacket \\
  12237. \begin{array}{lcl}
  12238. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12239. \end{array}
  12240. \end{array}
  12241. \]
  12242. \fi}
  12243. {\if\edition\pythonEd\pythonColor
  12244. \[
  12245. \begin{array}{l}
  12246. \gray{\CifASTPython} \\ \hline
  12247. \CtupASTPython \\
  12248. \begin{array}{lcl}
  12249. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12250. \end{array}
  12251. \end{array}
  12252. \]
  12253. \fi}
  12254. \end{tcolorbox}
  12255. \caption{The abstract syntax of \LangCVec{}, extending
  12256. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12257. (figure~\ref{fig:c1-syntax})}.}
  12258. \label{fig:c2-syntax}
  12259. \index{subject}{Cvec@\LangCVec{} abstract syntax}
  12260. \end{figure}
  12261. The output of \code{explicate\_control} is a program in the
  12262. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12263. shows the definition of the abstract syntax.
  12264. %
  12265. %% \racket{(The concrete syntax is defined in
  12266. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12267. %
  12268. The new expressions of \LangCVec{} include \key{allocate},
  12269. %
  12270. \racket{\key{vector-ref}, and \key{vector-set!},}
  12271. %
  12272. \python{accessing tuple elements,}
  12273. %
  12274. and \key{global\_value}.
  12275. %
  12276. \python{\LangCVec{} also includes the \code{collect} statement and
  12277. assignment to a tuple element.}
  12278. %
  12279. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12280. %
  12281. The \code{explicate\_control} pass can treat these new forms much like
  12282. the other forms that we've already encountered. The output of the
  12283. \code{explicate\_control} pass on the running example is shown on the
  12284. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12285. section.
  12286. \section{Select Instructions and the \LangXGlobal{} Language}
  12287. \label{sec:select-instructions-gc}
  12288. \index{subject}{select instructions}
  12289. %% void (rep as zero)
  12290. %% allocate
  12291. %% collect (callq collect)
  12292. %% vector-ref
  12293. %% vector-set!
  12294. %% vector-length
  12295. %% global (postpone)
  12296. In this pass we generate x86 code for most of the new operations that
  12297. are needed to compile tuples, including \code{Allocate},
  12298. \code{Collect}, accessing tuple elements, and the \code{Is}
  12299. comparison.
  12300. %
  12301. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12302. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12303. \ref{fig:x86-2}). \index{subject}{x86}
  12304. The tuple read and write forms translate into \code{movq}
  12305. instructions. (The $+1$ in the offset serves to move past the tag at the
  12306. beginning of the tuple representation.)
  12307. %
  12308. \begin{center}
  12309. \begin{minipage}{\textwidth}
  12310. {\if\edition\racketEd
  12311. \begin{lstlisting}
  12312. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12313. |$\Longrightarrow$|
  12314. movq |$\itm{tup}'$|, %r11
  12315. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12316. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12317. |$\Longrightarrow$|
  12318. movq |$\itm{tup}'$|, %r11
  12319. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12320. movq $0, |$\itm{lhs'}$|
  12321. \end{lstlisting}
  12322. \fi}
  12323. {\if\edition\pythonEd\pythonColor
  12324. \begin{lstlisting}
  12325. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12326. |$\Longrightarrow$|
  12327. movq |$\itm{tup}'$|, %r11
  12328. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12329. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12330. |$\Longrightarrow$|
  12331. movq |$\itm{tup}'$|, %r11
  12332. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12333. \end{lstlisting}
  12334. \fi}
  12335. \end{minipage}
  12336. \end{center}
  12337. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12338. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12339. are obtained by translating from \LangCVec{} to x86.
  12340. %
  12341. The move of $\itm{tup}'$ to
  12342. register \code{r11} ensures that the offset expression
  12343. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12344. removing \code{r11} from consideration by the register allocator.
  12345. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12346. \code{rax}. Then the generated code for tuple assignment would be
  12347. \begin{lstlisting}
  12348. movq |$\itm{tup}'$|, %rax
  12349. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12350. \end{lstlisting}
  12351. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12352. \code{patch\_instructions} would insert a move through \code{rax}
  12353. as follows:
  12354. \begin{lstlisting}
  12355. movq |$\itm{tup}'$|, %rax
  12356. movq |$\itm{rhs}'$|, %rax
  12357. movq %rax, |$8(n+1)$|(%rax)
  12358. \end{lstlisting}
  12359. However, this sequence of instructions does not work because we're
  12360. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12361. $\itm{rhs}'$) at the same time!
  12362. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12363. be translated into a sequence of instructions that read the tag of the
  12364. tuple and extract the 6 bits that represent the tuple length, which
  12365. are the bits starting at index 1 and going up to and including bit 6.
  12366. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12367. (shift right) can be used to accomplish this.
  12368. We compile the \code{allocate} form to operations on the
  12369. \code{free\_ptr}, as shown next. This approach is called
  12370. \emph{inline allocation} because it implements allocation without a
  12371. function call by simply incrementing the allocation pointer. It is much
  12372. more efficient than calling a function for each allocation. The
  12373. address in the \code{free\_ptr} is the next free address in the
  12374. FromSpace, so we copy it into \code{r11} and then move it forward by
  12375. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12376. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12377. the tag. We then initialize the \itm{tag} and finally copy the
  12378. address in \code{r11} to the left-hand side. Refer to
  12379. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12380. %
  12381. \racket{We recommend using the Racket operations
  12382. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12383. during compilation.}
  12384. %
  12385. \python{We recommend using the bitwise-or operator \code{|} and the
  12386. shift-left operator \code{<<} to compute the tag during
  12387. compilation.}
  12388. %
  12389. The type annotation in the \code{allocate} form is used to determine
  12390. the pointer mask region of the tag.
  12391. %
  12392. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12393. address of the \code{free\_ptr} global variable using a special
  12394. instruction-pointer-relative addressing mode of the x86-64 processor.
  12395. In particular, the assembler computes the distance $d$ between the
  12396. address of \code{free\_ptr} and where the \code{rip} would be at that
  12397. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12398. \code{$d$(\%rip)}, which at runtime will compute the address of
  12399. \code{free\_ptr}.
  12400. %
  12401. {\if\edition\racketEd
  12402. \begin{lstlisting}
  12403. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12404. |$\Longrightarrow$|
  12405. movq free_ptr(%rip), %r11
  12406. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12407. movq $|$\itm{tag}$|, 0(%r11)
  12408. movq %r11, |$\itm{lhs}'$|
  12409. \end{lstlisting}
  12410. \fi}
  12411. {\if\edition\pythonEd\pythonColor
  12412. \begin{lstlisting}
  12413. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12414. |$\Longrightarrow$|
  12415. movq free_ptr(%rip), %r11
  12416. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12417. movq $|$\itm{tag}$|, 0(%r11)
  12418. movq %r11, |$\itm{lhs}'$|
  12419. \end{lstlisting}
  12420. \fi}
  12421. %
  12422. The \code{collect} form is compiled to a call to the \code{collect}
  12423. function in the runtime. The arguments to \code{collect} are (1) the
  12424. top of the root stack, and (2) the number of bytes that need to be
  12425. allocated. We use another dedicated register, \code{r15}, to store
  12426. the pointer to the top of the root stack. Therefore \code{r15} is not
  12427. available for use by the register allocator.
  12428. %
  12429. {\if\edition\racketEd
  12430. \begin{lstlisting}
  12431. (collect |$\itm{bytes}$|)
  12432. |$\Longrightarrow$|
  12433. movq %r15, %rdi
  12434. movq $|\itm{bytes}|, %rsi
  12435. callq collect
  12436. \end{lstlisting}
  12437. \fi}
  12438. {\if\edition\pythonEd\pythonColor
  12439. \begin{lstlisting}
  12440. collect(|$\itm{bytes}$|)
  12441. |$\Longrightarrow$|
  12442. movq %r15, %rdi
  12443. movq $|\itm{bytes}|, %rsi
  12444. callq collect
  12445. \end{lstlisting}
  12446. \fi}
  12447. {\if\edition\pythonEd\pythonColor
  12448. The \code{is} comparison is compiled similarly to the other comparison
  12449. operators, using the \code{cmpq} instruction. Because the value of a
  12450. tuple is its address, we can translate \code{is} into a simple check
  12451. for equality using the \code{e} condition code. \\
  12452. \begin{tabular}{lll}
  12453. \begin{minipage}{0.4\textwidth}
  12454. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12455. \end{minipage}
  12456. &
  12457. $\Rightarrow$
  12458. &
  12459. \begin{minipage}{0.4\textwidth}
  12460. \begin{lstlisting}
  12461. cmpq |$\Arg_2$|, |$\Arg_1$|
  12462. sete %al
  12463. movzbq %al, |$\Var$|
  12464. \end{lstlisting}
  12465. \end{minipage}
  12466. \end{tabular}
  12467. \fi}
  12468. \newcommand{\GrammarXGlobal}{
  12469. \begin{array}{lcl}
  12470. \Arg &::=& \itm{label} \key{(\%rip)}
  12471. \end{array}
  12472. }
  12473. \newcommand{\ASTXGlobalRacket}{
  12474. \begin{array}{lcl}
  12475. \Arg &::=& \GLOBAL{\itm{label}}
  12476. \end{array}
  12477. }
  12478. \begin{figure}[tp]
  12479. \begin{tcolorbox}[colback=white]
  12480. \[
  12481. \begin{array}{l}
  12482. \gray{\GrammarXInt} \\ \hline
  12483. \gray{\GrammarXIf} \\ \hline
  12484. \GrammarXGlobal \\
  12485. \begin{array}{lcl}
  12486. \LangXGlobalM{} &::= & \key{.globl main} \\
  12487. & & \key{main:} \; \Instr^{*}
  12488. \end{array}
  12489. \end{array}
  12490. \]
  12491. \end{tcolorbox}
  12492. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12493. \label{fig:x86-2-concrete}
  12494. \end{figure}
  12495. \begin{figure}[tp]
  12496. \begin{tcolorbox}[colback=white]
  12497. \small
  12498. {\if\edition\racketEd
  12499. \[
  12500. \begin{array}{l}
  12501. \gray{\ASTXIntRacket} \\ \hline
  12502. \gray{\ASTXIfRacket} \\ \hline
  12503. \ASTXGlobalRacket \\
  12504. \begin{array}{lcl}
  12505. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12506. \end{array}
  12507. \end{array}
  12508. \]
  12509. \fi}
  12510. {\if\edition\pythonEd\pythonColor
  12511. \[
  12512. \begin{array}{l}
  12513. \gray{\ASTXIntPython} \\ \hline
  12514. \gray{\ASTXIfPython} \\ \hline
  12515. \ASTXGlobalRacket \\
  12516. \begin{array}{lcl}
  12517. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12518. \end{array}
  12519. \end{array}
  12520. \]
  12521. \fi}
  12522. \end{tcolorbox}
  12523. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12524. \label{fig:x86-2}
  12525. \end{figure}
  12526. The definitions of the concrete and abstract syntax of the
  12527. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12528. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12529. of global variables.
  12530. %
  12531. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12532. \code{select\_instructions} pass on the running example.
  12533. \begin{figure}[tbp]
  12534. \centering
  12535. \begin{tcolorbox}[colback=white]
  12536. {\if\edition\racketEd
  12537. % tests/s2_17.rkt
  12538. \begin{tabular}{lll}
  12539. \begin{minipage}{0.5\textwidth}
  12540. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12541. start:
  12542. tmp9 = (global-value free_ptr);
  12543. tmp0 = (+ tmp9 16);
  12544. tmp1 = (global-value fromspace_end);
  12545. if (< tmp0 tmp1)
  12546. goto block0;
  12547. else
  12548. goto block1;
  12549. block0:
  12550. _4 = (void);
  12551. goto block9;
  12552. block1:
  12553. (collect 16)
  12554. goto block9;
  12555. block9:
  12556. alloc2 = (allocate 1 (Vector Integer));
  12557. _3 = (vector-set! alloc2 0 42);
  12558. vecinit6 = alloc2;
  12559. tmp2 = (global-value free_ptr);
  12560. tmp3 = (+ tmp2 16);
  12561. tmp4 = (global-value fromspace_end);
  12562. if (< tmp3 tmp4)
  12563. goto block7;
  12564. else
  12565. goto block8;
  12566. block7:
  12567. _8 = (void);
  12568. goto block6;
  12569. block8:
  12570. (collect 16)
  12571. goto block6;
  12572. block6:
  12573. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12574. _7 = (vector-set! alloc5 0 vecinit6);
  12575. tmp5 = (vector-ref alloc5 0);
  12576. return (vector-ref tmp5 0);
  12577. \end{lstlisting}
  12578. \end{minipage}
  12579. &$\Rightarrow$&
  12580. \begin{minipage}{0.4\textwidth}
  12581. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12582. start:
  12583. movq free_ptr(%rip), tmp9
  12584. movq tmp9, tmp0
  12585. addq $16, tmp0
  12586. movq fromspace_end(%rip), tmp1
  12587. cmpq tmp1, tmp0
  12588. jl block0
  12589. jmp block1
  12590. block0:
  12591. movq $0, _4
  12592. jmp block9
  12593. block1:
  12594. movq %r15, %rdi
  12595. movq $16, %rsi
  12596. callq collect
  12597. jmp block9
  12598. block9:
  12599. movq free_ptr(%rip), %r11
  12600. addq $16, free_ptr(%rip)
  12601. movq $3, 0(%r11)
  12602. movq %r11, alloc2
  12603. movq alloc2, %r11
  12604. movq $42, 8(%r11)
  12605. movq $0, _3
  12606. movq alloc2, vecinit6
  12607. movq free_ptr(%rip), tmp2
  12608. movq tmp2, tmp3
  12609. addq $16, tmp3
  12610. movq fromspace_end(%rip), tmp4
  12611. cmpq tmp4, tmp3
  12612. jl block7
  12613. jmp block8
  12614. block7:
  12615. movq $0, _8
  12616. jmp block6
  12617. block8:
  12618. movq %r15, %rdi
  12619. movq $16, %rsi
  12620. callq collect
  12621. jmp block6
  12622. block6:
  12623. movq free_ptr(%rip), %r11
  12624. addq $16, free_ptr(%rip)
  12625. movq $131, 0(%r11)
  12626. movq %r11, alloc5
  12627. movq alloc5, %r11
  12628. movq vecinit6, 8(%r11)
  12629. movq $0, _7
  12630. movq alloc5, %r11
  12631. movq 8(%r11), tmp5
  12632. movq tmp5, %r11
  12633. movq 8(%r11), %rax
  12634. jmp conclusion
  12635. \end{lstlisting}
  12636. \end{minipage}
  12637. \end{tabular}
  12638. \fi}
  12639. {\if\edition\pythonEd
  12640. % tests/tuple/get_get.py
  12641. \begin{tabular}{lll}
  12642. \begin{minipage}{0.5\textwidth}
  12643. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12644. start:
  12645. init.514 = 42
  12646. tmp.517 = free_ptr
  12647. tmp.518 = (tmp.517 + 16)
  12648. tmp.519 = fromspace_end
  12649. if tmp.518 < tmp.519:
  12650. goto block.529
  12651. else:
  12652. goto block.530
  12653. block.529:
  12654. goto block.528
  12655. block.530:
  12656. collect(16)
  12657. goto block.528
  12658. block.528:
  12659. alloc.513 = allocate(1,tuple[int])
  12660. alloc.513:tuple[int][0] = init.514
  12661. v1 = alloc.513
  12662. init.516 = v1
  12663. tmp.520 = free_ptr
  12664. tmp.521 = (tmp.520 + 16)
  12665. tmp.522 = fromspace_end
  12666. if tmp.521 < tmp.522:
  12667. goto block.526
  12668. else:
  12669. goto block.527
  12670. block.526:
  12671. goto block.525
  12672. block.527:
  12673. collect(16)
  12674. goto block.525
  12675. block.525:
  12676. alloc.515 = allocate(1,tuple[tuple[int]])
  12677. alloc.515:tuple[tuple[int]][0] = init.516
  12678. v2 = alloc.515
  12679. tmp.523 = v2[0]
  12680. tmp.524 = tmp.523[0]
  12681. print(tmp.524)
  12682. return 0
  12683. \end{lstlisting}
  12684. \end{minipage}
  12685. &$\Rightarrow$&
  12686. \begin{minipage}{0.4\textwidth}
  12687. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12688. start:
  12689. movq $42, init.514
  12690. movq free_ptr(%rip), tmp.517
  12691. movq tmp.517, tmp.518
  12692. addq $16, tmp.518
  12693. movq fromspace_end(%rip), tmp.519
  12694. cmpq tmp.519, tmp.518
  12695. jl block.529
  12696. jmp block.530
  12697. block.529:
  12698. jmp block.528
  12699. block.530:
  12700. movq %r15, %rdi
  12701. movq $16, %rsi
  12702. callq collect
  12703. jmp block.528
  12704. block.528:
  12705. movq free_ptr(%rip), %r11
  12706. addq $16, free_ptr(%rip)
  12707. movq $3, 0(%r11)
  12708. movq %r11, alloc.513
  12709. movq alloc.513, %r11
  12710. movq init.514, 8(%r11)
  12711. movq alloc.513, v1
  12712. movq v1, init.516
  12713. movq free_ptr(%rip), tmp.520
  12714. movq tmp.520, tmp.521
  12715. addq $16, tmp.521
  12716. movq fromspace_end(%rip), tmp.522
  12717. cmpq tmp.522, tmp.521
  12718. jl block.526
  12719. jmp block.527
  12720. block.526:
  12721. jmp block.525
  12722. block.527:
  12723. movq %r15, %rdi
  12724. movq $16, %rsi
  12725. callq collect
  12726. jmp block.525
  12727. block.525:
  12728. movq free_ptr(%rip), %r11
  12729. addq $16, free_ptr(%rip)
  12730. movq $131, 0(%r11)
  12731. movq %r11, alloc.515
  12732. movq alloc.515, %r11
  12733. movq init.516, 8(%r11)
  12734. movq alloc.515, v2
  12735. movq v2, %r11
  12736. movq 8(%r11), %r11
  12737. movq %r11, tmp.523
  12738. movq tmp.523, %r11
  12739. movq 8(%r11), %r11
  12740. movq %r11, tmp.524
  12741. movq tmp.524, %rdi
  12742. callq print_int
  12743. movq $0, %rax
  12744. jmp conclusion
  12745. \end{lstlisting}
  12746. \end{minipage}
  12747. \end{tabular}
  12748. \fi}
  12749. \end{tcolorbox}
  12750. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12751. \code{select\_instructions} (\emph{right}) on the running example.}
  12752. \label{fig:select-instr-output-gc}
  12753. \end{figure}
  12754. \clearpage
  12755. \section{Register Allocation}
  12756. \label{sec:reg-alloc-gc}
  12757. \index{subject}{register allocation}
  12758. As discussed previously in this chapter, the garbage collector needs to
  12759. access all the pointers in the root set, that is, all variables that
  12760. are tuples. It will be the responsibility of the register allocator
  12761. to make sure that
  12762. \begin{enumerate}
  12763. \item the root stack is used for spilling tuple-typed variables, and
  12764. \item if a tuple-typed variable is live during a call to the
  12765. collector, it must be spilled to ensure that it is visible to the
  12766. collector.
  12767. \end{enumerate}
  12768. The latter responsibility can be handled during construction of the
  12769. interference graph, by adding interference edges between the call-live
  12770. tuple-typed variables and all the callee-saved registers. (They
  12771. already interfere with the caller-saved registers.)
  12772. %
  12773. \racket{The type information for variables is in the \code{Program}
  12774. form, so we recommend adding another parameter to the
  12775. \code{build\_interference} function to communicate this alist.}
  12776. %
  12777. \python{The type information for variables is generated by the type
  12778. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12779. the \code{CProgram} AST mode. You'll need to propagate that
  12780. information so that it is available in this pass.}
  12781. The spilling of tuple-typed variables to the root stack can be handled
  12782. after graph coloring, in choosing how to assign the colors
  12783. (integers) to registers and stack locations. The
  12784. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12785. changes to also record the number of spills to the root stack.
  12786. % build-interference
  12787. %
  12788. % callq
  12789. % extra parameter for var->type assoc. list
  12790. % update 'program' and 'if'
  12791. % allocate-registers
  12792. % allocate spilled vectors to the rootstack
  12793. % don't change color-graph
  12794. % TODO:
  12795. %\section{Patch Instructions}
  12796. %[mention that global variables are memory references]
  12797. \section{Generate Prelude and Conclusion}
  12798. \label{sec:print-x86-gc}
  12799. \label{sec:prelude-conclusion-x86-gc}
  12800. \index{subject}{prelude}\index{subject}{conclusion}
  12801. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12802. \code{prelude\_and\_conclusion} pass on the running example. In the
  12803. prelude of the \code{main} function, we allocate space
  12804. on the root stack to make room for the spills of tuple-typed
  12805. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12806. taking care that the root stack grows up instead of down. For the
  12807. running example, there was just one spill, so we increment \code{r15}
  12808. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12809. One issue that deserves special care is that there may be a call to
  12810. \code{collect} prior to the initializing assignments for all the
  12811. variables in the root stack. We do not want the garbage collector to
  12812. mistakenly determine that some uninitialized variable is a pointer that
  12813. needs to be followed. Thus, we zero out all locations on the root
  12814. stack in the prelude of \code{main}. In
  12815. figure~\ref{fig:print-x86-output-gc}, the instruction
  12816. %
  12817. \lstinline{movq $0, 0(%r15)}
  12818. %
  12819. is sufficient to accomplish this task because there is only one spill.
  12820. In general, we have to clear as many words as there are spills of
  12821. tuple-typed variables. The garbage collector tests each root to see
  12822. if it is null prior to dereferencing it.
  12823. \begin{figure}[htbp]
  12824. \begin{tcolorbox}[colback=white]
  12825. {\if\edition\racketEd
  12826. \begin{minipage}[t]{0.5\textwidth}
  12827. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12828. .globl main
  12829. main:
  12830. pushq %rbp
  12831. movq %rsp, %rbp
  12832. subq $0, %rsp
  12833. movq $65536, %rdi
  12834. movq $65536, %rsi
  12835. callq initialize
  12836. movq rootstack_begin(%rip), %r15
  12837. movq $0, 0(%r15)
  12838. addq $8, %r15
  12839. jmp start
  12840. conclusion:
  12841. subq $8, %r15
  12842. addq $0, %rsp
  12843. popq %rbp
  12844. retq
  12845. \end{lstlisting}
  12846. \end{minipage}
  12847. \fi}
  12848. {\if\edition\pythonEd
  12849. \begin{minipage}[t]{0.5\textwidth}
  12850. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12851. .globl main
  12852. main:
  12853. pushq %rbp
  12854. movq %rsp, %rbp
  12855. pushq %rbx
  12856. subq $8, %rsp
  12857. movq $65536, %rdi
  12858. movq $16, %rsi
  12859. callq initialize
  12860. movq rootstack_begin(%rip), %r15
  12861. movq $0, 0(%r15)
  12862. addq $8, %r15
  12863. jmp start
  12864. conclusion:
  12865. subq $8, %r15
  12866. addq $8, %rsp
  12867. popq %rbx
  12868. popq %rbp
  12869. retq
  12870. \end{lstlisting}
  12871. \end{minipage}
  12872. \fi}
  12873. \end{tcolorbox}
  12874. \caption{The prelude and conclusion for the running example.}
  12875. \label{fig:print-x86-output-gc}
  12876. \end{figure}
  12877. \begin{figure}[tbp]
  12878. \begin{tcolorbox}[colback=white]
  12879. {\if\edition\racketEd
  12880. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12881. \node (Lvec) at (0,2) {\large \LangVec{}};
  12882. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12883. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12884. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12885. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12886. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12887. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12888. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12889. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12890. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12891. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12892. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12893. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12894. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12895. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12896. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12897. \path[->,bend left=15] (Lvec-4) edge [right] node
  12898. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12899. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12900. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12901. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12902. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12903. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12904. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12905. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12906. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12907. \end{tikzpicture}
  12908. \fi}
  12909. {\if\edition\pythonEd\pythonColor
  12910. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12911. \node (Lvec) at (0,2) {\large \LangVec{}};
  12912. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12913. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12914. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12915. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12916. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12917. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12918. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12919. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12920. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12921. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12922. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12923. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12924. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12925. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12926. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12927. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12928. \end{tikzpicture}
  12929. \fi}
  12930. \end{tcolorbox}
  12931. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12932. \label{fig:Lvec-passes}
  12933. \end{figure}
  12934. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12935. for the compilation of \LangVec{}.
  12936. \clearpage
  12937. {\if\edition\racketEd
  12938. \section{Challenge: Simple Structures}
  12939. \label{sec:simple-structures}
  12940. \index{subject}{struct}
  12941. \index{subject}{structure}
  12942. The language \LangStruct{} extends \LangVec{} with support for simple
  12943. structures. The definition of its concrete syntax is shown in
  12944. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12945. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12946. in Typed Racket is a user-defined data type that contains named fields
  12947. and that is heap allocated\index{subject}{heap allocated},
  12948. similarly to a vector. The following is an
  12949. example of a structure definition, in this case the definition of a
  12950. \code{point} type:
  12951. \begin{lstlisting}
  12952. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12953. \end{lstlisting}
  12954. \newcommand{\LstructGrammarRacket}{
  12955. \begin{array}{lcl}
  12956. \Type &::=& \Var \\
  12957. \Exp &::=& (\Var\;\Exp \ldots)\\
  12958. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12959. \end{array}
  12960. }
  12961. \newcommand{\LstructASTRacket}{
  12962. \begin{array}{lcl}
  12963. \Type &::=& \VAR{\Var} \\
  12964. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12965. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12966. \end{array}
  12967. }
  12968. \begin{figure}[tbp]
  12969. \centering
  12970. \begin{tcolorbox}[colback=white]
  12971. \[
  12972. \begin{array}{l}
  12973. \gray{\LintGrammarRacket{}} \\ \hline
  12974. \gray{\LvarGrammarRacket{}} \\ \hline
  12975. \gray{\LifGrammarRacket{}} \\ \hline
  12976. \gray{\LwhileGrammarRacket} \\ \hline
  12977. \gray{\LtupGrammarRacket} \\ \hline
  12978. \LstructGrammarRacket \\
  12979. \begin{array}{lcl}
  12980. \LangStruct{} &::=& \Def \ldots \; \Exp
  12981. \end{array}
  12982. \end{array}
  12983. \]
  12984. \end{tcolorbox}
  12985. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12986. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12987. \label{fig:Lstruct-concrete-syntax}
  12988. \index{subject}{Lstruct@\LangStruct{} concrete syntax}
  12989. \end{figure}
  12990. \begin{figure}[tbp]
  12991. \centering
  12992. \begin{tcolorbox}[colback=white]
  12993. \small
  12994. \[
  12995. \begin{array}{l}
  12996. \gray{\LintASTRacket{}} \\ \hline
  12997. \gray{\LvarASTRacket{}} \\ \hline
  12998. \gray{\LifASTRacket{}} \\ \hline
  12999. \gray{\LwhileASTRacket} \\ \hline
  13000. \gray{\LtupASTRacket} \\ \hline
  13001. \LstructASTRacket \\
  13002. \begin{array}{lcl}
  13003. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13004. \end{array}
  13005. \end{array}
  13006. \]
  13007. \end{tcolorbox}
  13008. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  13009. (figure~\ref{fig:Lvec-syntax}).}
  13010. \label{fig:Lstruct-syntax}
  13011. \index{subject}{Lstruct@\LangStruct{} abstract syntax}
  13012. \end{figure}
  13013. An instance of a structure is created using function-call syntax, with
  13014. the name of the structure in the function position, as follows:
  13015. \begin{lstlisting}
  13016. (point 7 12)
  13017. \end{lstlisting}
  13018. Function-call syntax is also used to read a field of a structure. The
  13019. function name is formed by the structure name, a dash, and the field
  13020. name. The following example uses \code{point-x} and \code{point-y} to
  13021. access the \code{x} and \code{y} fields of two point instances:
  13022. \begin{center}
  13023. \begin{lstlisting}
  13024. (let ([pt1 (point 7 12)])
  13025. (let ([pt2 (point 4 3)])
  13026. (+ (- (point-x pt1) (point-x pt2))
  13027. (- (point-y pt1) (point-y pt2)))))
  13028. \end{lstlisting}
  13029. \end{center}
  13030. Similarly, to write to a field of a structure, use its set function,
  13031. whose name starts with \code{set-}, followed by the structure name,
  13032. then a dash, then the field name, and finally with an exclamation
  13033. mark. The following example uses \code{set-point-x!} to change the
  13034. \code{x} field from \code{7} to \code{42}:
  13035. \begin{center}
  13036. \begin{lstlisting}
  13037. (let ([pt (point 7 12)])
  13038. (let ([_ (set-point-x! pt 42)])
  13039. (point-x pt)))
  13040. \end{lstlisting}
  13041. \end{center}
  13042. \begin{exercise}\normalfont\normalsize
  13043. Create a type checker for \LangStruct{} by extending the type
  13044. checker for \LangVec{}. Extend your compiler with support for simple
  13045. structures, compiling \LangStruct{} to x86 assembly code. Create
  13046. five new test cases that use structures, and test your compiler.
  13047. \end{exercise}
  13048. % TODO: create an interpreter for L_struct
  13049. \clearpage
  13050. \fi}
  13051. \section{Challenge: Arrays}
  13052. \label{sec:arrays}
  13053. % TODO mention trapped-error
  13054. In this chapter we have studied tuples, that is, heterogeneous
  13055. sequences of elements whose length is determined at compile time. This
  13056. challenge is also about sequences, but this time the length is
  13057. determined at runtime and all the elements have the same type (they
  13058. are homogeneous). We use the traditional term \emph{array} for this
  13059. latter kind of sequence.
  13060. %
  13061. \racket{
  13062. The Racket language does not distinguish between tuples and arrays;
  13063. they are both represented by vectors. However, Typed Racket
  13064. distinguishes between tuples and arrays: the \code{Vector} type is for
  13065. tuples, and the \code{Vectorof} type is for arrays.}%
  13066. \python{Arrays correspond to the \code{list} type in the Python language.}
  13067. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13068. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13069. presents the definition of the abstract syntax, extending \LangVec{}
  13070. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13071. \racket{\code{make-vector} primitive operator for creating an array,
  13072. whose arguments are the length of the array and an initial value for
  13073. all the elements in the array.}%
  13074. \python{bracket notation for creating an array literal.}
  13075. \racket{The \code{vector-length},
  13076. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13077. for tuples become overloaded for use with arrays.}
  13078. \python{
  13079. The subscript operator becomes overloaded for use with arrays and tuples
  13080. and now may appear on the left-hand side of an assignment.
  13081. Note that the index of the subscript, when applied to an array, may be an
  13082. arbitrary expression and not exclusively a constant integer.
  13083. The \code{len} function is also applicable to arrays.
  13084. }
  13085. %
  13086. We include integer multiplication in \LangArray{} because it is
  13087. useful in many examples involving arrays such as computing the
  13088. inner product of two arrays (figure~\ref{fig:inner_product}).
  13089. \newcommand{\LarrayGrammarRacket}{
  13090. \begin{array}{lcl}
  13091. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13092. \Exp &::=& \CMUL{\Exp}{\Exp}
  13093. \MID \CMAKEVEC{\Exp}{\Exp}
  13094. \end{array}
  13095. }
  13096. \newcommand{\LarrayASTRacket}{
  13097. \begin{array}{lcl}
  13098. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13099. \Exp &::=& \MUL{\Exp}{\Exp}
  13100. \MID \MAKEVEC{\Exp}{\Exp}
  13101. \end{array}
  13102. }
  13103. \newcommand{\LarrayGrammarPython}{
  13104. \begin{array}{lcl}
  13105. \Type &::=& \key{list}\LS\Type\RS \\
  13106. \Exp &::=& \CMUL{\Exp}{\Exp}
  13107. \MID \CGET{\Exp}{\Exp}
  13108. \MID \LS \Exp \code{,} \ldots \RS \\
  13109. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13110. \end{array}
  13111. }
  13112. \newcommand{\LarrayASTPython}{
  13113. \begin{array}{lcl}
  13114. \Type &::=& \key{ListType}\LP\Type\RP \\
  13115. \Exp &::=& \MUL{\Exp}{\Exp}
  13116. \MID \GET{\Exp}{\Exp} \\
  13117. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13118. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13119. \end{array}
  13120. }
  13121. \begin{figure}[tp]
  13122. \centering
  13123. \begin{tcolorbox}[colback=white]
  13124. \small
  13125. {\if\edition\racketEd
  13126. \[
  13127. \begin{array}{l}
  13128. \gray{\LintGrammarRacket{}} \\ \hline
  13129. \gray{\LvarGrammarRacket{}} \\ \hline
  13130. \gray{\LifGrammarRacket{}} \\ \hline
  13131. \gray{\LwhileGrammarRacket} \\ \hline
  13132. \gray{\LtupGrammarRacket} \\ \hline
  13133. \LarrayGrammarRacket \\
  13134. \begin{array}{lcl}
  13135. \LangArray{} &::=& \Exp
  13136. \end{array}
  13137. \end{array}
  13138. \]
  13139. \fi}
  13140. {\if\edition\pythonEd\pythonColor
  13141. \[
  13142. \begin{array}{l}
  13143. \gray{\LintGrammarPython{}} \\ \hline
  13144. \gray{\LvarGrammarPython{}} \\ \hline
  13145. \gray{\LifGrammarPython{}} \\ \hline
  13146. \gray{\LwhileGrammarPython} \\ \hline
  13147. \gray{\LtupGrammarPython} \\ \hline
  13148. \LarrayGrammarPython \\
  13149. \begin{array}{rcl}
  13150. \LangArrayM{} &::=& \Stmt^{*}
  13151. \end{array}
  13152. \end{array}
  13153. \]
  13154. \fi}
  13155. \end{tcolorbox}
  13156. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13157. \label{fig:Lvecof-concrete-syntax}
  13158. \index{subject}{Larray@\LangArray{} concrete syntax}
  13159. \end{figure}
  13160. \begin{figure}[tp]
  13161. \centering
  13162. \begin{tcolorbox}[colback=white]
  13163. \small
  13164. {\if\edition\racketEd
  13165. \[
  13166. \begin{array}{l}
  13167. \gray{\LintASTRacket{}} \\ \hline
  13168. \gray{\LvarASTRacket{}} \\ \hline
  13169. \gray{\LifASTRacket{}} \\ \hline
  13170. \gray{\LwhileASTRacket} \\ \hline
  13171. \gray{\LtupASTRacket} \\ \hline
  13172. \LarrayASTRacket \\
  13173. \begin{array}{lcl}
  13174. \LangArray{} &::=& \Exp
  13175. \end{array}
  13176. \end{array}
  13177. \]
  13178. \fi}
  13179. {\if\edition\pythonEd\pythonColor
  13180. \[
  13181. \begin{array}{l}
  13182. \gray{\LintASTPython{}} \\ \hline
  13183. \gray{\LvarASTPython{}} \\ \hline
  13184. \gray{\LifASTPython{}} \\ \hline
  13185. \gray{\LwhileASTPython} \\ \hline
  13186. \gray{\LtupASTPython} \\ \hline
  13187. \LarrayASTPython \\
  13188. \begin{array}{rcl}
  13189. \LangArrayM{} &::=& \Stmt^{*}
  13190. \end{array}
  13191. \end{array}
  13192. \]
  13193. \fi}
  13194. \end{tcolorbox}
  13195. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13196. \label{fig:Lvecof-syntax}
  13197. \index{subject}{Larray@\LangArray{} abstract syntax}
  13198. \end{figure}
  13199. \begin{figure}[tp]
  13200. \begin{tcolorbox}[colback=white]
  13201. {\if\edition\racketEd
  13202. % TODO: remove the function from the following example, like the python version -Jeremy
  13203. \begin{lstlisting}
  13204. (let ([A (make-vector 2 2)])
  13205. (let ([B (make-vector 2 3)])
  13206. (let ([i 0])
  13207. (let ([prod 0])
  13208. (begin
  13209. (while (< i n)
  13210. (begin
  13211. (set! prod (+ prod (* (vector-ref A i)
  13212. (vector-ref B i))))
  13213. (set! i (+ i 1))))
  13214. prod)))))
  13215. \end{lstlisting}
  13216. \fi}
  13217. {\if\edition\pythonEd\pythonColor
  13218. \begin{lstlisting}
  13219. A = [2, 2]
  13220. B = [3, 3]
  13221. i = 0
  13222. prod = 0
  13223. while i != len(A):
  13224. prod = prod + A[i] * B[i]
  13225. i = i + 1
  13226. print(prod)
  13227. \end{lstlisting}
  13228. \fi}
  13229. \end{tcolorbox}
  13230. \caption{Example program that computes the inner product.}
  13231. \label{fig:inner_product}
  13232. \end{figure}
  13233. {\if\edition\racketEd
  13234. %
  13235. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13236. checker for \LangArray{}. The result type of
  13237. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13238. of the initializing expression. The length expression is required to
  13239. have type \code{Integer}. The type checking of the operators
  13240. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13241. updated to handle the situation in which the vector has type
  13242. \code{Vectorof}. In these cases we translate the operators to their
  13243. \code{vectorof} form so that later passes can easily distinguish
  13244. between operations on tuples versus arrays. We override the
  13245. \code{operator-types} method to provide the type signature for
  13246. multiplication: it takes two integers and returns an integer.
  13247. \fi}
  13248. %
  13249. {\if\edition\pythonEd\pythonColor
  13250. %
  13251. The type checker for \LangArray{} is defined in
  13252. figures~\ref{fig:type-check-Lvecof} and
  13253. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13254. is \code{list[T]}, where \code{T} is the type of the initializing
  13255. expressions. The type checking of the \code{len} function and the
  13256. subscript operator are updated to handle lists. The type checker now
  13257. also handles a subscript on the left-hand side of an assignment.
  13258. Regarding multiplication, it takes two integers and returns an
  13259. integer.
  13260. %
  13261. \fi}
  13262. \begin{figure}[tbp]
  13263. \begin{tcolorbox}[colback=white]
  13264. {\if\edition\racketEd
  13265. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13266. (define type-check-Lvecof-class
  13267. (class type-check-Lvec-class
  13268. (super-new)
  13269. (inherit check-type-equal?)
  13270. (define/override (operator-types)
  13271. (append '((* . ((Integer Integer) . Integer)))
  13272. (super operator-types)))
  13273. (define/override (type-check-exp env)
  13274. (lambda (e)
  13275. (define recur (type-check-exp env))
  13276. (match e
  13277. [(Prim 'make-vector (list e1 e2))
  13278. (define-values (e1^ t1) (recur e1))
  13279. (define-values (e2^ elt-type) (recur e2))
  13280. (define vec-type `(Vectorof ,elt-type))
  13281. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13282. [(Prim 'vector-ref (list e1 e2))
  13283. (define-values (e1^ t1) (recur e1))
  13284. (define-values (e2^ t2) (recur e2))
  13285. (match* (t1 t2)
  13286. [(`(Vectorof ,elt-type) 'Integer)
  13287. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13288. [(other wise) ((super type-check-exp env) e)])]
  13289. [(Prim 'vector-set! (list e1 e2 e3) )
  13290. (define-values (e-vec t-vec) (recur e1))
  13291. (define-values (e2^ t2) (recur e2))
  13292. (define-values (e-arg^ t-arg) (recur e3))
  13293. (match t-vec
  13294. [`(Vectorof ,elt-type)
  13295. (check-type-equal? elt-type t-arg e)
  13296. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13297. [else ((super type-check-exp env) e)])]
  13298. [(Prim 'vector-length (list e1))
  13299. (define-values (e1^ t1) (recur e1))
  13300. (match t1
  13301. [`(Vectorof ,t)
  13302. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13303. [else ((super type-check-exp env) e)])]
  13304. [else ((super type-check-exp env) e)])))
  13305. ))
  13306. (define (type-check-Lvecof p)
  13307. (send (new type-check-Lvecof-class) type-check-program p))
  13308. \end{lstlisting}
  13309. \fi}
  13310. {\if\edition\pythonEd\pythonColor
  13311. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13312. class TypeCheckLarray(TypeCheckLtup):
  13313. def type_check_exp(self, e, env):
  13314. match e:
  13315. case ast.List(es, Load()):
  13316. ts = [self.type_check_exp(e, env) for e in es]
  13317. elt_ty = ts[0]
  13318. for (ty, elt) in zip(ts, es):
  13319. self.check_type_equal(elt_ty, ty, elt)
  13320. e.has_type = ListType(elt_ty)
  13321. return e.has_type
  13322. case Call(Name('len'), [tup]):
  13323. tup_t = self.type_check_exp(tup, env)
  13324. tup.has_type = tup_t
  13325. match tup_t:
  13326. case TupleType(ts):
  13327. return IntType()
  13328. case ListType(ty):
  13329. return IntType()
  13330. case _:
  13331. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13332. case Subscript(tup, index, Load()):
  13333. tup_ty = self.type_check_exp(tup, env)
  13334. index_ty = self.type_check_exp(index, env)
  13335. self.check_type_equal(index_ty, IntType(), index)
  13336. match tup_ty:
  13337. case TupleType(ts):
  13338. match index:
  13339. case Constant(i):
  13340. return ts[i]
  13341. case _:
  13342. raise Exception('subscript required constant integer index')
  13343. case ListType(ty):
  13344. return ty
  13345. case _:
  13346. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13347. case BinOp(left, Mult(), right):
  13348. l = self.type_check_exp(left, env)
  13349. self.check_type_equal(l, IntType(), left)
  13350. r = self.type_check_exp(right, env)
  13351. self.check_type_equal(r, IntType(), right)
  13352. return IntType()
  13353. case _:
  13354. return super().type_check_exp(e, env)
  13355. \end{lstlisting}
  13356. \fi}
  13357. \end{tcolorbox}
  13358. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13359. \label{fig:type-check-Lvecof}
  13360. \end{figure}
  13361. {\if\edition\pythonEd
  13362. \begin{figure}[tbp]
  13363. \begin{tcolorbox}[colback=white]
  13364. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13365. def type_check_stmts(self, ss, env):
  13366. if len(ss) == 0:
  13367. return VoidType()
  13368. match ss[0]:
  13369. case Assign([Subscript(tup, index, Store())], value):
  13370. tup_t = self.type_check_exp(tup, env)
  13371. value_t = self.type_check_exp(value, env)
  13372. index_ty = self.type_check_exp(index, env)
  13373. self.check_type_equal(index_ty, IntType(), index)
  13374. match tup_t:
  13375. case ListType(ty):
  13376. self.check_type_equal(ty, value_t, ss[0])
  13377. case TupleType(ts):
  13378. return self.type_check_stmts(ss, env)
  13379. case _:
  13380. raise Exception('type_check_stmts: '
  13381. 'expected tuple or list, not ' + repr(tup_t))
  13382. return self.type_check_stmts(ss[1:], env)
  13383. case _:
  13384. return super().type_check_stmts(ss, env)
  13385. \end{lstlisting}
  13386. \end{tcolorbox}
  13387. \caption{Type checker for the \LangArray{} language, part 2.}
  13388. \label{fig:type-check-Lvecof-part2}
  13389. \end{figure}
  13390. \fi}
  13391. The definition of the interpreter for \LangArray{} is shown in
  13392. \racket{figure~\ref{fig:interp-Lvecof}}
  13393. \python{figure~\ref{fig:interp-Lvecof}}.
  13394. \racket{The \code{make-vector} operator is
  13395. interpreted using Racket's \code{make-vector} function,
  13396. and multiplication is interpreted using \code{fx*},
  13397. which is multiplication for \code{fixnum} integers.
  13398. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13399. we translate array access operations
  13400. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13401. which we interpret using \code{vector} operations with additional
  13402. bounds checks that signal a \code{trapped-error}.
  13403. }
  13404. %
  13405. \python{We implement array creation with a Python list comprehension,
  13406. and multiplication is implemented with 64-bit multiplication. We
  13407. add a case for a subscript on the left-hand side of
  13408. assignment. Other uses of subscript can be handled by the existing
  13409. code for tuples.}
  13410. \begin{figure}[tbp]
  13411. \begin{tcolorbox}[colback=white]
  13412. {\if\edition\racketEd
  13413. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13414. (define interp-Lvecof-class
  13415. (class interp-Lvec-class
  13416. (super-new)
  13417. (define/override (interp-op op)
  13418. (match op
  13419. ['make-vector make-vector]
  13420. ['vectorof-length vector-length]
  13421. ['vectorof-ref
  13422. (lambda (v i)
  13423. (if (< i (vector-length v))
  13424. (vector-ref v i)
  13425. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13426. ['vectorof-set!
  13427. (lambda (v i e)
  13428. (if (< i (vector-length v))
  13429. (vector-set! v i e)
  13430. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13431. [else (super interp-op op)]))
  13432. ))
  13433. (define (interp-Lvecof p)
  13434. (send (new interp-Lvecof-class) interp-program p))
  13435. \end{lstlisting}
  13436. \fi}
  13437. {\if\edition\pythonEd\pythonColor
  13438. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13439. class InterpLarray(InterpLtup):
  13440. def interp_exp(self, e, env):
  13441. match e:
  13442. case ast.List(es, Load()):
  13443. return [self.interp_exp(e, env) for e in es]
  13444. case BinOp(left, Mult(), right):
  13445. l = self.interp_exp(left, env)
  13446. r = self.interp_exp(right, env)
  13447. return mul64(l, r)
  13448. case Subscript(tup, index, Load()):
  13449. t = self.interp_exp(tup, env)
  13450. n = self.interp_exp(index, env)
  13451. if n < len(t):
  13452. return t[n]
  13453. else:
  13454. raise TrappedError('array index out of bounds')
  13455. case _:
  13456. return super().interp_exp(e, env)
  13457. def interp_stmt(self, s, env, cont):
  13458. match s:
  13459. case Assign([Subscript(tup, index)], value):
  13460. t = self.interp_exp(tup, env)
  13461. n = self.interp_exp(index, env)
  13462. if n < len(t):
  13463. t[n] = self.interp_exp(value, env)
  13464. else:
  13465. raise TrappedError('array index out of bounds')
  13466. return self.interp_stmts(cont, env)
  13467. case _:
  13468. return super().interp_stmt(s, env, cont)
  13469. \end{lstlisting}
  13470. \fi}
  13471. \end{tcolorbox}
  13472. \caption{Interpreter for \LangArray{}.}
  13473. \label{fig:interp-Lvecof}
  13474. \end{figure}
  13475. \subsection{Data Representation}
  13476. \label{sec:array-rep}
  13477. Just as with tuples, we store arrays on the heap, which means that the
  13478. garbage collector will need to inspect arrays. An immediate thought is
  13479. to use the same representation for arrays that we use for tuples.
  13480. However, we limit tuples to a length of fifty so that their length and
  13481. pointer mask can fit into the 64-bit tag at the beginning of each
  13482. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13483. millions of elements, so we need more bits to store the length.
  13484. However, because arrays are homogeneous, we need only 1 bit for the
  13485. pointer mask instead of 1 bit per array element. Finally, the
  13486. garbage collector must be able to distinguish between tuples
  13487. and arrays, so we need to reserve one bit for that purpose. We
  13488. arrive at the following layout for the 64-bit tag at the beginning of
  13489. an array:
  13490. \begin{itemize}
  13491. \item The right-most bit is the forwarding bit, just as in a tuple.
  13492. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13493. that it is not.
  13494. \item The next bit to the left is the pointer mask. A $0$ indicates
  13495. that none of the elements are pointers, and a $1$ indicates that all
  13496. the elements are pointers.
  13497. \item The next $60$ bits store the length of the array.
  13498. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13499. and an array ($1$).
  13500. \item The left-most bit is reserved as explained in
  13501. chapter~\ref{ch:Lgrad}.
  13502. \end{itemize}
  13503. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13504. %% differentiate the kinds of values that have been injected into the
  13505. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13506. %% to indicate that the value is an array.
  13507. In the following subsections we provide hints regarding how to update
  13508. the passes to handle arrays.
  13509. \subsection{Overload Resolution}
  13510. \label{sec:array-resolution}
  13511. As noted previously, with the addition of arrays, several operators
  13512. have become \emph{overloaded}; that is, they can be applied to values
  13513. of more than one type. In this case, the element access and length
  13514. operators can be applied to both tuples and arrays. This kind of
  13515. overloading is quite common in programming languages, so many
  13516. compilers perform \emph{overload resolution}\index{subject}{overload
  13517. resolution} to handle it. The idea is to translate each overloaded
  13518. operator into different operators for the different types.
  13519. Implement a new pass named \code{resolve}.
  13520. Translate the reading of an array element to
  13521. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13522. and the writing of an array element to
  13523. \racket{\code{vectorof-set!}}\python{\code{array\_store}}.
  13524. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13525. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13526. When these operators are applied to tuples, leave them as is.
  13527. %
  13528. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13529. field, which can be inspected to determine whether the operator
  13530. is applied to a tuple or an array.}
  13531. \subsection{Bounds Checking}
  13532. Recall that the interpreter for \LangArray{} signals a
  13533. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13534. when there is an array access that is out of
  13535. bounds. Therefore your compiler is obliged to also catch these errors
  13536. during execution and halt, signaling an error. We recommend inserting
  13537. a new pass named \code{check\_bounds} that inserts code around each
  13538. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13539. \python{subscript} operation to ensure that the index is greater than
  13540. or equal to zero and less than the array's length. If not, the program
  13541. should halt, for which we recommend using a new primitive operation
  13542. named \code{exit}.
  13543. %% \subsection{Reveal Casts}
  13544. %% The array-access operators \code{vectorof-ref} and
  13545. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13546. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13547. %% that the type checker cannot tell whether the index will be in bounds,
  13548. %% so the bounds check must be performed at run time. Recall that the
  13549. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13550. %% an \code{If} around a vector reference for update to check whether
  13551. %% the index is less than the length. You should do the same for
  13552. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13553. %% In addition, the handling of the \code{any-vector} operators in
  13554. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13555. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13556. %% generated code should test whether the tag is for tuples (\code{010})
  13557. %% or arrays (\code{110}) and then dispatch to either
  13558. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13559. %% we add a case in \code{select\_instructions} to generate the
  13560. %% appropriate instructions for accessing the array length from the
  13561. %% header of an array.
  13562. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13563. %% the generated code needs to check that the index is less than the
  13564. %% vector length, so like the code for \code{any-vector-length}, check
  13565. %% the tag to determine whether to use \code{any-vector-length} or
  13566. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13567. %% is complete, the generated code can use \code{any-vector-ref} and
  13568. %% \code{any-vector-set!} for both tuples and arrays because the
  13569. %% instructions used for those operators do not look at the tag at the
  13570. %% front of the tuple or array.
  13571. \subsection{Expose Allocation}
  13572. This pass should translate array creation into lower-level
  13573. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13574. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13575. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13576. array. The \code{AllocateArray} AST node allocates an array of the
  13577. length specified by the $\Exp$ (of type \INTTY), but does not
  13578. initialize the elements of the array. Generate code in this pass to
  13579. initialize the elements analogous to the case for tuples.
  13580. {\if\edition\racketEd
  13581. \subsection{Uncover \texttt{get!}}
  13582. \label{sec:uncover-get-bang-vecof}
  13583. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13584. \code{uncover-get!-exp}.
  13585. \fi}
  13586. \subsection{Remove Complex Operands}
  13587. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13588. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13589. complex, and its subexpression must be atomic.
  13590. \subsection{Explicate Control}
  13591. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13592. \code{explicate\_assign}.
  13593. \subsection{Select Instructions}
  13594. \index{subject}{select instructions}
  13595. Generate instructions for \code{AllocateArray} similar to those for
  13596. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13597. except that the tag at the front of the array should instead use the
  13598. representation discussed in section~\ref{sec:array-rep}.
  13599. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13600. extract the length from the tag.
  13601. The instructions generated for accessing an element of an array differ
  13602. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13603. that the index is not a constant so you need to generate instructions
  13604. that compute the offset at runtime.
  13605. Compile the \code{exit} primitive into a call to the \code{exit}
  13606. function of the C standard library, with an argument of $255$.
  13607. %% Also, note that assignment to an array element may appear in
  13608. %% as a stand-alone statement, so make sure to handle that situation in
  13609. %% this pass.
  13610. %% Finally, the instructions for \code{any-vectorof-length} should be
  13611. %% similar to those for \code{vectorof-length}, except that one must
  13612. %% first project the array by writing zeroes into the $3$-bit tag
  13613. \begin{exercise}\normalfont\normalsize
  13614. Implement a compiler for the \LangArray{} language by extending your
  13615. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13616. programs, including the one shown in figure~\ref{fig:inner_product}
  13617. and also a program that multiplies two matrices. Note that although
  13618. matrices are two-dimensional arrays, they can be encoded into
  13619. one-dimensional arrays by laying out each row in the array, one after
  13620. the next.
  13621. \end{exercise}
  13622. {\if\edition\racketEd
  13623. \section{Challenge: Generational Collection}
  13624. The copying collector described in section~\ref{sec:GC} can incur
  13625. significant runtime overhead because the call to \code{collect} takes
  13626. time proportional to all the live data. One way to reduce this
  13627. overhead is to reduce how much data is inspected in each call to
  13628. \code{collect}. In particular, researchers have observed that recently
  13629. allocated data is more likely to become garbage then data that has
  13630. survived one or more previous calls to \code{collect}. This insight
  13631. motivated the creation of \emph{generational garbage collectors}
  13632. \index{subject}{generational garbage collector} that
  13633. (1) segregate data according to its age into two or more generations;
  13634. (2) allocate less space for younger generations, so collecting them is
  13635. faster, and more space for the older generations; and (3) perform
  13636. collection on the younger generations more frequently than on older
  13637. generations~\citep{Wilson:1992fk}.
  13638. For this challenge assignment, the goal is to adapt the copying
  13639. collector implemented in \code{runtime.c} to use two generations, one
  13640. for young data and one for old data. Each generation consists of a
  13641. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13642. \code{collect} function to use the two generations:
  13643. \begin{enumerate}
  13644. \item Copy the young generation's FromSpace to its ToSpace and then
  13645. switch the role of the ToSpace and FromSpace.
  13646. \item If there is enough space for the requested number of bytes in
  13647. the young FromSpace, then return from \code{collect}.
  13648. \item If there is not enough space in the young FromSpace for the
  13649. requested bytes, then move the data from the young generation to the
  13650. old one with the following steps:
  13651. \begin{enumerate}
  13652. \item[a.] If there is enough room in the old FromSpace, copy the young
  13653. FromSpace to the old FromSpace and then return.
  13654. \item[b.] If there is not enough room in the old FromSpace, then collect
  13655. the old generation by copying the old FromSpace to the old ToSpace
  13656. and swap the roles of the old FromSpace and ToSpace.
  13657. \item[c.] If there is enough room now, copy the young FromSpace to the
  13658. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13659. and ToSpace for the old generation. Copy the young FromSpace and
  13660. the old FromSpace into the larger FromSpace for the old
  13661. generation and then return.
  13662. \end{enumerate}
  13663. \end{enumerate}
  13664. We recommend that you generalize the \code{cheney} function so that it
  13665. can be used for all the copies mentioned: between the young FromSpace
  13666. and ToSpace, between the old FromSpace and ToSpace, and between the
  13667. young FromSpace and old FromSpace. This can be accomplished by adding
  13668. parameters to \code{cheney} that replace its use of the global
  13669. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13670. \code{tospace\_begin}, and \code{tospace\_end}.
  13671. Note that the collection of the young generation does not traverse the
  13672. old generation. This introduces a potential problem: there may be
  13673. young data that is reachable only through pointers in the old
  13674. generation. If these pointers are not taken into account, the
  13675. collector could throw away young data that is live! One solution,
  13676. called \emph{pointer recording}, is to maintain a set of all the
  13677. pointers from the old generation into the new generation and consider
  13678. this set as part of the root set. To maintain this set, the compiler
  13679. must insert extra instructions around every \code{vector-set!}. If the
  13680. vector being modified is in the old generation, and if the value being
  13681. written is a pointer into the new generation, then that pointer must
  13682. be added to the set. Also, if the value being overwritten was a
  13683. pointer into the new generation, then that pointer should be removed
  13684. from the set.
  13685. \begin{exercise}\normalfont\normalsize
  13686. Adapt the \code{collect} function in \code{runtime.c} to implement
  13687. generational garbage collection, as outlined in this section.
  13688. Update the code generation for \code{vector-set!} to implement
  13689. pointer recording. Make sure that your new compiler and runtime
  13690. execute without error on your test suite.
  13691. \end{exercise}
  13692. \fi}
  13693. \section{Further Reading}
  13694. \citet{Appel90} describes many data representation approaches
  13695. including the ones used in the compilation of Standard ML.
  13696. There are many alternatives to copying collectors (and their bigger
  13697. siblings, the generational collectors) with regard to garbage
  13698. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13699. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13700. collectors are that allocation is fast (just a comparison and pointer
  13701. increment), there is no fragmentation, cyclic garbage is collected,
  13702. and the time complexity of collection depends only on the amount of
  13703. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13704. main disadvantages of a two-space copying collector is that it uses a
  13705. lot of extra space and takes a long time to perform the copy, though
  13706. these problems are ameliorated in generational collectors.
  13707. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13708. small objects and generate a lot of garbage, so copying and
  13709. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13710. Garbage collection is an active research topic, especially concurrent
  13711. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13712. developing new techniques and revisiting old
  13713. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13714. meet every year at the International Symposium on Memory Management to
  13715. present these findings.
  13716. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13717. \chapter{Functions}
  13718. \label{ch:Lfun}
  13719. \index{subject}{function}
  13720. \setcounter{footnote}{0}
  13721. This chapter studies the compilation of a subset of \racket{Typed
  13722. Racket}\python{Python} in which only top-level function definitions
  13723. are allowed. This kind of function appears in the C programming
  13724. language, and it serves as an important stepping-stone to implementing
  13725. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13726. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13727. \section{The \LangFun{} Language}
  13728. The concrete syntax and abstract syntax for function definitions and
  13729. function application are shown in
  13730. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13731. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13732. with zero or more function definitions. The function names from these
  13733. definitions are in scope for the entire program, including all the
  13734. function definitions, and therefore the ordering of function
  13735. definitions does not matter.
  13736. %
  13737. \python{The abstract syntax for function parameters in
  13738. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13739. consists of a parameter name and its type. This design differs from
  13740. Python's \code{ast} module, which has a more complex structure for
  13741. function parameters to handle keyword parameters,
  13742. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13743. complex Python abstract syntax into the simpler syntax shown in
  13744. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13745. \code{FunctionDef} constructor are for decorators and a type
  13746. comment, neither of which are used by our compiler. We recommend
  13747. replacing them with \code{None} in the \code{shrink} pass.
  13748. }
  13749. %
  13750. The concrete syntax for function application
  13751. \index{subject}{function application}
  13752. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13753. where the first expression
  13754. must evaluate to a function and the remaining expressions are the arguments. The
  13755. abstract syntax for function application is
  13756. $\APPLY{\Exp}{\Exp^*}$.
  13757. %% The syntax for function application does not include an explicit
  13758. %% keyword, which is error prone when using \code{match}. To alleviate
  13759. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13760. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13761. Functions are first-class in the sense that a function pointer
  13762. \index{subject}{function pointer} is data and can be stored in memory or passed
  13763. as a parameter to another function. Thus, there is a function
  13764. type, written
  13765. {\if\edition\racketEd
  13766. \begin{lstlisting}
  13767. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13768. \end{lstlisting}
  13769. \fi}
  13770. {\if\edition\pythonEd\pythonColor
  13771. \begin{lstlisting}
  13772. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13773. \end{lstlisting}
  13774. \fi}
  13775. %
  13776. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13777. through $\Type_n$ and whose return type is $\Type_R$. The main
  13778. limitation of these functions (with respect to
  13779. \racket{Racket}\python{Python} functions) is that they are not
  13780. lexically scoped. That is, the only external entities that can be
  13781. referenced from inside a function body are other globally defined
  13782. functions. The syntax of \LangFun{} prevents function definitions from
  13783. being nested inside each other.
  13784. \newcommand{\LfunGrammarRacket}{
  13785. \begin{array}{lcl}
  13786. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13787. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13788. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13789. \end{array}
  13790. }
  13791. \newcommand{\LfunASTRacket}{
  13792. \begin{array}{lcl}
  13793. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13794. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13795. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13796. \end{array}
  13797. }
  13798. \newcommand{\LfunGrammarPython}{
  13799. \begin{array}{lcl}
  13800. \Type &::=& \key{int}
  13801. \MID \key{bool} \MID \key{void}
  13802. \MID \key{tuple}\LS \Type^+ \RS
  13803. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13804. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13805. \Stmt &::=& \CRETURN{\Exp} \\
  13806. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13807. \end{array}
  13808. }
  13809. \newcommand{\LfunASTPython}{
  13810. \begin{array}{lcl}
  13811. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13812. \MID \key{TupleType}\LS\Type^+\RS\\
  13813. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13814. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13815. \Stmt &::=& \RETURN{\Exp} \\
  13816. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13817. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13818. \end{array}
  13819. }
  13820. \begin{figure}[tp]
  13821. \centering
  13822. \begin{tcolorbox}[colback=white]
  13823. \small
  13824. {\if\edition\racketEd
  13825. \[
  13826. \begin{array}{l}
  13827. \gray{\LintGrammarRacket{}} \\ \hline
  13828. \gray{\LvarGrammarRacket{}} \\ \hline
  13829. \gray{\LifGrammarRacket{}} \\ \hline
  13830. \gray{\LwhileGrammarRacket} \\ \hline
  13831. \gray{\LtupGrammarRacket} \\ \hline
  13832. \LfunGrammarRacket \\
  13833. \begin{array}{lcl}
  13834. \LangFunM{} &::=& \Def \ldots \; \Exp
  13835. \end{array}
  13836. \end{array}
  13837. \]
  13838. \fi}
  13839. {\if\edition\pythonEd\pythonColor
  13840. \[
  13841. \begin{array}{l}
  13842. \gray{\LintGrammarPython{}} \\ \hline
  13843. \gray{\LvarGrammarPython{}} \\ \hline
  13844. \gray{\LifGrammarPython{}} \\ \hline
  13845. \gray{\LwhileGrammarPython} \\ \hline
  13846. \gray{\LtupGrammarPython} \\ \hline
  13847. \LfunGrammarPython \\
  13848. \begin{array}{rcl}
  13849. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13850. \end{array}
  13851. \end{array}
  13852. \]
  13853. \fi}
  13854. \end{tcolorbox}
  13855. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13856. \label{fig:Lfun-concrete-syntax}
  13857. \index{subject}{Lfun@\LangFun{} concrete syntax}
  13858. \end{figure}
  13859. \begin{figure}[tp]
  13860. \centering
  13861. \begin{tcolorbox}[colback=white]
  13862. \small
  13863. {\if\edition\racketEd
  13864. \[
  13865. \begin{array}{l}
  13866. \gray{\LintOpAST} \\ \hline
  13867. \gray{\LvarASTRacket{}} \\ \hline
  13868. \gray{\LifASTRacket{}} \\ \hline
  13869. \gray{\LwhileASTRacket{}} \\ \hline
  13870. \gray{\LtupASTRacket{}} \\ \hline
  13871. \LfunASTRacket \\
  13872. \begin{array}{lcl}
  13873. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13874. \end{array}
  13875. \end{array}
  13876. \]
  13877. \fi}
  13878. {\if\edition\pythonEd\pythonColor
  13879. \[
  13880. \begin{array}{l}
  13881. \gray{\LintASTPython{}} \\ \hline
  13882. \gray{\LvarASTPython{}} \\ \hline
  13883. \gray{\LifASTPython{}} \\ \hline
  13884. \gray{\LwhileASTPython} \\ \hline
  13885. \gray{\LtupASTPython} \\ \hline
  13886. \LfunASTPython \\
  13887. \begin{array}{rcl}
  13888. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13889. \end{array}
  13890. \end{array}
  13891. \]
  13892. \fi}
  13893. \end{tcolorbox}
  13894. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13895. \label{fig:Lfun-syntax}
  13896. \index{subject}{Lfun@\LangFun{} abstract syntax}
  13897. \end{figure}
  13898. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13899. representative example of defining and using functions in \LangFun{}.
  13900. We define a function \code{map} that applies some other function
  13901. \code{f} to both elements of a tuple and returns a new tuple
  13902. containing the results. We also define a function \code{inc}. The
  13903. program applies \code{map} to \code{inc} and
  13904. %
  13905. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13906. %
  13907. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13908. %
  13909. from which we return \code{42}.
  13910. \begin{figure}[tbp]
  13911. \begin{tcolorbox}[colback=white]
  13912. {\if\edition\racketEd
  13913. \begin{lstlisting}
  13914. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13915. : (Vector Integer Integer)
  13916. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13917. (define (inc [x : Integer]) : Integer
  13918. (+ x 1))
  13919. (vector-ref (map inc (vector 0 41)) 1)
  13920. \end{lstlisting}
  13921. \fi}
  13922. {\if\edition\pythonEd\pythonColor
  13923. \begin{lstlisting}
  13924. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13925. return f(v[0]), f(v[1])
  13926. def inc(x : int) -> int:
  13927. return x + 1
  13928. print(map(inc, (0, 41))[1])
  13929. \end{lstlisting}
  13930. \fi}
  13931. \end{tcolorbox}
  13932. \caption{Example of using functions in \LangFun{}.}
  13933. \label{fig:Lfun-function-example}
  13934. \end{figure}
  13935. The definitional interpreter for \LangFun{} is shown in
  13936. figure~\ref{fig:interp-Lfun}. The case for the
  13937. %
  13938. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13939. %
  13940. AST is responsible for setting up the mutual recursion between the
  13941. top-level function definitions.
  13942. %
  13943. \racket{We use the classic back-patching
  13944. \index{subject}{back-patching} approach that uses mutable variables
  13945. and makes two passes over the function
  13946. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13947. top-level environment using a mutable cons cell for each function
  13948. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13949. for each function is incomplete; it does not yet include the environment.
  13950. Once the top-level environment has been constructed, we iterate over it and
  13951. update the \code{lambda} values to use the top-level environment.}
  13952. %
  13953. \python{We create a dictionary named \code{env} and fill it in
  13954. by mapping each function name to a new \code{Function} value,
  13955. each of which stores a reference to the \code{env}.
  13956. (We define the class \code{Function} for this purpose.)}
  13957. %
  13958. To interpret a function \racket{application}\python{call}, we match
  13959. the result of the function expression to obtain a function value. We
  13960. then extend the function's environment with the mapping of parameters to
  13961. argument values. Finally, we interpret the body of the function in
  13962. this extended environment.
  13963. \begin{figure}[tp]
  13964. \begin{tcolorbox}[colback=white]
  13965. {\if\edition\racketEd
  13966. \begin{lstlisting}
  13967. (define interp-Lfun-class
  13968. (class interp-Lvec-class
  13969. (super-new)
  13970. (define/override ((interp-exp env) e)
  13971. (define recur (interp-exp env))
  13972. (match e
  13973. [(Apply fun args)
  13974. (define fun-val (recur fun))
  13975. (define arg-vals (for/list ([e args]) (recur e)))
  13976. (match fun-val
  13977. [`(function (,xs ...) ,body ,fun-env)
  13978. (define params-args (for/list ([x xs] [arg arg-vals])
  13979. (cons x (box arg))))
  13980. (define new-env (append params-args fun-env))
  13981. ((interp-exp new-env) body)]
  13982. [else
  13983. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13984. [else ((super interp-exp env) e)]
  13985. ))
  13986. (define/public (interp-def d)
  13987. (match d
  13988. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13989. (cons f (box `(function ,xs ,body ())))]))
  13990. (define/override (interp-program p)
  13991. (match p
  13992. [(ProgramDefsExp info ds body)
  13993. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13994. (for/list ([f (in-dict-values top-level)])
  13995. (set-box! f (match (unbox f)
  13996. [`(function ,xs ,body ())
  13997. `(function ,xs ,body ,top-level)])))
  13998. ((interp-exp top-level) body))]))
  13999. ))
  14000. (define (interp-Lfun p)
  14001. (send (new interp-Lfun-class) interp-program p))
  14002. \end{lstlisting}
  14003. \fi}
  14004. {\if\edition\pythonEd\pythonColor
  14005. \begin{lstlisting}
  14006. class InterpLfun(InterpLtup):
  14007. def apply_fun(self, fun, args, e):
  14008. match fun:
  14009. case Function(name, xs, body, env):
  14010. new_env = env.copy().update(zip(xs, args))
  14011. return self.interp_stmts(body, new_env)
  14012. case _:
  14013. raise Exception('apply_fun: unexpected: ' + repr(fun))
  14014. def interp_exp(self, e, env):
  14015. match e:
  14016. case Call(Name('input_int'), []):
  14017. return super().interp_exp(e, env)
  14018. case Call(func, args):
  14019. f = self.interp_exp(func, env)
  14020. vs = [self.interp_exp(arg, env) for arg in args]
  14021. return self.apply_fun(f, vs, e)
  14022. case _:
  14023. return super().interp_exp(e, env)
  14024. def interp_stmt(self, s, env, cont):
  14025. match s:
  14026. case Return(value):
  14027. return self.interp_exp(value, env)
  14028. case FunctionDef(name, params, bod, dl, returns, comment):
  14029. if isinstance(params, ast.arguments):
  14030. ps = [p.arg for p in params.args]
  14031. else:
  14032. ps = [x for (x,t) in params]
  14033. env[name] = Function(name, ps, bod, env)
  14034. return self.interp_stmts(cont, env)
  14035. case _:
  14036. return super().interp_stmt(s, env, cont)
  14037. def interp(self, p):
  14038. match p:
  14039. case Module(ss):
  14040. env = {}
  14041. self.interp_stmts(ss, env)
  14042. if 'main' in env.keys():
  14043. self.apply_fun(env['main'], [], None)
  14044. case _:
  14045. raise Exception('interp: unexpected ' + repr(p))
  14046. \end{lstlisting}
  14047. \fi}
  14048. \end{tcolorbox}
  14049. \caption{Interpreter for the \LangFun{} language.}
  14050. \label{fig:interp-Lfun}
  14051. \end{figure}
  14052. %\margincomment{TODO: explain type checker}
  14053. The type checker for \LangFun{} is shown in
  14054. figure~\ref{fig:type-check-Lfun}.
  14055. %
  14056. \python{(We omit the code that parses function parameters into the
  14057. simpler abstract syntax.)}
  14058. %
  14059. Similarly to the interpreter, the case for the
  14060. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14061. %
  14062. AST is responsible for setting up the mutual recursion between the
  14063. top-level function definitions. We begin by creating a mapping
  14064. \code{env} from every function name to its type. We then type check
  14065. the program using this mapping.
  14066. %
  14067. \python{To check a function definition, we copy and extend the
  14068. \code{env} with the parameters of the function. We then type check
  14069. the body of the function and obtain the actual return type
  14070. \code{rt}, which is either the type of the expression in a
  14071. \code{return} statement or the \code{VoidType} if control reaches
  14072. the end of the function without a \code{return} statement. (If
  14073. there are multiple \code{return} statements, the types of their
  14074. expressions must agree.) Finally, we check that the actual return
  14075. type \code{rt} is equal to the declared return type \code{returns}.}
  14076. %
  14077. To check a function \racket{application}\python{call}, we match
  14078. the type of the function expression to a function type and check that
  14079. the types of the argument expressions are equal to the function's
  14080. parameter types. The type of the \racket{application}\python{call} as
  14081. a whole is the return type from the function type.
  14082. \begin{figure}[tp]
  14083. \begin{tcolorbox}[colback=white]
  14084. {\if\edition\racketEd
  14085. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14086. (define type-check-Lfun-class
  14087. (class type-check-Lvec-class
  14088. (super-new)
  14089. (inherit check-type-equal?)
  14090. (define/public (type-check-apply env e es)
  14091. (define-values (e^ ty) ((type-check-exp env) e))
  14092. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14093. ((type-check-exp env) e)))
  14094. (match ty
  14095. [`(,ty^* ... -> ,rt)
  14096. (for ([arg-ty ty*] [param-ty ty^*])
  14097. (check-type-equal? arg-ty param-ty (Apply e es)))
  14098. (values e^ e* rt)]))
  14099. (define/override (type-check-exp env)
  14100. (lambda (e)
  14101. (match e
  14102. [(FunRef f n)
  14103. (values (FunRef f n) (dict-ref env f))]
  14104. [(Apply e es)
  14105. (define-values (e^ es^ rt) (type-check-apply env e es))
  14106. (values (Apply e^ es^) rt)]
  14107. [(Call e es)
  14108. (define-values (e^ es^ rt) (type-check-apply env e es))
  14109. (values (Call e^ es^) rt)]
  14110. [else ((super type-check-exp env) e)])))
  14111. (define/public (type-check-def env)
  14112. (lambda (e)
  14113. (match e
  14114. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14115. (define new-env (append (map cons xs ps) env))
  14116. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14117. (check-type-equal? ty^ rt body)
  14118. (Def f p:t* rt info body^)])))
  14119. (define/public (fun-def-type d)
  14120. (match d
  14121. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14122. (define/override (type-check-program e)
  14123. (match e
  14124. [(ProgramDefsExp info ds body)
  14125. (define env (for/list ([d ds])
  14126. (cons (Def-name d) (fun-def-type d))))
  14127. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14128. (define-values (body^ ty) ((type-check-exp env) body))
  14129. (check-type-equal? ty 'Integer body)
  14130. (ProgramDefsExp info ds^ body^)]))))
  14131. (define (type-check-Lfun p)
  14132. (send (new type-check-Lfun-class) type-check-program p))
  14133. \end{lstlisting}
  14134. \fi}
  14135. {\if\edition\pythonEd\pythonColor
  14136. \begin{lstlisting}
  14137. class TypeCheckLfun(TypeCheckLtup):
  14138. def type_check_exp(self, e, env):
  14139. match e:
  14140. case Call(Name('input_int'), []):
  14141. return super().type_check_exp(e, env)
  14142. case Call(func, args):
  14143. func_t = self.type_check_exp(func, env)
  14144. args_t = [self.type_check_exp(arg, env) for arg in args]
  14145. match func_t:
  14146. case FunctionType(params_t, return_t):
  14147. for (arg_t, param_t) in zip(args_t, params_t):
  14148. check_type_equal(param_t, arg_t, e)
  14149. return return_t
  14150. case _:
  14151. raise Exception('type_check_exp: in call, unexpected ' +
  14152. repr(func_t))
  14153. case _:
  14154. return super().type_check_exp(e, env)
  14155. def type_check_stmts(self, ss, env):
  14156. if len(ss) == 0:
  14157. return VoidType()
  14158. match ss[0]:
  14159. case FunctionDef(name, params, body, dl, returns, comment):
  14160. new_env = env.copy().update(params)
  14161. rt = self.type_check_stmts(body, new_env)
  14162. check_type_equal(returns, rt, ss[0])
  14163. return self.type_check_stmts(ss[1:], env)
  14164. case Return(value):
  14165. return self.type_check_exp(value, env)
  14166. case _:
  14167. return super().type_check_stmts(ss, env)
  14168. def type_check(self, p):
  14169. match p:
  14170. case Module(body):
  14171. env = {}
  14172. for s in body:
  14173. match s:
  14174. case FunctionDef(name, params, bod, dl, returns, comment):
  14175. if name in env:
  14176. raise Exception('type_check: function ' +
  14177. repr(name) + ' defined twice')
  14178. params_t = [t for (x,t) in params]
  14179. env[name] = FunctionType(params_t, returns)
  14180. self.type_check_stmts(body, env)
  14181. case _:
  14182. raise Exception('type_check: unexpected ' + repr(p))
  14183. \end{lstlisting}
  14184. \fi}
  14185. \end{tcolorbox}
  14186. \caption{Type checker for the \LangFun{} language.}
  14187. \label{fig:type-check-Lfun}
  14188. \end{figure}
  14189. \clearpage
  14190. \section{Functions in x86}
  14191. \label{sec:fun-x86}
  14192. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14193. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14194. %% \margincomment{\tiny Talk about the return address on the
  14195. %% stack and what callq and retq does.\\ --Jeremy }
  14196. The x86 architecture provides a few features to support the
  14197. implementation of functions. We have already seen that there are
  14198. labels in x86 so that one can refer to the location of an instruction,
  14199. as is needed for jump instructions. Labels can also be used to mark
  14200. the beginning of the instructions for a function. Going further, we
  14201. can obtain the address of a label by using the \key{leaq}
  14202. instruction. For example, the following puts the address of the
  14203. \code{inc} label into the \code{rbx} register:
  14204. \begin{lstlisting}
  14205. leaq inc(%rip), %rbx
  14206. \end{lstlisting}
  14207. Recall from section~\ref{sec:select-instructions-gc} that
  14208. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14209. addressing.
  14210. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14211. to functions whose locations were given by a label, such as
  14212. \code{read\_int}. To support function calls in this chapter we instead
  14213. jump to functions whose location are given by an address in
  14214. a register; that is, we use \emph{indirect function calls}. The
  14215. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14216. before the register name.\index{subject}{indirect function call}
  14217. \begin{lstlisting}
  14218. callq *%rbx
  14219. \end{lstlisting}
  14220. \subsection{Calling Conventions}
  14221. \label{sec:calling-conventions-fun}
  14222. \index{subject}{calling conventions}
  14223. The \code{callq} instruction provides partial support for implementing
  14224. functions: it pushes the return address on the stack and it jumps to
  14225. the target. However, \code{callq} does not handle
  14226. \begin{enumerate}
  14227. \item parameter passing,
  14228. \item pushing frames on the procedure call stack and popping them off,
  14229. or
  14230. \item determining how registers are shared by different functions.
  14231. \end{enumerate}
  14232. Regarding parameter passing, recall that the x86-64 calling
  14233. convention for Unix-based systems uses the following six registers to
  14234. pass arguments to a function, in the given order:
  14235. \begin{lstlisting}
  14236. rdi rsi rdx rcx r8 r9
  14237. \end{lstlisting}
  14238. If there are more than six arguments, then the calling convention
  14239. mandates using space on the frame of the caller for the rest of the
  14240. arguments. However, to ease the implementation of efficient tail calls
  14241. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14242. arguments.
  14243. %
  14244. The return value of the function is stored in register \code{rax}.
  14245. Regarding frames \index{subject}{frame} and the procedure call stack,
  14246. \index{subject}{procedure call stack} recall from
  14247. section~\ref{sec:x86} that the stack grows down and each function call
  14248. uses a chunk of space on the stack called a frame. The caller sets the
  14249. stack pointer, register \code{rsp}, to the last data item in its
  14250. frame. The callee must not change anything in the caller's frame, that
  14251. is, anything that is at or above the stack pointer. The callee is free
  14252. to use locations that are below the stack pointer.
  14253. Recall that we store variables of tuple type on the root stack. So,
  14254. the prelude\index{subject}{prelude} of a function needs to move the
  14255. root stack pointer \code{r15} up according to the number of variables
  14256. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14257. move the root stack pointer back down. Also, the prelude must
  14258. initialize to \code{0} this frame's slots in the root stack to signal
  14259. to the garbage collector that those slots do not yet contain a valid
  14260. pointer. Otherwise the garbage collector will interpret the garbage
  14261. bits in those slots as memory addresses and try to traverse them,
  14262. causing serious mayhem!
  14263. Regarding the sharing of registers between different functions, recall
  14264. from section~\ref{sec:calling-conventions} that the registers are
  14265. divided into two groups, the caller-saved registers and the
  14266. callee-saved registers. The caller should assume that all the
  14267. caller-saved registers are overwritten with arbitrary values by the
  14268. callee. For that reason we recommend in
  14269. section~\ref{sec:calling-conventions} that variables that are live
  14270. during a function call should not be assigned to caller-saved
  14271. registers.
  14272. On the flip side, if the callee wants to use a callee-saved register,
  14273. the callee must save the contents of those registers on their stack
  14274. frame and then put them back prior to returning to the caller. For
  14275. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14276. the register allocator assigns a variable to a callee-saved register,
  14277. then the prelude of the \code{main} function must save that register
  14278. to the stack and the conclusion of \code{main} must restore it. This
  14279. recommendation now generalizes to all functions.
  14280. Recall that the base pointer, register \code{rbp}, is used as a
  14281. point of reference within a frame, so that each local variable can be
  14282. accessed at a fixed offset from the base pointer
  14283. (section~\ref{sec:x86}).
  14284. %
  14285. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14286. frames.
  14287. \begin{figure}[tbp]
  14288. \centering
  14289. \begin{tcolorbox}[colback=white]
  14290. \begin{tabular}{r|r|l|l} \hline
  14291. Caller View & Callee View & Contents & Frame \\ \hline
  14292. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14293. 0(\key{\%rbp}) & & old \key{rbp} \\
  14294. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14295. \ldots & & \ldots \\
  14296. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14297. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14298. \ldots & & \ldots \\
  14299. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14300. %% & & \\
  14301. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14302. %% & \ldots & \ldots \\
  14303. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14304. \hline
  14305. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14306. & 0(\key{\%rbp}) & old \key{rbp} \\
  14307. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14308. & \ldots & \ldots \\
  14309. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14310. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14311. & \ldots & \ldots \\
  14312. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14313. \end{tabular}
  14314. \end{tcolorbox}
  14315. \caption{Memory layout of caller and callee frames.}
  14316. \label{fig:call-frames}
  14317. \end{figure}
  14318. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14319. %% local variables and for storing the values of callee-saved registers
  14320. %% (we shall refer to all of these collectively as ``locals''), and that
  14321. %% at the beginning of a function we move the stack pointer \code{rsp}
  14322. %% down to make room for them.
  14323. %% We recommend storing the local variables
  14324. %% first and then the callee-saved registers, so that the local variables
  14325. %% can be accessed using \code{rbp} the same as before the addition of
  14326. %% functions.
  14327. %% To make additional room for passing arguments, we shall
  14328. %% move the stack pointer even further down. We count how many stack
  14329. %% arguments are needed for each function call that occurs inside the
  14330. %% body of the function and find their maximum. Adding this number to the
  14331. %% number of locals gives us how much the \code{rsp} should be moved at
  14332. %% the beginning of the function. In preparation for a function call, we
  14333. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14334. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14335. %% so on.
  14336. %% Upon calling the function, the stack arguments are retrieved by the
  14337. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14338. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14339. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14340. %% the layout of the caller and callee frames. Notice how important it is
  14341. %% that we correctly compute the maximum number of arguments needed for
  14342. %% function calls; if that number is too small then the arguments and
  14343. %% local variables will smash into each other!
  14344. \subsection{Efficient Tail Calls}
  14345. \label{sec:tail-call}
  14346. In general, the amount of stack space used by a program is determined
  14347. by the longest chain of nested function calls. That is, if function
  14348. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14349. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14350. large if functions are recursive. However, in some cases we can
  14351. arrange to use only a constant amount of space for a long chain of
  14352. nested function calls.
  14353. A \emph{tail call}\index{subject}{tail call} is a function call that
  14354. happens as the last action in a function body. For example, in the
  14355. following program, the recursive call to \code{tail\_sum} is a tail
  14356. call:
  14357. \begin{center}
  14358. {\if\edition\racketEd
  14359. \begin{lstlisting}
  14360. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14361. (if (eq? n 0)
  14362. r
  14363. (tail_sum (- n 1) (+ n r))))
  14364. (+ (tail_sum 3 0) 36)
  14365. \end{lstlisting}
  14366. \fi}
  14367. {\if\edition\pythonEd\pythonColor
  14368. \begin{lstlisting}
  14369. def tail_sum(n : int, r : int) -> int:
  14370. if n == 0:
  14371. return r
  14372. else:
  14373. return tail_sum(n - 1, n + r)
  14374. print(tail_sum(3, 0) + 36)
  14375. \end{lstlisting}
  14376. \fi}
  14377. \end{center}
  14378. At a tail call, the frame of the caller is no longer needed, so we can
  14379. pop the caller's frame before making the tail
  14380. call. \index{subject}{frame} With this approach, a recursive function
  14381. that makes only tail calls ends up using a constant amount of stack
  14382. space. \racket{Functional languages like Racket rely heavily on
  14383. recursive functions, so the definition of Racket \emph{requires}
  14384. that all tail calls be optimized in this way.}
  14385. Some care is needed with regard to argument passing in tail calls. As
  14386. mentioned, for arguments beyond the sixth, the convention is to use
  14387. space in the caller's frame for passing arguments. However, for a
  14388. tail call we pop the caller's frame and can no longer use it. An
  14389. alternative is to use space in the callee's frame for passing
  14390. arguments. However, this option is also problematic because the caller
  14391. and callee's frames overlap in memory. As we begin to copy the
  14392. arguments from their sources in the caller's frame, the target
  14393. locations in the callee's frame might collide with the sources for
  14394. later arguments! We solve this problem by using the heap instead of
  14395. the stack for passing more than six arguments
  14396. (section~\ref{sec:limit-functions-r4}).
  14397. As mentioned, for a tail call we pop the caller's frame prior to
  14398. making the tail call. The instructions for popping a frame are the
  14399. instructions that we usually place in the conclusion of a
  14400. function. Thus, we also need to place such code immediately before
  14401. each tail call. These instructions include restoring the callee-saved
  14402. registers, so it is fortunate that the argument passing registers are
  14403. all caller-saved registers.
  14404. One note remains regarding which instruction to use to make the tail
  14405. call. When the callee is finished, it should not return to the current
  14406. function but instead return to the function that called the current
  14407. one. Thus, the return address that is already on the stack is the
  14408. right one, and we should not use \key{callq} to make the tail call
  14409. because that would overwrite the return address. Instead we simply use
  14410. the \key{jmp} instruction. As with the indirect function call, we write
  14411. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14412. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14413. jump target because the conclusion can overwrite just about everything
  14414. else.
  14415. \begin{lstlisting}
  14416. jmp *%rax
  14417. \end{lstlisting}
  14418. \section{Shrink \LangFun{}}
  14419. \label{sec:shrink-r4}
  14420. The \code{shrink} pass performs a minor modification to ease the
  14421. later passes. This pass introduces an explicit \code{main} function
  14422. that gobbles up all the top-level statements of the module.
  14423. %
  14424. \racket{It also changes the top \code{ProgramDefsExp} form to
  14425. \code{ProgramDefs}.}
  14426. {\if\edition\racketEd
  14427. \begin{lstlisting}
  14428. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14429. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14430. \end{lstlisting}
  14431. where $\itm{mainDef}$ is
  14432. \begin{lstlisting}
  14433. (Def 'main '() 'Integer '() |$\Exp'$|)
  14434. \end{lstlisting}
  14435. \fi}
  14436. {\if\edition\pythonEd\pythonColor
  14437. \begin{lstlisting}
  14438. Module(|$\Def\ldots\Stmt\ldots$|)
  14439. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14440. \end{lstlisting}
  14441. where $\itm{mainDef}$ is
  14442. \begin{lstlisting}
  14443. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14444. \end{lstlisting}
  14445. \fi}
  14446. \section{Reveal Functions and the \LangFunRef{} Language}
  14447. \label{sec:reveal-functions-r4}
  14448. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14449. in that it conflates the use of function names and local
  14450. variables. This is a problem because we need to compile the use of a
  14451. function name differently from the use of a local variable. In
  14452. particular, we use \code{leaq} to convert the function name (a label
  14453. in x86) to an address in a register. Thus, we create a new pass that
  14454. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14455. $n$ is the arity of the function.\python{\footnote{The arity is not
  14456. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14457. This pass is named \code{reveal\_functions} and the output language
  14458. is \LangFunRef{}\index{subject}{Lfunref@\LangFunRef{}}.
  14459. %is defined in figure~\ref{fig:f1-syntax}.
  14460. %% The concrete syntax for a
  14461. %% function reference is $\CFUNREF{f}$.
  14462. %% \begin{figure}[tp]
  14463. %% \centering
  14464. %% \fbox{
  14465. %% \begin{minipage}{0.96\textwidth}
  14466. %% {\if\edition\racketEd
  14467. %% \[
  14468. %% \begin{array}{lcl}
  14469. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14470. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14471. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14472. %% \end{array}
  14473. %% \]
  14474. %% \fi}
  14475. %% {\if\edition\pythonEd\pythonColor
  14476. %% \[
  14477. %% \begin{array}{lcl}
  14478. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14479. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14480. %% \end{array}
  14481. %% \]
  14482. %% \fi}
  14483. %% \end{minipage}
  14484. %% }
  14485. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14486. %% (figure~\ref{fig:Lfun-syntax}).}
  14487. %% \label{fig:f1-syntax}
  14488. %% \end{figure}
  14489. %% Distinguishing between calls in tail position and non-tail position
  14490. %% requires the pass to have some notion of context. We recommend using
  14491. %% two mutually recursive functions, one for processing expressions in
  14492. %% tail position and another for the rest.
  14493. \racket{Placing this pass after \code{uniquify} will make sure that
  14494. there are no local variables and functions that share the same
  14495. name.}
  14496. %
  14497. The \code{reveal\_functions} pass should come before the
  14498. \code{remove\_complex\_operands} pass because function references
  14499. should be categorized as complex expressions.
  14500. \section{Limit Functions}
  14501. \label{sec:limit-functions-r4}
  14502. Recall that we wish to limit the number of function parameters to six
  14503. so that we do not need to use the stack for argument passing, which
  14504. makes it easier to implement efficient tail calls. However, because
  14505. the input language \LangFun{} supports arbitrary numbers of function
  14506. arguments, we have some work to do! The \code{limit\_functions} pass
  14507. transforms functions and function calls that involve more than six
  14508. arguments to pass the first five arguments as usual, but it packs the
  14509. rest of the arguments into a tuple and passes it as the sixth
  14510. argument.\footnote{The implementation this pass can be postponed to
  14511. last because you can test the rest of the passes on functions with
  14512. six or fewer parameters.}
  14513. Each function definition with seven or more parameters is transformed as
  14514. follows:
  14515. {\if\edition\racketEd
  14516. \begin{lstlisting}
  14517. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14518. |$\Rightarrow$|
  14519. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14520. \end{lstlisting}
  14521. \fi}
  14522. {\if\edition\pythonEd\pythonColor
  14523. \begin{lstlisting}
  14524. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14525. |$\Rightarrow$|
  14526. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14527. |$T_r$|, None, |$\itm{body}'$|, None)
  14528. \end{lstlisting}
  14529. \fi}
  14530. %
  14531. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14532. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14533. the $k$th element of the tuple, where $k = i - 6$.
  14534. %
  14535. {\if\edition\racketEd
  14536. \begin{lstlisting}
  14537. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14538. \end{lstlisting}
  14539. \fi}
  14540. {\if\edition\pythonEd\pythonColor
  14541. \begin{lstlisting}
  14542. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14543. \end{lstlisting}
  14544. \fi}
  14545. For function calls with too many arguments, the \code{limit\_functions}
  14546. pass transforms them in the following way:
  14547. \begin{tabular}{lll}
  14548. \begin{minipage}{0.3\textwidth}
  14549. {\if\edition\racketEd
  14550. \begin{lstlisting}
  14551. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14552. \end{lstlisting}
  14553. \fi}
  14554. {\if\edition\pythonEd\pythonColor
  14555. \begin{lstlisting}
  14556. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14557. \end{lstlisting}
  14558. \fi}
  14559. \end{minipage}
  14560. &
  14561. $\Rightarrow$
  14562. &
  14563. \begin{minipage}{0.5\textwidth}
  14564. {\if\edition\racketEd
  14565. \begin{lstlisting}
  14566. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14567. \end{lstlisting}
  14568. \fi}
  14569. {\if\edition\pythonEd\pythonColor
  14570. \begin{lstlisting}
  14571. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14572. \end{lstlisting}
  14573. \fi}
  14574. \end{minipage}
  14575. \end{tabular}
  14576. \section{Remove Complex Operands}
  14577. \label{sec:rco-r4}
  14578. The primary decisions to make for this pass are whether to classify
  14579. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14580. atomic or complex expressions. Recall that an atomic expression
  14581. ends up as an immediate argument of an x86 instruction. Function
  14582. application translates to a sequence of instructions, so
  14583. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14584. a complex expression. On the other hand, the arguments of
  14585. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14586. expressions.
  14587. %
  14588. Regarding \code{FunRef}, as discussed previously, the function label
  14589. needs to be converted to an address using the \code{leaq}
  14590. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14591. needs to be classified as a complex expression so that we generate an
  14592. assignment statement with a left-hand side that can serve as the
  14593. target of the \code{leaq}.
  14594. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14595. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14596. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14597. and augments programs to include a list of function definitions.
  14598. %
  14599. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14600. \newcommand{\LfunMonadASTRacket}{
  14601. \begin{array}{lcl}
  14602. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14603. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14604. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14605. \end{array}
  14606. }
  14607. \newcommand{\LfunMonadASTPython}{
  14608. \begin{array}{lcl}
  14609. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14610. \MID \key{TupleType}\LS\Type^+\RS\\
  14611. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14612. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14613. \Stmt &::=& \RETURN{\Exp} \\
  14614. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14615. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14616. \end{array}
  14617. }
  14618. \begin{figure}[tp]
  14619. \centering
  14620. \begin{tcolorbox}[colback=white]
  14621. \footnotesize
  14622. {\if\edition\racketEd
  14623. \[
  14624. \begin{array}{l}
  14625. \gray{\LvarMonadASTRacket} \\ \hline
  14626. \gray{\LifMonadASTRacket} \\ \hline
  14627. \gray{\LwhileMonadASTRacket} \\ \hline
  14628. \gray{\LtupMonadASTRacket} \\ \hline
  14629. \LfunMonadASTRacket \\
  14630. \begin{array}{rcl}
  14631. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14632. \end{array}
  14633. \end{array}
  14634. \]
  14635. \fi}
  14636. {\if\edition\pythonEd\pythonColor
  14637. \[
  14638. \begin{array}{l}
  14639. \gray{\LvarMonadASTPython} \\ \hline
  14640. \gray{\LifMonadASTPython} \\ \hline
  14641. \gray{\LwhileMonadASTPython} \\ \hline
  14642. \gray{\LtupMonadASTPython} \\ \hline
  14643. \LfunMonadASTPython \\
  14644. \begin{array}{rcl}
  14645. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14646. \end{array}
  14647. \end{array}
  14648. \]
  14649. \fi}
  14650. \end{tcolorbox}
  14651. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14652. \label{fig:Lfun-anf-syntax}
  14653. \index{subject}{Lfunmon@\LangFunANF{} abstract syntax}
  14654. \end{figure}
  14655. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14656. %% \LangFunANF{} of this pass.
  14657. %% \begin{figure}[tp]
  14658. %% \centering
  14659. %% \fbox{
  14660. %% \begin{minipage}{0.96\textwidth}
  14661. %% \small
  14662. %% \[
  14663. %% \begin{array}{rcl}
  14664. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14665. %% \MID \VOID{} } \\
  14666. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14667. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14668. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14669. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14670. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14671. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14672. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14673. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14674. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14675. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14676. %% \end{array}
  14677. %% \]
  14678. %% \end{minipage}
  14679. %% }
  14680. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14681. %% \label{fig:Lfun-anf-syntax}
  14682. %% \end{figure}
  14683. \section{Explicate Control and the \LangCFun{} Language}
  14684. \label{sec:explicate-control-r4}
  14685. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14686. output of \code{explicate\_control}.
  14687. %
  14688. %% \racket{(The concrete syntax is given in
  14689. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14690. %
  14691. The auxiliary functions for assignment\racket{ and tail contexts} should
  14692. be updated with cases for
  14693. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14694. function for predicate context should be updated for
  14695. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14696. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14697. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14698. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14699. auxiliary function for processing function definitions. This code is
  14700. similar to the case for \code{Program} in \LangVec{}. The top-level
  14701. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14702. form of \LangFun{} can then apply this new function to all the
  14703. function definitions.
  14704. {\if\edition\pythonEd\pythonColor
  14705. The translation of \code{Return} statements requires a new auxiliary
  14706. function to handle expressions in tail context, called
  14707. \code{explicate\_tail}. The function should take an expression and the
  14708. dictionary of basic blocks and produce a list of statements in the
  14709. \LangCFun{} language. The \code{explicate\_tail} function should
  14710. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14711. and a default case for other kinds of expressions. The default case
  14712. should produce a \code{Return} statement. The case for \code{Call}
  14713. should change it into \code{TailCall}. The other cases should
  14714. recursively process their subexpressions and statements, choosing the
  14715. appropriate explicate functions for the various contexts.
  14716. \fi}
  14717. \newcommand{\CfunASTRacket}{
  14718. \begin{array}{lcl}
  14719. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14720. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14721. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14722. \end{array}
  14723. }
  14724. \newcommand{\CfunASTPython}{
  14725. \begin{array}{lcl}
  14726. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14727. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14728. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14729. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14730. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14731. \end{array}
  14732. }
  14733. \begin{figure}[tp]
  14734. \begin{tcolorbox}[colback=white]
  14735. \footnotesize
  14736. {\if\edition\racketEd
  14737. \[
  14738. \begin{array}{l}
  14739. \gray{\CvarASTRacket} \\ \hline
  14740. \gray{\CifASTRacket} \\ \hline
  14741. \gray{\CloopASTRacket} \\ \hline
  14742. \gray{\CtupASTRacket} \\ \hline
  14743. \CfunASTRacket \\
  14744. \begin{array}{lcl}
  14745. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14746. \end{array}
  14747. \end{array}
  14748. \]
  14749. \fi}
  14750. {\if\edition\pythonEd\pythonColor
  14751. \[
  14752. \begin{array}{l}
  14753. \gray{\CifASTPython} \\ \hline
  14754. \gray{\CtupASTPython} \\ \hline
  14755. \CfunASTPython \\
  14756. \begin{array}{lcl}
  14757. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14758. \end{array}
  14759. \end{array}
  14760. \]
  14761. \fi}
  14762. \end{tcolorbox}
  14763. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14764. \label{fig:c3-syntax}
  14765. \index{subject}{Cfun@\LangCFun{} abstract syntax}
  14766. \end{figure}
  14767. \clearpage
  14768. \section{Select Instructions and the \LangXIndCall{} Language}
  14769. \label{sec:select-r4}
  14770. \index{subject}{select instructions}
  14771. The output of select instructions is a program in the \LangXIndCall{}
  14772. language; the definition of its concrete syntax is shown in
  14773. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14774. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14775. directive on the labels of function definitions to make sure the
  14776. bottom three bits are zero, which we put to use in
  14777. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14778. this section. \index{subject}{x86}
  14779. \newcommand{\GrammarXIndCall}{
  14780. \begin{array}{lcl}
  14781. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14782. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14783. \Block &::= & \Instr^{+} \\
  14784. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14785. \end{array}
  14786. }
  14787. \newcommand{\ASTXIndCallRacket}{
  14788. \begin{array}{lcl}
  14789. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14790. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14791. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14792. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14793. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14794. \end{array}
  14795. }
  14796. \begin{figure}[tp]
  14797. \begin{tcolorbox}[colback=white]
  14798. \small
  14799. \[
  14800. \begin{array}{l}
  14801. \gray{\GrammarXInt} \\ \hline
  14802. \gray{\GrammarXIf} \\ \hline
  14803. \gray{\GrammarXGlobal} \\ \hline
  14804. \GrammarXIndCall \\
  14805. \begin{array}{lcl}
  14806. \LangXIndCallM{} &::= & \Def^{*}
  14807. \end{array}
  14808. \end{array}
  14809. \]
  14810. \end{tcolorbox}
  14811. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14812. \label{fig:x86-3-concrete}
  14813. \end{figure}
  14814. \begin{figure}[tp]
  14815. \begin{tcolorbox}[colback=white]
  14816. \small
  14817. {\if\edition\racketEd
  14818. \[\arraycolsep=3pt
  14819. \begin{array}{l}
  14820. \gray{\ASTXIntRacket} \\ \hline
  14821. \gray{\ASTXIfRacket} \\ \hline
  14822. \gray{\ASTXGlobalRacket} \\ \hline
  14823. \ASTXIndCallRacket \\
  14824. \begin{array}{lcl}
  14825. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14826. \end{array}
  14827. \end{array}
  14828. \]
  14829. \fi}
  14830. {\if\edition\pythonEd\pythonColor
  14831. \[
  14832. \begin{array}{lcl}
  14833. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14834. \MID \BYTEREG{\Reg} } \\
  14835. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14836. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14837. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14838. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14839. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14840. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14841. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14842. \end{array}
  14843. \]
  14844. \fi}
  14845. \end{tcolorbox}
  14846. \caption{The abstract syntax of \LangXIndCall{} (extends
  14847. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14848. \label{fig:x86-3}
  14849. \end{figure}
  14850. An assignment of a function reference to a variable becomes a
  14851. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14852. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14853. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14854. node, whose concrete syntax is instruction-pointer-relative
  14855. addressing.
  14856. \begin{center}
  14857. \begin{tabular}{lcl}
  14858. \begin{minipage}{0.35\textwidth}
  14859. {\if\edition\racketEd
  14860. \begin{lstlisting}
  14861. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14862. \end{lstlisting}
  14863. \fi}
  14864. {\if\edition\pythonEd\pythonColor
  14865. \begin{lstlisting}
  14866. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14867. \end{lstlisting}
  14868. \fi}
  14869. \end{minipage}
  14870. &
  14871. $\Rightarrow$\qquad\qquad
  14872. &
  14873. \begin{minipage}{0.3\textwidth}
  14874. \begin{lstlisting}
  14875. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14876. \end{lstlisting}
  14877. \end{minipage}
  14878. \end{tabular}
  14879. \end{center}
  14880. Regarding function definitions, we need to remove the parameters and
  14881. instead perform parameter passing using the conventions discussed in
  14882. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14883. registers. We recommend turning the parameters into local variables
  14884. and generating instructions at the beginning of the function to move
  14885. from the argument-passing registers
  14886. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14887. {\if\edition\racketEd
  14888. \begin{lstlisting}
  14889. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14890. |$\Rightarrow$|
  14891. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14892. \end{lstlisting}
  14893. \fi}
  14894. {\if\edition\pythonEd\pythonColor
  14895. \begin{lstlisting}
  14896. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14897. |$\Rightarrow$|
  14898. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14899. \end{lstlisting}
  14900. \fi}
  14901. The basic blocks $B'$ are the same as $B$ except that the
  14902. \code{start} block is modified to add the instructions for moving from
  14903. the argument registers to the parameter variables. So the \code{start}
  14904. block of $B$ shown on the left of the following is changed to the code
  14905. on the right:
  14906. \begin{center}
  14907. \begin{minipage}{0.3\textwidth}
  14908. \begin{lstlisting}
  14909. start:
  14910. |$\itm{instr}_1$|
  14911. |$\cdots$|
  14912. |$\itm{instr}_n$|
  14913. \end{lstlisting}
  14914. \end{minipage}
  14915. $\Rightarrow$
  14916. \begin{minipage}{0.3\textwidth}
  14917. \begin{lstlisting}
  14918. |$f$|start:
  14919. movq %rdi, |$x_1$|
  14920. movq %rsi, |$x_2$|
  14921. |$\cdots$|
  14922. |$\itm{instr}_1$|
  14923. |$\cdots$|
  14924. |$\itm{instr}_n$|
  14925. \end{lstlisting}
  14926. \end{minipage}
  14927. \end{center}
  14928. Recall that we use the label \code{start} for the initial block of a
  14929. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14930. the conclusion of the program with \code{conclusion}, so that
  14931. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14932. by a jump to \code{conclusion}. With the addition of function
  14933. definitions, there is a start block and conclusion for each function,
  14934. but their labels need to be unique. We recommend prepending the
  14935. function's name to \code{start} and \code{conclusion}, respectively,
  14936. to obtain unique labels.
  14937. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14938. number of parameters the function expects, but the parameters are no
  14939. longer in the syntax of function definitions. Instead, add an entry
  14940. to $\itm{info}$ that maps \code{num-params} to the number of
  14941. parameters to construct $\itm{info}'$.}
  14942. By changing the parameters to local variables, we are giving the
  14943. register allocator control over which registers or stack locations to
  14944. use for them. If you implement the move-biasing challenge
  14945. (section~\ref{sec:move-biasing}), the register allocator will try to
  14946. assign the parameter variables to the corresponding argument register,
  14947. in which case the \code{patch\_instructions} pass will remove the
  14948. \code{movq} instruction. This happens in the example translation given
  14949. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14950. the \code{add} function.
  14951. %
  14952. Also, note that the register allocator will perform liveness analysis
  14953. on this sequence of move instructions and build the interference
  14954. graph. So, for example, $x_1$ will be marked as interfering with
  14955. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14956. which is good because otherwise the first \code{movq} would overwrite
  14957. the argument in \code{rsi} that is needed for $x_2$.
  14958. Next, consider the compilation of function calls. In the mirror image
  14959. of the handling of parameters in function definitions, the arguments
  14960. are moved to the argument-passing registers. Note that the function
  14961. is not given as a label, but its address is produced by the argument
  14962. $\itm{arg}_0$. So, we translate the call into an indirect function
  14963. call. The return value from the function is stored in \code{rax}, so
  14964. it needs to be moved into the \itm{lhs}.
  14965. \begin{lstlisting}
  14966. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  14967. |$\Rightarrow$|
  14968. movq |$\itm{arg}_1$|, %rdi
  14969. movq |$\itm{arg}_2$|, %rsi
  14970. |$\vdots$|
  14971. callq *|$\itm{arg}_0$|
  14972. movq %rax, |$\itm{lhs}$|
  14973. \end{lstlisting}
  14974. The \code{IndirectCallq} AST node includes an integer for the arity of
  14975. the function, that is, the number of parameters. That information is
  14976. useful in the \code{uncover\_live} pass for determining which
  14977. argument-passing registers are potentially read during the call.
  14978. For tail calls, the parameter passing is the same as non-tail calls:
  14979. generate instructions to move the arguments into the argument-passing
  14980. registers. After that we need to pop the frame from the procedure
  14981. call stack. However, we do not yet know how big the frame is; that
  14982. gets determined during register allocation. So, instead of generating
  14983. those instructions here, we invent a new instruction that means ``pop
  14984. the frame and then do an indirect jump,'' which we name
  14985. \code{TailJmp}. The abstract syntax for this instruction includes an
  14986. argument that specifies where to jump and an integer that represents
  14987. the arity of the function being called.
  14988. \section{Register Allocation}
  14989. \label{sec:register-allocation-r4}
  14990. The addition of functions requires some changes to all three aspects
  14991. of register allocation, which we discuss in the following subsections.
  14992. \subsection{Liveness Analysis}
  14993. \label{sec:liveness-analysis-r4}
  14994. \index{subject}{liveness analysis}
  14995. %% The rest of the passes need only minor modifications to handle the new
  14996. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14997. %% \code{leaq}.
  14998. The \code{IndirectCallq} instruction should be treated like
  14999. \code{Callq} regarding its written locations $W$, in that they should
  15000. include all the caller-saved registers. Recall that the reason for
  15001. that is to force variables that are live across a function call to be assigned to callee-saved
  15002. registers or to be spilled to the stack.
  15003. Regarding the set of read locations $R$, the arity fields of
  15004. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  15005. argument-passing registers should be considered as read by those
  15006. instructions. Also, the target field of \code{TailJmp} and
  15007. \code{IndirectCallq} should be included in the set of read locations
  15008. $R$.
  15009. \subsection{Build Interference Graph}
  15010. \label{sec:build-interference-r4}
  15011. With the addition of function definitions, we compute a separate interference
  15012. graph for each function (not just one for the whole program).
  15013. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  15014. spill tuple-typed variables that are live during a call to
  15015. \code{collect}, the garbage collector. With the addition of functions
  15016. to our language, we need to revisit this issue. Functions that perform
  15017. allocation contain calls to the collector. Thus, we should not only
  15018. spill a tuple-typed variable when it is live during a call to
  15019. \code{collect}, but we should spill the variable if it is live during
  15020. a call to any user-defined function. Thus, in the
  15021. \code{build\_interference} pass, we recommend adding interference
  15022. edges between call-live tuple-typed variables and the callee-saved
  15023. registers (in addition to creating edges between
  15024. call-live variables and the caller-saved registers).
  15025. \subsection{Allocate Registers}
  15026. The primary change to the \code{allocate\_registers} pass is adding an
  15027. auxiliary function for handling definitions (the \Def{} nonterminal
  15028. shown in figure~\ref{fig:x86-3}) with one case for function
  15029. definitions. The logic is the same as described in
  15030. chapter~\ref{ch:register-allocation-Lvar} except that now register
  15031. allocation is performed many times, once for each function definition,
  15032. instead of just once for the whole program.
  15033. \section{Patch Instructions}
  15034. In \code{patch\_instructions}, you should deal with the x86
  15035. idiosyncrasy that the destination argument of \code{leaq} must be a
  15036. register. Additionally, you should ensure that the argument of
  15037. \code{TailJmp} is \itm{rax}, our reserved register---because we
  15038. trample many other registers before the tail call, as explained in the
  15039. next section.
  15040. \section{Generate Prelude and Conclusion}
  15041. Now that register allocation is complete, we can translate the
  15042. \code{TailJmp} into a sequence of instructions. A naive translation of
  15043. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15044. before the jump we need to pop the current frame to achieve efficient
  15045. tail calls. This sequence of instructions is the same as the code for
  15046. the conclusion of a function, except that the \code{retq} is replaced with
  15047. \code{jmp *$\itm{arg}$}.
  15048. Regarding function definitions, we generate a prelude and conclusion
  15049. for each one. This code is similar to the prelude and conclusion
  15050. generated for the \code{main} function presented in
  15051. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15052. carry out the following steps:
  15053. % TODO: .align the functions!
  15054. \begin{enumerate}
  15055. %% \item Start with \code{.global} and \code{.align} directives followed
  15056. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15057. %% example.)
  15058. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15059. pointer.
  15060. \item Push to the stack all the callee-saved registers that were
  15061. used for register allocation.
  15062. \item Move the stack pointer \code{rsp} down to make room for the
  15063. regular spills (aligned to 16 bytes).
  15064. \item Move the root stack pointer \code{r15} up by the size of the
  15065. root-stack frame for this function, which depends on the number of
  15066. spilled tuple-typed variables. \label{root-stack-init}
  15067. \item Initialize to zero all new entries in the root-stack frame.
  15068. \item Jump to the start block.
  15069. \end{enumerate}
  15070. The prelude of the \code{main} function has an additional task: call
  15071. the \code{initialize} function to set up the garbage collector, and
  15072. then move the value of the global \code{rootstack\_begin} in
  15073. \code{r15}. This initialization should happen before step
  15074. \ref{root-stack-init}, which depends on \code{r15}.
  15075. The conclusion of every function should do the following:
  15076. \begin{enumerate}
  15077. \item Move the stack pointer back up past the regular spills.
  15078. \item Restore the callee-saved registers by popping them from the
  15079. stack.
  15080. \item Move the root stack pointer back down by the size of the
  15081. root-stack frame for this function.
  15082. \item Restore \code{rbp} by popping it from the stack.
  15083. \item Return to the caller with the \code{retq} instruction.
  15084. \end{enumerate}
  15085. The output of this pass is \LangXIndCallFlat{}, which differs from
  15086. \LangXIndCall{} in that there is no longer an AST node for function
  15087. definitions. Instead, a program is just
  15088. \racket{an association list}\python{a dictionary}
  15089. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15090. {\if\edition\racketEd
  15091. \[
  15092. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15093. \]
  15094. \fi}
  15095. {\if\edition\pythonEd
  15096. \[
  15097. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15098. \]
  15099. \fi}
  15100. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15101. compiling \LangFun{} to x86.
  15102. \begin{exercise}\normalfont\normalsize
  15103. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15104. Create eight new programs that use functions including examples that
  15105. pass functions and return functions from other functions, recursive
  15106. functions, functions that create tuples, and functions that make tail
  15107. calls. Test your compiler on these new programs and all your
  15108. previously created test programs.
  15109. \end{exercise}
  15110. \begin{figure}[tbp]
  15111. \begin{tcolorbox}[colback=white]
  15112. {\if\edition\racketEd
  15113. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15114. \node (Lfun) at (0,2) {\large \LangFun{}};
  15115. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15116. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15117. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15118. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15119. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15120. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15121. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15122. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15123. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15124. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15125. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15126. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15127. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15128. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15129. \path[->,bend left=15] (Lfun) edge [above] node
  15130. {\ttfamily\footnotesize shrink} (Lfun-1);
  15131. \path[->,bend left=15] (Lfun-1) edge [above] node
  15132. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15133. \path[->,bend left=15] (Lfun-2) edge [above] node
  15134. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15135. \path[->,bend left=15] (F1-1) edge [left] node
  15136. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15137. \path[->,bend left=15] (F1-2) edge [below] node
  15138. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15139. \path[->,bend left=15] (F1-3) edge [below] node
  15140. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15141. \path[->,bend right=15] (F1-4) edge [above] node
  15142. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15143. \path[->,bend right=15] (F1-5) edge [right] node
  15144. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15145. \path[->,bend right=15] (C3-2) edge [right] node
  15146. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15147. \path[->,bend left=15] (x86-2) edge [right] node
  15148. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15149. \path[->,bend right=15] (x86-2-1) edge [below] node
  15150. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15151. \path[->,bend right=15] (x86-2-2) edge [right] node
  15152. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15153. \path[->,bend left=15] (x86-3) edge [above] node
  15154. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15155. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15156. \end{tikzpicture}
  15157. \fi}
  15158. {\if\edition\pythonEd\pythonColor
  15159. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15160. \node (Lfun) at (0,2) {\large \LangFun{}};
  15161. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15162. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15163. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15164. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15165. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15166. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15167. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15168. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15169. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15170. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15171. \path[->,bend left=15] (Lfun) edge [above] node
  15172. {\ttfamily\footnotesize shrink} (Lfun-2);
  15173. \path[->,bend left=15] (Lfun-2) edge [above] node
  15174. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15175. \path[->,bend left=15] (F1-1) edge [above] node
  15176. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15177. \path[->,bend left=15] (F1-2) edge [right] node
  15178. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15179. \path[->,bend right=15] (F1-4) edge [above] node
  15180. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15181. \path[->,bend right=15] (F1-5) edge [right] node
  15182. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15183. \path[->,bend left=15] (C3-2) edge [right] node
  15184. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15185. \path[->,bend right=15] (x86-2) edge [below] node
  15186. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15187. \path[->,bend left=15] (x86-3) edge [above] node
  15188. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15189. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15190. \end{tikzpicture}
  15191. \fi}
  15192. \end{tcolorbox}
  15193. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15194. \label{fig:Lfun-passes}
  15195. \end{figure}
  15196. \section{An Example Translation}
  15197. \label{sec:functions-example}
  15198. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15199. function in \LangFun{} to x86. The figure includes the results of
  15200. \code{explicate\_control} and \code{select\_instructions}.
  15201. \begin{figure}[hbtp]
  15202. \begin{tcolorbox}[colback=white]
  15203. \begin{tabular}{ll}
  15204. \begin{minipage}{0.4\textwidth}
  15205. % s3_2.rkt
  15206. {\if\edition\racketEd
  15207. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15208. (define (add [x : Integer]
  15209. [y : Integer])
  15210. : Integer
  15211. (+ x y))
  15212. (add 40 2)
  15213. \end{lstlisting}
  15214. \fi}
  15215. {\if\edition\pythonEd\pythonColor
  15216. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15217. def add(x:int, y:int) -> int:
  15218. return x + y
  15219. print(add(40, 2))
  15220. \end{lstlisting}
  15221. \fi}
  15222. $\Downarrow$
  15223. {\if\edition\racketEd
  15224. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15225. (define (add86 [x87 : Integer]
  15226. [y88 : Integer])
  15227. : Integer
  15228. add86start:
  15229. return (+ x87 y88);
  15230. )
  15231. (define (main) : Integer ()
  15232. mainstart:
  15233. tmp89 = (fun-ref add86 2);
  15234. (tail-call tmp89 40 2)
  15235. )
  15236. \end{lstlisting}
  15237. \fi}
  15238. {\if\edition\pythonEd\pythonColor
  15239. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15240. def add(x:int, y:int) -> int:
  15241. addstart:
  15242. return x + y
  15243. def main() -> int:
  15244. mainstart:
  15245. fun.0 = add
  15246. tmp.1 = fun.0(40, 2)
  15247. print(tmp.1)
  15248. return 0
  15249. \end{lstlisting}
  15250. \fi}
  15251. \end{minipage}
  15252. &
  15253. $\Rightarrow$
  15254. \begin{minipage}{0.5\textwidth}
  15255. {\if\edition\racketEd
  15256. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15257. (define (add86) : Integer
  15258. add86start:
  15259. movq %rdi, x87
  15260. movq %rsi, y88
  15261. movq x87, %rax
  15262. addq y88, %rax
  15263. jmp inc1389conclusion
  15264. )
  15265. (define (main) : Integer
  15266. mainstart:
  15267. leaq (fun-ref add86 2), tmp89
  15268. movq $40, %rdi
  15269. movq $2, %rsi
  15270. tail-jmp tmp89
  15271. )
  15272. \end{lstlisting}
  15273. \fi}
  15274. {\if\edition\pythonEd\pythonColor
  15275. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15276. def add() -> int:
  15277. addstart:
  15278. movq %rdi, x
  15279. movq %rsi, y
  15280. movq x, %rax
  15281. addq y, %rax
  15282. jmp addconclusion
  15283. def main() -> int:
  15284. mainstart:
  15285. leaq add, fun.0
  15286. movq $40, %rdi
  15287. movq $2, %rsi
  15288. callq *fun.0
  15289. movq %rax, tmp.1
  15290. movq tmp.1, %rdi
  15291. callq print_int
  15292. movq $0, %rax
  15293. jmp mainconclusion
  15294. \end{lstlisting}
  15295. \fi}
  15296. $\Downarrow$
  15297. \end{minipage}
  15298. \end{tabular}
  15299. \begin{tabular}{ll}
  15300. \begin{minipage}{0.3\textwidth}
  15301. {\if\edition\racketEd
  15302. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15303. .globl add86
  15304. .align 8
  15305. add86:
  15306. pushq %rbp
  15307. movq %rsp, %rbp
  15308. jmp add86start
  15309. add86start:
  15310. movq %rdi, %rax
  15311. addq %rsi, %rax
  15312. jmp add86conclusion
  15313. add86conclusion:
  15314. popq %rbp
  15315. retq
  15316. \end{lstlisting}
  15317. \fi}
  15318. {\if\edition\pythonEd\pythonColor
  15319. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15320. .align 8
  15321. add:
  15322. pushq %rbp
  15323. movq %rsp, %rbp
  15324. subq $0, %rsp
  15325. jmp addstart
  15326. addstart:
  15327. movq %rdi, %rdx
  15328. movq %rsi, %rcx
  15329. movq %rdx, %rax
  15330. addq %rcx, %rax
  15331. jmp addconclusion
  15332. addconclusion:
  15333. subq $0, %r15
  15334. addq $0, %rsp
  15335. popq %rbp
  15336. retq
  15337. \end{lstlisting}
  15338. \fi}
  15339. \end{minipage}
  15340. &
  15341. \begin{minipage}{0.5\textwidth}
  15342. {\if\edition\racketEd
  15343. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15344. .globl main
  15345. .align 8
  15346. main:
  15347. pushq %rbp
  15348. movq %rsp, %rbp
  15349. movq $16384, %rdi
  15350. movq $16384, %rsi
  15351. callq initialize
  15352. movq rootstack_begin(%rip), %r15
  15353. jmp mainstart
  15354. mainstart:
  15355. leaq add86(%rip), %rcx
  15356. movq $40, %rdi
  15357. movq $2, %rsi
  15358. movq %rcx, %rax
  15359. popq %rbp
  15360. jmp *%rax
  15361. mainconclusion:
  15362. popq %rbp
  15363. retq
  15364. \end{lstlisting}
  15365. \fi}
  15366. {\if\edition\pythonEd\pythonColor
  15367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15368. .globl main
  15369. .align 8
  15370. main:
  15371. pushq %rbp
  15372. movq %rsp, %rbp
  15373. subq $0, %rsp
  15374. movq $65536, %rdi
  15375. movq $65536, %rsi
  15376. callq initialize
  15377. movq rootstack_begin(%rip), %r15
  15378. jmp mainstart
  15379. mainstart:
  15380. leaq add(%rip), %rcx
  15381. movq $40, %rdi
  15382. movq $2, %rsi
  15383. callq *%rcx
  15384. movq %rax, %rcx
  15385. movq %rcx, %rdi
  15386. callq print_int
  15387. movq $0, %rax
  15388. jmp mainconclusion
  15389. mainconclusion:
  15390. subq $0, %r15
  15391. addq $0, %rsp
  15392. popq %rbp
  15393. retq
  15394. \end{lstlisting}
  15395. \fi}
  15396. \end{minipage}
  15397. \end{tabular}
  15398. \end{tcolorbox}
  15399. \caption{Example compilation of a simple function to x86.}
  15400. \label{fig:add-fun}
  15401. \end{figure}
  15402. % Challenge idea: inlining! (simple version)
  15403. % Further Reading
  15404. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15405. \chapter{Lexically Scoped Functions}
  15406. \label{ch:Llambda}
  15407. \setcounter{footnote}{0}
  15408. This chapter studies lexically scoped functions. Lexical
  15409. scoping\index{subject}{lexical scoping} means that a function's body
  15410. may refer to variables whose binding site is outside of the function,
  15411. in an enclosing scope.
  15412. %
  15413. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15414. in \LangLam{}, which extends \LangFun{} with the
  15415. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15416. functions. The body of the \key{lambda} refers to three variables:
  15417. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15418. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15419. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15420. function \code{f}}, and \code{x} is a parameter of function
  15421. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15422. result value. The main expression of the program includes two calls to
  15423. \code{f} with different arguments for \code{x}: first \code{5} and
  15424. then \code{3}. The functions returned from \code{f} are bound to
  15425. variables \code{g} and \code{h}. Even though these two functions were
  15426. created by the same \code{lambda}, they are really different functions
  15427. because they use different values for \code{x}. Applying \code{g} to
  15428. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15429. produces \code{22}, so the result of the program is \code{42}.
  15430. \begin{figure}[btp]
  15431. \begin{tcolorbox}[colback=white]
  15432. {\if\edition\racketEd
  15433. % lambda_test_21.rkt
  15434. \begin{lstlisting}
  15435. (define (f [x : Integer]) : (Integer -> Integer)
  15436. (let ([y 4])
  15437. (lambda: ([z : Integer]) : Integer
  15438. (+ x (+ y z)))))
  15439. (let ([g (f 5)])
  15440. (let ([h (f 3)])
  15441. (+ (g 11) (h 15))))
  15442. \end{lstlisting}
  15443. \fi}
  15444. {\if\edition\pythonEd\pythonColor
  15445. \begin{lstlisting}
  15446. def f(x : int) -> Callable[[int], int]:
  15447. y = 4
  15448. return lambda z: x + y + z
  15449. g = f(5)
  15450. h = f(3)
  15451. print(g(11) + h(15))
  15452. \end{lstlisting}
  15453. \fi}
  15454. \end{tcolorbox}
  15455. \caption{Example of a lexically scoped function.}
  15456. \label{fig:lexical-scoping}
  15457. \end{figure}
  15458. The approach that we take for implementing lexically scoped functions
  15459. is to compile them into top-level function definitions, translating
  15460. from \LangLam{} into \LangFun{}. However, the compiler must give
  15461. special treatment to variable occurrences such as \code{x} and
  15462. \code{y} in the body of the \code{lambda} shown in
  15463. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15464. may not refer to variables defined outside of it. To identify such
  15465. variable occurrences, we review the standard notion of free variable.
  15466. \begin{definition}\normalfont
  15467. A variable is \emph{free in expression} $e$ if the variable occurs
  15468. inside $e$ but does not have an enclosing definition that is also in
  15469. $e$.\index{subject}{free variable}
  15470. \end{definition}
  15471. For example, in the expression
  15472. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15473. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15474. only \code{x} and \code{y} are free in the following expression,
  15475. because \code{z} is defined by the \code{lambda}
  15476. {\if\edition\racketEd
  15477. \begin{lstlisting}
  15478. (lambda: ([z : Integer]) : Integer
  15479. (+ x (+ y z)))
  15480. \end{lstlisting}
  15481. \fi}
  15482. {\if\edition\pythonEd\pythonColor
  15483. \begin{lstlisting}
  15484. lambda z: x + y + z
  15485. \end{lstlisting}
  15486. \fi}
  15487. %
  15488. \noindent Thus the free variables of a \code{lambda} are the ones that
  15489. need special treatment. We need to transport at runtime the values
  15490. of those variables from the point where the \code{lambda} was created
  15491. to the point where the \code{lambda} is applied. An efficient solution
  15492. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15493. values of the free variables together with a function pointer into a
  15494. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15495. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15496. closure}
  15497. %
  15498. By design, we have all the ingredients to make closures:
  15499. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15500. function pointers. The function pointer resides at index $0$, and the
  15501. values for the free variables fill in the rest of the tuple.
  15502. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15503. to see how closures work. It is a three-step dance. The program calls
  15504. function \code{f}, which creates a closure for the \code{lambda}. The
  15505. closure is a tuple whose first element is a pointer to the top-level
  15506. function that we will generate for the \code{lambda}; the second
  15507. element is the value of \code{x}, which is \code{5}; and the third
  15508. element is \code{4}, the value of \code{y}. The closure does not
  15509. contain an element for \code{z} because \code{z} is not a free
  15510. variable of the \code{lambda}. Creating the closure is step 1 of the
  15511. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15512. shown in figure~\ref{fig:closures}.
  15513. %
  15514. The second call to \code{f} creates another closure, this time with
  15515. \code{3} in the second slot (for \code{x}). This closure is also
  15516. returned from \code{f} but bound to \code{h}, which is also shown in
  15517. figure~\ref{fig:closures}.
  15518. \begin{figure}[tbp]
  15519. \centering
  15520. \begin{minipage}{0.65\textwidth}
  15521. \begin{tcolorbox}[colback=white]
  15522. \includegraphics[width=\textwidth]{figs/closures}
  15523. \end{tcolorbox}
  15524. \end{minipage}
  15525. \caption{Flat closure representations for the two functions
  15526. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15527. \label{fig:closures}
  15528. \end{figure}
  15529. Continuing with the example, consider the application of \code{g} to
  15530. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15531. closure, we obtain the function pointer from the first element of the
  15532. closure and call it, passing in the closure itself and then the
  15533. regular arguments, in this case \code{11}. This technique for applying
  15534. a closure is step 2 of the dance.
  15535. %
  15536. But doesn't this \code{lambda} take only one argument, for parameter
  15537. \code{z}? The third and final step of the dance is generating a
  15538. top-level function for a \code{lambda}. We add an additional
  15539. parameter for the closure and insert an initialization at the beginning
  15540. of the function for each free variable, to bind those variables to the
  15541. appropriate elements from the closure parameter.
  15542. %
  15543. This three-step dance is known as \emph{closure
  15544. conversion}\index{subject}{closure conversion}. We discuss the
  15545. details of closure conversion in section~\ref{sec:closure-conversion}
  15546. and show the code generated from the example in
  15547. section~\ref{sec:example-lambda}. First, we define the syntax and
  15548. semantics of \LangLam{} in section~\ref{sec:r5}.
  15549. \section{The \LangLam{} Language}
  15550. \label{sec:r5}
  15551. The definitions of the concrete syntax and abstract syntax for
  15552. \LangLam{}, a language with anonymous functions and lexical scoping,
  15553. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15554. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15555. for \LangFun{}, which already has syntax for function application.
  15556. %
  15557. \python{The syntax also includes an assignment statement that includes
  15558. a type annotation for the variable on the left-hand side, which
  15559. facilitates the type checking of \code{lambda} expressions that we
  15560. discuss later in this section.}
  15561. %
  15562. \racket{The \code{procedure-arity} operation returns the number of parameters
  15563. of a given function, an operation that we need for the translation
  15564. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15565. %
  15566. \python{The \code{arity} operation returns the number of parameters of
  15567. a given function, an operation that we need for the translation
  15568. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15569. The \code{arity} operation is not in Python, but the same functionality
  15570. is available in a more complex form. We include \code{arity} in the
  15571. \LangLam{} source language to enable testing.}
  15572. \newcommand{\LlambdaGrammarRacket}{
  15573. \begin{array}{lcl}
  15574. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15575. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15576. \end{array}
  15577. }
  15578. \newcommand{\LlambdaASTRacket}{
  15579. \begin{array}{lcl}
  15580. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15581. \itm{op} &::=& \code{procedure-arity}
  15582. \end{array}
  15583. }
  15584. \newcommand{\LlambdaGrammarPython}{
  15585. \begin{array}{lcl}
  15586. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15587. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15588. \end{array}
  15589. }
  15590. \newcommand{\LlambdaASTPython}{
  15591. \begin{array}{lcl}
  15592. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15593. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15594. \end{array}
  15595. }
  15596. % include AnnAssign in ASTPython
  15597. \begin{figure}[tp]
  15598. \centering
  15599. \begin{tcolorbox}[colback=white]
  15600. \small
  15601. {\if\edition\racketEd
  15602. \[
  15603. \begin{array}{l}
  15604. \gray{\LintGrammarRacket{}} \\ \hline
  15605. \gray{\LvarGrammarRacket{}} \\ \hline
  15606. \gray{\LifGrammarRacket{}} \\ \hline
  15607. \gray{\LwhileGrammarRacket} \\ \hline
  15608. \gray{\LtupGrammarRacket} \\ \hline
  15609. \gray{\LfunGrammarRacket} \\ \hline
  15610. \LlambdaGrammarRacket \\
  15611. \begin{array}{lcl}
  15612. \LangLamM{} &::=& \Def\ldots \; \Exp
  15613. \end{array}
  15614. \end{array}
  15615. \]
  15616. \fi}
  15617. {\if\edition\pythonEd\pythonColor
  15618. \[
  15619. \begin{array}{l}
  15620. \gray{\LintGrammarPython{}} \\ \hline
  15621. \gray{\LvarGrammarPython{}} \\ \hline
  15622. \gray{\LifGrammarPython{}} \\ \hline
  15623. \gray{\LwhileGrammarPython} \\ \hline
  15624. \gray{\LtupGrammarPython} \\ \hline
  15625. \gray{\LfunGrammarPython} \\ \hline
  15626. \LlambdaGrammarPython \\
  15627. \begin{array}{lcl}
  15628. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15629. \end{array}
  15630. \end{array}
  15631. \]
  15632. \fi}
  15633. \end{tcolorbox}
  15634. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15635. with \key{lambda}.}
  15636. \label{fig:Llam-concrete-syntax}
  15637. \index{subject}{Llambda@\LangLam{} concrete syntax}
  15638. \end{figure}
  15639. \begin{figure}[tp]
  15640. \centering
  15641. \begin{tcolorbox}[colback=white]
  15642. \small
  15643. {\if\edition\racketEd
  15644. \[\arraycolsep=3pt
  15645. \begin{array}{l}
  15646. \gray{\LintOpAST} \\ \hline
  15647. \gray{\LvarASTRacket{}} \\ \hline
  15648. \gray{\LifASTRacket{}} \\ \hline
  15649. \gray{\LwhileASTRacket{}} \\ \hline
  15650. \gray{\LtupASTRacket{}} \\ \hline
  15651. \gray{\LfunASTRacket} \\ \hline
  15652. \LlambdaASTRacket \\
  15653. \begin{array}{lcl}
  15654. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15655. \end{array}
  15656. \end{array}
  15657. \]
  15658. \fi}
  15659. {\if\edition\pythonEd\pythonColor
  15660. \[
  15661. \begin{array}{l}
  15662. \gray{\LintASTPython} \\ \hline
  15663. \gray{\LvarASTPython{}} \\ \hline
  15664. \gray{\LifASTPython{}} \\ \hline
  15665. \gray{\LwhileASTPython{}} \\ \hline
  15666. \gray{\LtupASTPython{}} \\ \hline
  15667. \gray{\LfunASTPython} \\ \hline
  15668. \LlambdaASTPython \\
  15669. \begin{array}{lcl}
  15670. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15671. \end{array}
  15672. \end{array}
  15673. \]
  15674. \fi}
  15675. \end{tcolorbox}
  15676. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15677. \label{fig:Llam-syntax}
  15678. \index{subject}{Llambda@\LangLam{} abstract syntax}
  15679. \end{figure}
  15680. Figure~\ref{fig:interp-Llambda} shows the definitional
  15681. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15682. \key{Lambda} saves the current environment inside the returned
  15683. function value. Recall that during function application, the
  15684. environment stored in the function value, extended with the mapping of
  15685. parameters to argument values, is used to interpret the body of the
  15686. function.
  15687. \begin{figure}[tbp]
  15688. \begin{tcolorbox}[colback=white]
  15689. {\if\edition\racketEd
  15690. \begin{lstlisting}
  15691. (define interp-Llambda-class
  15692. (class interp-Lfun-class
  15693. (super-new)
  15694. (define/override (interp-op op)
  15695. (match op
  15696. ['procedure-arity
  15697. (lambda (v)
  15698. (match v
  15699. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15700. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15701. [else (super interp-op op)]))
  15702. (define/override ((interp-exp env) e)
  15703. (define recur (interp-exp env))
  15704. (match e
  15705. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15706. `(function ,xs ,body ,env)]
  15707. [else ((super interp-exp env) e)]))
  15708. ))
  15709. (define (interp-Llambda p)
  15710. (send (new interp-Llambda-class) interp-program p))
  15711. \end{lstlisting}
  15712. \fi}
  15713. {\if\edition\pythonEd\pythonColor
  15714. \begin{lstlisting}
  15715. class InterpLlambda(InterpLfun):
  15716. def arity(self, v):
  15717. match v:
  15718. case Function(name, params, body, env):
  15719. return len(params)
  15720. case _:
  15721. raise Exception('Llambda arity unexpected ' + repr(v))
  15722. def interp_exp(self, e, env):
  15723. match e:
  15724. case Call(Name('arity'), [fun]):
  15725. f = self.interp_exp(fun, env)
  15726. return self.arity(f)
  15727. case Lambda(params, body):
  15728. return Function('lambda', params, [Return(body)], env)
  15729. case _:
  15730. return super().interp_exp(e, env)
  15731. def interp_stmt(self, s, env, cont):
  15732. match s:
  15733. case AnnAssign(lhs, typ, value, simple):
  15734. env[lhs.id] = self.interp_exp(value, env)
  15735. return self.interp_stmts(cont, env)
  15736. case Pass():
  15737. return self.interp_stmts(cont, env)
  15738. case _:
  15739. return super().interp_stmt(s, env, cont)
  15740. \end{lstlisting}
  15741. \fi}
  15742. \end{tcolorbox}
  15743. \caption{Interpreter for \LangLam{}.}
  15744. \label{fig:interp-Llambda}
  15745. \end{figure}
  15746. {\if\edition\racketEd
  15747. %
  15748. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15749. \key{lambda} form. The body of the \key{lambda} is checked in an
  15750. environment that includes the current environment (because it is
  15751. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15752. require the body's type to match the declared return type.
  15753. %
  15754. \fi}
  15755. {\if\edition\pythonEd\pythonColor
  15756. %
  15757. Figures~\ref{fig:type-check-Llambda} and
  15758. \ref{fig:type-check-Llambda-part2} define the type checker for
  15759. \LangLam{}, which is more complex than one might expect. The reason
  15760. for the added complexity is that the syntax of \key{lambda} does not
  15761. include type annotations for the parameters or return type. Instead
  15762. they must be inferred. There are many approaches to type inference
  15763. from which to choose, of varying degrees of complexity. We choose one
  15764. of the simpler approaches, bidirectional type
  15765. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15766. book is compilation, not type inference.
  15767. The main idea of bidirectional type inference is to add an auxiliary
  15768. function, here named \code{check\_exp}, that takes an expected type
  15769. and checks whether the given expression is of that type. Thus, in
  15770. \code{check\_exp}, type information flows in a top-down manner with
  15771. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15772. function, where type information flows in a primarily bottom-up
  15773. manner.
  15774. %
  15775. The idea then is to use \code{check\_exp} in all the places where we
  15776. already know what the type of an expression should be, such as in the
  15777. \code{return} statement of a top-level function definition or on the
  15778. right-hand side of an annotated assignment statement.
  15779. With regard to \code{lambda}, it is straightforward to check a
  15780. \code{lambda} inside \code{check\_exp} because the expected type
  15781. provides the parameter types and the return type. On the other hand,
  15782. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15783. that we do not allow \code{lambda} in contexts in which we don't already
  15784. know its type. This restriction does not incur a loss of
  15785. expressiveness for \LangLam{} because it is straightforward to modify
  15786. a program to sidestep the restriction, for example, by using an
  15787. annotated assignment statement to assign the \code{lambda} to a
  15788. temporary variable.
  15789. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15790. checker records their type in a \code{has\_type} field. This type
  15791. information is used further on in this chapter.
  15792. %
  15793. \fi}
  15794. \begin{figure}[tbp]
  15795. \begin{tcolorbox}[colback=white]
  15796. {\if\edition\racketEd
  15797. \begin{lstlisting}
  15798. (define (type-check-Llambda env)
  15799. (lambda (e)
  15800. (match e
  15801. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15802. (define-values (new-body bodyT)
  15803. ((type-check-exp (append (map cons xs Ts) env)) body))
  15804. (define ty `(,@Ts -> ,rT))
  15805. (cond
  15806. [(equal? rT bodyT)
  15807. (values (HasType (Lambda params rT new-body) ty) ty)]
  15808. [else
  15809. (error "mismatch in return type" bodyT rT)])]
  15810. ...
  15811. )))
  15812. \end{lstlisting}
  15813. \fi}
  15814. {\if\edition\pythonEd\pythonColor
  15815. \begin{lstlisting}
  15816. class TypeCheckLlambda(TypeCheckLfun):
  15817. def type_check_exp(self, e, env):
  15818. match e:
  15819. case Name(id):
  15820. e.has_type = env[id]
  15821. return env[id]
  15822. case Lambda(params, body):
  15823. raise Exception('cannot synthesize a type for a lambda')
  15824. case Call(Name('arity'), [func]):
  15825. func_t = self.type_check_exp(func, env)
  15826. match func_t:
  15827. case FunctionType(params_t, return_t):
  15828. return IntType()
  15829. case _:
  15830. raise Exception('in arity, unexpected ' + repr(func_t))
  15831. case _:
  15832. return super().type_check_exp(e, env)
  15833. def check_exp(self, e, ty, env):
  15834. match e:
  15835. case Lambda(params, body):
  15836. e.has_type = ty
  15837. match ty:
  15838. case FunctionType(params_t, return_t):
  15839. new_env = env.copy().update(zip(params, params_t))
  15840. self.check_exp(body, return_t, new_env)
  15841. case _:
  15842. raise Exception('lambda does not have type ' + str(ty))
  15843. case Call(func, args):
  15844. func_t = self.type_check_exp(func, env)
  15845. match func_t:
  15846. case FunctionType(params_t, return_t):
  15847. for (arg, param_t) in zip(args, params_t):
  15848. self.check_exp(arg, param_t, env)
  15849. self.check_type_equal(return_t, ty, e)
  15850. case _:
  15851. raise Exception('type_check_exp: in call, unexpected ' + \
  15852. repr(func_t))
  15853. case _:
  15854. t = self.type_check_exp(e, env)
  15855. self.check_type_equal(t, ty, e)
  15856. \end{lstlisting}
  15857. \fi}
  15858. \end{tcolorbox}
  15859. \caption{Type checking \LangLam{}\python{, part 1}.}
  15860. \label{fig:type-check-Llambda}
  15861. \end{figure}
  15862. {\if\edition\pythonEd\pythonColor
  15863. \begin{figure}[tbp]
  15864. \begin{tcolorbox}[colback=white]
  15865. \begin{lstlisting}
  15866. def check_stmts(self, ss, return_ty, env):
  15867. if len(ss) == 0:
  15868. return
  15869. match ss[0]:
  15870. case FunctionDef(name, params, body, dl, returns, comment):
  15871. new_env = env.copy().update(params)
  15872. rt = self.check_stmts(body, returns, new_env)
  15873. self.check_stmts(ss[1:], return_ty, env)
  15874. case Return(value):
  15875. self.check_exp(value, return_ty, env)
  15876. case Assign([Name(id)], value):
  15877. if id in env:
  15878. self.check_exp(value, env[id], env)
  15879. else:
  15880. env[id] = self.type_check_exp(value, env)
  15881. self.check_stmts(ss[1:], return_ty, env)
  15882. case Assign([Subscript(tup, Constant(index), Store())], value):
  15883. tup_t = self.type_check_exp(tup, env)
  15884. match tup_t:
  15885. case TupleType(ts):
  15886. self.check_exp(value, ts[index], env)
  15887. case _:
  15888. raise Exception('expected a tuple, not ' + repr(tup_t))
  15889. self.check_stmts(ss[1:], return_ty, env)
  15890. case AnnAssign(Name(id), ty_annot, value, simple):
  15891. ss[0].annotation = ty_annot
  15892. if id in env:
  15893. self.check_type_equal(env[id], ty_annot)
  15894. else:
  15895. env[id] = ty_annot
  15896. self.check_exp(value, ty_annot, env)
  15897. self.check_stmts(ss[1:], return_ty, env)
  15898. case _:
  15899. self.type_check_stmts(ss, env)
  15900. def type_check(self, p):
  15901. match p:
  15902. case Module(body):
  15903. env = {}
  15904. for s in body:
  15905. match s:
  15906. case FunctionDef(name, params, bod, dl, returns, comment):
  15907. params_t = [t for (x,t) in params]
  15908. env[name] = FunctionType(params_t, returns)
  15909. self.check_stmts(body, int, env)
  15910. \end{lstlisting}
  15911. \end{tcolorbox}
  15912. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15913. \label{fig:type-check-Llambda-part2}
  15914. \end{figure}
  15915. \fi}
  15916. \clearpage
  15917. \section{Assignment and Lexically Scoped Functions}
  15918. \label{sec:assignment-scoping}
  15919. The combination of lexically scoped functions and assignment to
  15920. variables raises a challenge with the flat-closure approach to
  15921. implementing lexically scoped functions. Consider the following
  15922. example in which function \code{f} has a free variable \code{x} that
  15923. is changed after \code{f} is created but before the call to \code{f}.
  15924. % loop_test_11.rkt
  15925. {\if\edition\racketEd
  15926. \begin{lstlisting}
  15927. (let ([x 0])
  15928. (let ([y 0])
  15929. (let ([z 20])
  15930. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15931. (begin
  15932. (set! x 10)
  15933. (set! y 12)
  15934. (f y))))))
  15935. \end{lstlisting}
  15936. \fi}
  15937. {\if\edition\pythonEd\pythonColor
  15938. % box_free_assign.py
  15939. \begin{lstlisting}
  15940. def g(z : int) -> int:
  15941. x = 0
  15942. y = 0
  15943. f : Callable[[int],int] = lambda a: a + x + z
  15944. x = 10
  15945. y = 12
  15946. return f(y)
  15947. print(g(20))
  15948. \end{lstlisting}
  15949. \fi} The correct output for this example is \code{42} because the call
  15950. to \code{f} is required to use the current value of \code{x} (which is
  15951. \code{10}). Unfortunately, the closure conversion pass
  15952. (section~\ref{sec:closure-conversion}) generates code for the
  15953. \code{lambda} that copies the old value of \code{x} into a
  15954. closure. Thus, if we naively applied closure conversion, the output of
  15955. this program would be \code{32}.
  15956. A first attempt at solving this problem would be to save a pointer to
  15957. \code{x} in the closure and change the occurrences of \code{x} inside
  15958. the lambda to dereference the pointer. Of course, this would require
  15959. assigning \code{x} to the stack and not to a register. However, the
  15960. problem goes a bit deeper.
  15961. Consider the following example that returns a function that refers to
  15962. a local variable of the enclosing function:
  15963. \begin{center}
  15964. \begin{minipage}{\textwidth}
  15965. {\if\edition\racketEd
  15966. \begin{lstlisting}
  15967. (define (f) : ( -> Integer)
  15968. (let ([x 0])
  15969. (let ([g (lambda: () : Integer x)])
  15970. (begin
  15971. (set! x 42)
  15972. g))))
  15973. ((f))
  15974. \end{lstlisting}
  15975. \fi}
  15976. {\if\edition\pythonEd\pythonColor
  15977. % counter.py
  15978. \begin{lstlisting}
  15979. def f():
  15980. x = 0
  15981. g = lambda: x
  15982. x = 42
  15983. return g
  15984. print(f()())
  15985. \end{lstlisting}
  15986. \fi}
  15987. \end{minipage}
  15988. \end{center}
  15989. In this example, the lifetime of \code{x} extends beyond the lifetime
  15990. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15991. stack frame for the call to \code{f}, it would be gone by the time we
  15992. called \code{g}, leaving us with dangling pointers for
  15993. \code{x}. This example demonstrates that when a variable occurs free
  15994. inside a function, its lifetime becomes indefinite. Thus, the value of
  15995. the variable needs to live on the heap. The verb
  15996. \emph{box}\index{subject}{box} is often used for allocating a single
  15997. value on the heap, producing a pointer, and
  15998. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15999. %
  16000. We introduce a new pass named \code{convert\_assignments} to address
  16001. this challenge.
  16002. %
  16003. \python{But before diving into that, we have one more
  16004. problem to discuss.}
  16005. {\if\edition\pythonEd\pythonColor
  16006. \section{Uniquify Variables}
  16007. \label{sec:uniquify-lambda}
  16008. With the addition of \code{lambda} we have a complication to deal
  16009. with: name shadowing. Consider the following program with a function
  16010. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  16011. \code{lambda} expressions. The first \code{lambda} has a parameter
  16012. that is also named \code{x}.
  16013. \begin{lstlisting}
  16014. def f(x:int, y:int) -> Callable[[int], int]:
  16015. g : Callable[[int],int] = (lambda x: x + y)
  16016. h : Callable[[int],int] = (lambda y: x + y)
  16017. x = input_int()
  16018. return g
  16019. print(f(0, 10)(32))
  16020. \end{lstlisting}
  16021. Many of our compiler passes rely on being able to connect variable
  16022. uses with their definitions using just the name of the
  16023. variable. However, in the example above, the name of the variable does
  16024. not uniquely determine its definition. To solve this problem we
  16025. recommend implementing a pass named \code{uniquify} that renames every
  16026. variable in the program to make sure that they are all unique.
  16027. The following shows the result of \code{uniquify} for the example
  16028. above. The \code{x} parameter of function \code{f} is renamed to
  16029. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  16030. renamed to \code{x\_4}.
  16031. \begin{lstlisting}
  16032. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  16033. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  16034. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  16035. x_0 = input_int()
  16036. return g_2
  16037. def main() -> int :
  16038. print(f(0, 10)(32))
  16039. return 0
  16040. \end{lstlisting}
  16041. \fi} % pythonEd
  16042. %% \section{Reveal Functions}
  16043. %% \label{sec:reveal-functions-r5}
  16044. %% \racket{To support the \code{procedure-arity} operator we need to
  16045. %% communicate the arity of a function to the point of closure
  16046. %% creation.}
  16047. %% %
  16048. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16049. %% function at runtime. Thus, we need to communicate the arity of a
  16050. %% function to the point of closure creation.}
  16051. %% %
  16052. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16053. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16054. %% \[
  16055. %% \begin{array}{lcl}
  16056. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16057. %% \end{array}
  16058. %% \]
  16059. \section{Assignment Conversion}
  16060. \label{sec:convert-assignments}
  16061. The purpose of the \code{convert\_assignments} pass is to address the
  16062. challenge regarding the interaction between variable assignments and
  16063. closure conversion. First we identify which variables need to be
  16064. boxed, and then we transform the program to box those variables. In
  16065. general, boxing introduces runtime overhead that we would like to
  16066. avoid, so we should box as few variables as possible. We recommend
  16067. boxing the variables in the intersection of the following two sets of
  16068. variables:
  16069. \begin{enumerate}
  16070. \item The variables that are free in a \code{lambda}.
  16071. \item The variables that appear on the left-hand side of an
  16072. assignment.
  16073. \end{enumerate}
  16074. The first condition is a must but the second condition is
  16075. conservative. It is possible to develop a more liberal condition using
  16076. static program analysis.
  16077. Consider again the first example from
  16078. section~\ref{sec:assignment-scoping}:
  16079. %
  16080. {\if\edition\racketEd
  16081. \begin{lstlisting}
  16082. (let ([x 0])
  16083. (let ([y 0])
  16084. (let ([z 20])
  16085. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16086. (begin
  16087. (set! x 10)
  16088. (set! y 12)
  16089. (f y))))))
  16090. \end{lstlisting}
  16091. \fi}
  16092. {\if\edition\pythonEd\pythonColor
  16093. \begin{lstlisting}
  16094. def g(z : int) -> int:
  16095. x = 0
  16096. y = 0
  16097. f : Callable[[int],int] = lambda a: a + x + z
  16098. x = 10
  16099. y = 12
  16100. return f(y)
  16101. print(g(20))
  16102. \end{lstlisting}
  16103. \fi}
  16104. %
  16105. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16106. side of assignments. The variables \code{x} and \code{z} occur free
  16107. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16108. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16109. three transformations: initialize \code{x} with a tuple whose element
  16110. is uninitialized, replace reads from \code{x} with tuple reads, and
  16111. replace each assignment to \code{x} with a tuple write. The output of
  16112. \code{convert\_assignments} for this example is as follows:
  16113. %
  16114. {\if\edition\racketEd
  16115. \begin{lstlisting}
  16116. (define (main) : Integer
  16117. (let ([x0 (vector 0)])
  16118. (let ([y1 0])
  16119. (let ([z2 20])
  16120. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16121. (+ a3 (+ (vector-ref x0 0) z2)))])
  16122. (begin
  16123. (vector-set! x0 0 10)
  16124. (set! y1 12)
  16125. (f4 y1)))))))
  16126. \end{lstlisting}
  16127. \fi}
  16128. %
  16129. {\if\edition\pythonEd\pythonColor
  16130. \begin{lstlisting}
  16131. def g(z : int)-> int:
  16132. x = (uninitialized(int),)
  16133. x[0] = 0
  16134. y = 0
  16135. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16136. x[0] = 10
  16137. y = 12
  16138. return f(y)
  16139. def main() -> int:
  16140. print(g(20))
  16141. return 0
  16142. \end{lstlisting}
  16143. \fi}
  16144. To compute the free variables of all the \code{lambda} expressions, we
  16145. recommend defining the following two auxiliary functions:
  16146. \begin{enumerate}
  16147. \item \code{free\_variables} computes the free variables of an expression, and
  16148. \item \code{free\_in\_lambda} collects all the variables that are
  16149. free in any of the \code{lambda} expressions, using
  16150. \code{free\_variables} in the case for each \code{lambda}.
  16151. \end{enumerate}
  16152. {\if\edition\racketEd
  16153. %
  16154. To compute the variables that are assigned to, we recommend updating
  16155. the \code{collect-set!} function that we introduced in
  16156. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16157. as \code{Lambda}.
  16158. %
  16159. \fi}
  16160. {\if\edition\pythonEd\pythonColor
  16161. %
  16162. To compute the variables that are assigned to, we recommend defining
  16163. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16164. the set of variables that occur in the left-hand side of an assignment
  16165. statement and otherwise returns the empty set.
  16166. %
  16167. \fi}
  16168. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16169. free in a \code{lambda} and that are assigned to in the enclosing
  16170. function definition.
  16171. Next we discuss the \code{convert\_assignments} pass. In the case for
  16172. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16173. $\VAR{x}$ to a tuple read.
  16174. %
  16175. {\if\edition\racketEd
  16176. \begin{lstlisting}
  16177. (Var |$x$|)
  16178. |$\Rightarrow$|
  16179. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16180. \end{lstlisting}
  16181. \fi}
  16182. %
  16183. {\if\edition\pythonEd\pythonColor
  16184. \begin{lstlisting}
  16185. Name(|$x$|)
  16186. |$\Rightarrow$|
  16187. Subscript(Name(|$x$|), Constant(0), Load())
  16188. \end{lstlisting}
  16189. \fi}
  16190. %
  16191. \noindent In the case for assignment, recursively process the
  16192. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16193. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16194. as follows:
  16195. %
  16196. {\if\edition\racketEd
  16197. \begin{lstlisting}
  16198. (SetBang |$x$| |$\itm{rhs}$|)
  16199. |$\Rightarrow$|
  16200. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16201. \end{lstlisting}
  16202. \fi}
  16203. {\if\edition\pythonEd\pythonColor
  16204. \begin{lstlisting}
  16205. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16206. |$\Rightarrow$|
  16207. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16208. \end{lstlisting}
  16209. \fi}
  16210. %
  16211. {\if\edition\racketEd
  16212. The case for \code{Lambda} is nontrivial, but it is similar to the
  16213. case for function definitions, which we discuss next.
  16214. \fi}
  16215. %
  16216. To translate a function definition, we first compute $\mathit{AF}$,
  16217. the intersection of the variables that are free in a \code{lambda} and
  16218. that are assigned to. We then apply assignment conversion to the body
  16219. of the function definition. Finally, we box the parameters of this
  16220. function definition that are in $\mathit{AF}$. For example,
  16221. the parameter \code{x} of the following function \code{g}
  16222. needs to be boxed:
  16223. {\if\edition\racketEd
  16224. \begin{lstlisting}
  16225. (define (g [x : Integer]) : Integer
  16226. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16227. (begin
  16228. (set! x 10)
  16229. (f 32))))
  16230. \end{lstlisting}
  16231. \fi}
  16232. %
  16233. {\if\edition\pythonEd\pythonColor
  16234. \begin{lstlisting}
  16235. def g(x : int) -> int:
  16236. f : Callable[[int],int] = lambda a: a + x
  16237. x = 10
  16238. return f(32)
  16239. \end{lstlisting}
  16240. \fi}
  16241. %
  16242. \noindent We box parameter \code{x} by creating a local variable named
  16243. \code{x} that is initialized to a tuple whose contents is the value of
  16244. the parameter, which is renamed to \code{x\_0}.
  16245. %
  16246. {\if\edition\racketEd
  16247. \begin{lstlisting}
  16248. (define (g [x_0 : Integer]) : Integer
  16249. (let ([x (vector x_0)])
  16250. (let ([f (lambda: ([a : Integer]) : Integer
  16251. (+ a (vector-ref x 0)))])
  16252. (begin
  16253. (vector-set! x 0 10)
  16254. (f 32)))))
  16255. \end{lstlisting}
  16256. \fi}
  16257. %
  16258. {\if\edition\pythonEd\pythonColor
  16259. \begin{lstlisting}
  16260. def g(x_0 : int)-> int:
  16261. x = (x_0,)
  16262. f : Callable[[int], int] = (lambda a: a + x[0])
  16263. x[0] = 10
  16264. return f(32)
  16265. \end{lstlisting}
  16266. \fi}
  16267. \section{Closure Conversion}
  16268. \label{sec:closure-conversion}
  16269. \index{subject}{closure conversion}
  16270. The compiling of lexically scoped functions into top-level function
  16271. definitions and flat closures is accomplished in the pass
  16272. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16273. and before \code{limit\_functions}.
  16274. As usual, we implement the pass as a recursive function over the
  16275. AST. The interesting cases are for \key{lambda} and function
  16276. application. We transform a \key{lambda} expression into an expression
  16277. that creates a closure, that is, a tuple for which the first element
  16278. is a function pointer and the rest of the elements are the values of
  16279. the free variables of the \key{lambda}.
  16280. %
  16281. However, we use the \code{Closure} AST node instead of using a tuple
  16282. so that we can record the arity.
  16283. %
  16284. In the generated code that follows, \itm{fvs} is the list of free
  16285. variables of the lambda and \itm{name} is a unique symbol generated to
  16286. identify the lambda.
  16287. %
  16288. \racket{The \itm{arity} is the number of parameters (the length of
  16289. \itm{ps}).}
  16290. %
  16291. {\if\edition\racketEd
  16292. \begin{lstlisting}
  16293. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16294. |$\Rightarrow$|
  16295. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16296. \end{lstlisting}
  16297. \fi}
  16298. %
  16299. {\if\edition\pythonEd\pythonColor
  16300. \begin{lstlisting}
  16301. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16302. |$\Rightarrow$|
  16303. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16304. \end{lstlisting}
  16305. \fi}
  16306. %
  16307. In addition to transforming each \key{Lambda} AST node into a
  16308. tuple, we create a top-level function definition for each
  16309. \key{Lambda}, as shown next.\\
  16310. \begin{minipage}{0.8\textwidth}
  16311. {\if\edition\racketEd
  16312. \begin{lstlisting}
  16313. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16314. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16315. ...
  16316. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16317. |\itm{body'}|)...))
  16318. \end{lstlisting}
  16319. \fi}
  16320. {\if\edition\pythonEd\pythonColor
  16321. \begin{lstlisting}
  16322. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16323. |$\itm{fvs}_1$| = clos[1]
  16324. |$\ldots$|
  16325. |$\itm{fvs}_m$| = clos[|$m$|]
  16326. |\itm{body'}|
  16327. \end{lstlisting}
  16328. \fi}
  16329. \end{minipage}\\
  16330. %
  16331. The \code{clos} parameter refers to the closure. The type
  16332. \itm{closTy} is a tuple type for which the first element type is
  16333. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16334. rest of the element types are the types of the free variables in the
  16335. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16336. is nontrivial to give a type to the function in the closure's
  16337. type.\footnote{To give an accurate type to a closure, we would need to
  16338. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16339. %
  16340. \racket{Translate the type
  16341. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16342. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16343. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16344. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16345. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16346. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16347. %% The dummy type is considered to be equal to any other type during type
  16348. %% checking.
  16349. The free variables become local variables that are initialized with
  16350. their values in the closure.
  16351. Closure conversion turns every function into a tuple, so the type
  16352. annotations in the program must also be translated. We recommend
  16353. defining an auxiliary recursive function for this purpose. Function
  16354. types should be translated as follows:
  16355. %
  16356. {\if\edition\racketEd
  16357. \begin{lstlisting}
  16358. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16359. |$\Rightarrow$|
  16360. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16361. \end{lstlisting}
  16362. \fi}
  16363. {\if\edition\pythonEd\pythonColor
  16364. \begin{lstlisting}
  16365. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16366. |$\Rightarrow$|
  16367. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16368. \end{lstlisting}
  16369. \fi}
  16370. %
  16371. This type indicates that the first thing in the tuple is a
  16372. function. The first parameter of the function is a tuple (a closure)
  16373. and the rest of the parameters are the ones from the original
  16374. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16375. omits the types of the free variables because (1) those types are not
  16376. available in this context, and (2) we do not need them in the code that
  16377. is generated for function application. So this type describes only the
  16378. first component of the closure tuple. At runtime the tuple may have
  16379. more components, but we ignore them at this point.
  16380. We transform function application into code that retrieves the
  16381. function from the closure and then calls the function, passing the
  16382. closure as the first argument. We place $e'$ in a temporary variable
  16383. to avoid code duplication.
  16384. \begin{center}
  16385. \begin{minipage}{\textwidth}
  16386. {\if\edition\racketEd
  16387. \begin{lstlisting}
  16388. (Apply |$e$| |$\itm{es}$|)
  16389. |$\Rightarrow$|
  16390. (Let |$\itm{tmp}$| |$e'$|
  16391. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16392. \end{lstlisting}
  16393. \fi}
  16394. %
  16395. {\if\edition\pythonEd\pythonColor
  16396. \begin{lstlisting}
  16397. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16398. |$\Rightarrow$|
  16399. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16400. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16401. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16402. \end{lstlisting}
  16403. \fi}
  16404. \end{minipage}
  16405. \end{center}
  16406. There is also the question of what to do with references to top-level
  16407. function definitions. To maintain a uniform translation of function
  16408. application, we turn function references into closures.
  16409. \begin{tabular}{lll}
  16410. \begin{minipage}{0.2\textwidth}
  16411. {\if\edition\racketEd
  16412. \begin{lstlisting}
  16413. (FunRef |$f$| |$n$|)
  16414. \end{lstlisting}
  16415. \fi}
  16416. {\if\edition\pythonEd\pythonColor
  16417. \begin{lstlisting}
  16418. FunRef(|$f$|, |$n$|)
  16419. \end{lstlisting}
  16420. \fi}
  16421. \end{minipage}
  16422. &
  16423. $\Rightarrow\qquad$
  16424. &
  16425. \begin{minipage}{0.5\textwidth}
  16426. {\if\edition\racketEd
  16427. \begin{lstlisting}
  16428. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16429. \end{lstlisting}
  16430. \fi}
  16431. {\if\edition\pythonEd\pythonColor
  16432. \begin{lstlisting}
  16433. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16434. \end{lstlisting}
  16435. \fi}
  16436. \end{minipage}
  16437. \end{tabular} \\
  16438. We no longer need the annotated assignment statement \code{AnnAssign}
  16439. to support the type checking of \code{lambda} expressions, so we
  16440. translate it to a regular \code{Assign} statement.
  16441. The top-level function definitions need to be updated to take an extra
  16442. closure parameter, but that parameter is ignored in the body of those
  16443. functions.
  16444. \subsection{An Example Translation}
  16445. \label{sec:example-lambda}
  16446. Figure~\ref{fig:lexical-functions-example} shows the result of
  16447. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16448. program demonstrating lexical scoping that we discussed at the
  16449. beginning of this chapter.
  16450. \begin{figure}[tbp]
  16451. \begin{tcolorbox}[colback=white]
  16452. \begin{minipage}{0.8\textwidth}
  16453. {\if\edition\racketEd
  16454. % tests/lambda_test_6.rkt
  16455. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16456. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16457. (let ([y8 4])
  16458. (lambda: ([z9 : Integer]) : Integer
  16459. (+ x7 (+ y8 z9)))))
  16460. (define (main) : Integer
  16461. (let ([g0 ((fun-ref f6 1) 5)])
  16462. (let ([h1 ((fun-ref f6 1) 3)])
  16463. (+ (g0 11) (h1 15)))))
  16464. \end{lstlisting}
  16465. $\Rightarrow$
  16466. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16467. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16468. (let ([y8 4])
  16469. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16470. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16471. (let ([x7 (vector-ref fvs3 1)])
  16472. (let ([y8 (vector-ref fvs3 2)])
  16473. (+ x7 (+ y8 z9)))))
  16474. (define (main) : Integer
  16475. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16476. ((vector-ref clos5 0) clos5 5))])
  16477. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16478. ((vector-ref clos6 0) clos6 3))])
  16479. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16480. \end{lstlisting}
  16481. \fi}
  16482. %
  16483. {\if\edition\pythonEd\pythonColor
  16484. % free_var.py
  16485. \begin{lstlisting}
  16486. def f(x: int) -> Callable[[int],int]:
  16487. y = 4
  16488. return lambda z: x + y + z
  16489. g = f(5)
  16490. h = f(3)
  16491. print(g(11) + h(15))
  16492. \end{lstlisting}
  16493. $\Rightarrow$
  16494. \begin{lstlisting}
  16495. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16496. x = fvs_1[1]
  16497. y = fvs_1[2]
  16498. return (x + y[0] + z)
  16499. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16500. y = (uninitialized(int),)
  16501. y[0] = 4
  16502. return closure{1}({lambda_0}, x, y)
  16503. def main() -> int:
  16504. g = (begin: clos_3 = closure{1}({f})
  16505. clos_3[0](clos_3, 5))
  16506. h = (begin: clos_4 = closure{1}({f})
  16507. clos_4[0](clos_4, 3))
  16508. print((begin: clos_5 = g
  16509. clos_5[0](clos_5, 11))
  16510. + (begin: clos_6 = h
  16511. clos_6[0](clos_6, 15)))
  16512. return 0
  16513. \end{lstlisting}
  16514. \fi}
  16515. \end{minipage}
  16516. \end{tcolorbox}
  16517. \caption{Example of closure conversion.}
  16518. \label{fig:lexical-functions-example}
  16519. \end{figure}
  16520. \begin{exercise}\normalfont\normalsize
  16521. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16522. Create five new programs that use \key{lambda} functions and make use of
  16523. lexical scoping. Test your compiler on these new programs and all
  16524. your previously created test programs.
  16525. \end{exercise}
  16526. \section{Expose Allocation}
  16527. \label{sec:expose-allocation-r5}
  16528. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code that
  16529. allocates and initializes a tuple, similar to the translation of the
  16530. tuple creation in section~\ref{sec:expose-allocation}. The main
  16531. difference is replacing the use of \ALLOC{\itm{len}}{\itm{type}} with
  16532. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}. The result type of
  16533. the translation of $\CLOSURE{\itm{arity}}{\Exp^{*}}$ should be a tuple
  16534. type, but only a single element tuple type. The types of the tuple
  16535. elements that correspond to the free variables of the closure should
  16536. not appear in the tuple type. The new AST class \code{UncheckedCast}
  16537. can be used to adjust the result type.
  16538. \section{Explicate Control and \LangCLam{}}
  16539. \label{sec:explicate-r5}
  16540. The output language of \code{explicate\_control} is \LangCLam{}; the
  16541. definition of its abstract syntax is shown in
  16542. figure~\ref{fig:Clam-syntax}.
  16543. %
  16544. \racket{The only differences with respect to \LangCFun{} are the
  16545. addition of the \code{AllocateClosure} form to the grammar for
  16546. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16547. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16548. similar to the handling of other expressions such as primitive
  16549. operators.}
  16550. %
  16551. \python{The differences with respect to \LangCFun{} are the
  16552. additions of \code{Uninitialized}, \code{AllocateClosure},
  16553. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16554. \code{explicate\_control} pass is similar to the handling of other
  16555. expressions such as primitive operators.}
  16556. \newcommand{\ClambdaASTRacket}{
  16557. \begin{array}{lcl}
  16558. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16559. \itm{op} &::= & \code{procedure-arity}
  16560. \end{array}
  16561. }
  16562. \newcommand{\ClambdaASTPython}{
  16563. \begin{array}{lcl}
  16564. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16565. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16566. &\MID& \ARITY{\Atm}
  16567. \MID \key{UncheckedCast}\LP\Exp,\Type\RP
  16568. \end{array}
  16569. }
  16570. \begin{figure}[tp]
  16571. \begin{tcolorbox}[colback=white]
  16572. \small
  16573. {\if\edition\racketEd
  16574. \[
  16575. \begin{array}{l}
  16576. \gray{\CvarASTRacket} \\ \hline
  16577. \gray{\CifASTRacket} \\ \hline
  16578. \gray{\CloopASTRacket} \\ \hline
  16579. \gray{\CtupASTRacket} \\ \hline
  16580. \gray{\CfunASTRacket} \\ \hline
  16581. \ClambdaASTRacket \\
  16582. \begin{array}{lcl}
  16583. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16584. \end{array}
  16585. \end{array}
  16586. \]
  16587. \fi}
  16588. {\if\edition\pythonEd\pythonColor
  16589. \[
  16590. \begin{array}{l}
  16591. \gray{\CifASTPython} \\ \hline
  16592. \gray{\CtupASTPython} \\ \hline
  16593. \gray{\CfunASTPython} \\ \hline
  16594. \ClambdaASTPython \\
  16595. \begin{array}{lcl}
  16596. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16597. \end{array}
  16598. \end{array}
  16599. \]
  16600. \fi}
  16601. \end{tcolorbox}
  16602. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16603. \label{fig:Clam-syntax}
  16604. \index{subject}{Clambda@\LangCLam{} abstract syntax}
  16605. \end{figure}
  16606. \section{Select Instructions}
  16607. \label{sec:select-instructions-Llambda}
  16608. \index{subject}{select instructions}
  16609. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16610. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16611. (section~\ref{sec:select-instructions-gc}). The only difference is
  16612. that you should place the \itm{arity} in the tag that is stored at
  16613. position $0$ of the tuple. Recall that in
  16614. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16615. was not used. We store the arity in the $5$ bits starting at position
  16616. $58$.
  16617. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16618. instructions that access the tag from position $0$ of the vector and
  16619. extract the $5$ bits starting at position $58$ from the tag.}
  16620. %
  16621. \python{Compile a call to the \code{arity} operator to a sequence of
  16622. instructions that access the tag from position $0$ of the tuple
  16623. (representing a closure) and extract the $5$ bits starting at position
  16624. $58$ from the tag.}
  16625. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16626. needed for the compilation of \LangLam{}.
  16627. \begin{figure}[bthp]
  16628. \begin{tcolorbox}[colback=white]
  16629. {\if\edition\racketEd
  16630. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16631. \node (Lfun) at (0,2) {\large \LangLam{}};
  16632. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16633. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16634. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16635. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16636. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16637. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16638. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16639. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16640. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16641. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16642. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16643. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16644. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16645. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16646. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16647. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16648. \path[->,bend left=15] (Lfun) edge [above] node
  16649. {\ttfamily\footnotesize shrink} (Lfun-2);
  16650. \path[->,bend left=15] (Lfun-2) edge [above] node
  16651. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16652. \path[->,bend left=15] (Lfun-3) edge [above] node
  16653. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16654. \path[->,bend left=15] (F1-0) edge [left] node
  16655. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16656. \path[->,bend left=15] (F1-1) edge [below] node
  16657. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16658. \path[->,bend right=15] (F1-2) edge [above] node
  16659. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16660. \path[->,bend right=15] (F1-3) edge [above] node
  16661. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16662. \path[->,bend left=15] (F1-4) edge [right] node
  16663. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16664. \path[->,bend right=15] (F1-5) edge [below] node
  16665. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16666. \path[->,bend left=15] (F1-6) edge [above] node
  16667. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16668. \path[->] (C3-2) edge [right] node
  16669. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16670. \path[->,bend right=15] (x86-2) edge [right] node
  16671. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16672. \path[->,bend right=15] (x86-2-1) edge [below] node
  16673. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16674. \path[->,bend right=15] (x86-2-2) edge [right] node
  16675. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16676. \path[->,bend left=15] (x86-3) edge [above] node
  16677. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16678. \path[->,bend left=15] (x86-4) edge [right] node
  16679. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16680. \end{tikzpicture}
  16681. \fi}
  16682. {\if\edition\pythonEd\pythonColor
  16683. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16684. \node (Lfun) at (0,2) {\large \LangLam{}};
  16685. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16686. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16687. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16688. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16689. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16690. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16691. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16692. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16693. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16694. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16695. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16696. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16697. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16698. \path[->,bend left=15] (Lfun) edge [above] node
  16699. {\ttfamily\footnotesize shrink} (Lfun-2);
  16700. \path[->,bend left=15] (Lfun-2) edge [above] node
  16701. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16702. \path[->,bend left=15] (Lfun-3) edge [above] node
  16703. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16704. \path[->,bend left=15] (F1-0) edge [left] node
  16705. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16706. \path[->,bend left=15] (F1-1) edge [below] node
  16707. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16708. \path[->,bend left=15] (F1-2) edge [below] node
  16709. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16710. \path[->,bend right=15] (F1-3) edge [above] node
  16711. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16712. \path[->,bend right=15] (F1-5) edge [right] node
  16713. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16714. \path[->,bend left=15] (F1-6) edge [right] node
  16715. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16716. \path[->,bend right=15] (C3-2) edge [right] node
  16717. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16718. \path[->,bend right=15] (x86-2) edge [below] node
  16719. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16720. \path[->,bend right=15] (x86-3) edge [below] node
  16721. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16722. \path[->,bend left=15] (x86-4) edge [above] node
  16723. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16724. \end{tikzpicture}
  16725. \fi}
  16726. \end{tcolorbox}
  16727. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16728. functions.}
  16729. \label{fig:Llambda-passes}
  16730. \end{figure}
  16731. \clearpage
  16732. \section{Challenge: Optimize Closures}
  16733. \label{sec:optimize-closures}
  16734. In this chapter we compile lexically scoped functions into a
  16735. relatively efficient representation: flat closures. However, even this
  16736. representation comes with some overhead. For example, consider the
  16737. following program with a function \code{tail\_sum} that does not have
  16738. any free variables and where all the uses of \code{tail\_sum} are in
  16739. applications in which we know that only \code{tail\_sum} is being applied
  16740. (and not any other functions):
  16741. \begin{center}
  16742. \begin{minipage}{0.95\textwidth}
  16743. {\if\edition\racketEd
  16744. \begin{lstlisting}
  16745. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16746. (if (eq? n 0)
  16747. s
  16748. (tail_sum (- n 1) (+ n s))))
  16749. (+ (tail_sum 3 0) 36)
  16750. \end{lstlisting}
  16751. \fi}
  16752. {\if\edition\pythonEd\pythonColor
  16753. \begin{lstlisting}
  16754. def tail_sum(n : int, s : int) -> int:
  16755. if n == 0:
  16756. return s
  16757. else:
  16758. return tail_sum(n - 1, n + s)
  16759. print(tail_sum(3, 0) + 36)
  16760. \end{lstlisting}
  16761. \fi}
  16762. \end{minipage}
  16763. \end{center}
  16764. As described in this chapter, we uniformly apply closure conversion to
  16765. all functions, obtaining the following output for this program:
  16766. \begin{center}
  16767. \begin{minipage}{0.95\textwidth}
  16768. {\if\edition\racketEd
  16769. \begin{lstlisting}
  16770. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16771. (if (eq? n2 0)
  16772. s3
  16773. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16774. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16775. (define (main) : Integer
  16776. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16777. ((vector-ref clos6 0) clos6 3 0)) 27))
  16778. \end{lstlisting}
  16779. \fi}
  16780. {\if\edition\pythonEd\pythonColor
  16781. \begin{lstlisting}
  16782. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16783. if n_0 == 0:
  16784. return s_1
  16785. else:
  16786. return (begin: clos_2 = (tail_sum,)
  16787. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16788. def main() -> int :
  16789. print((begin: clos_4 = (tail_sum,)
  16790. clos_4[0](clos_4, 3, 0)) + 36)
  16791. return 0
  16792. \end{lstlisting}
  16793. \fi}
  16794. \end{minipage}
  16795. \end{center}
  16796. If this program were compiled according to the previous chapter, there
  16797. would be no allocation and the calls to \code{tail\_sum} would be
  16798. direct calls. In contrast, the program presented here allocates memory
  16799. for each closure and the calls to \code{tail\_sum} are indirect. These
  16800. two differences incur considerable overhead in a program such as this,
  16801. in which the allocations and indirect calls occur inside a tight loop.
  16802. One might think that this problem is trivial to solve: can't we just
  16803. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16804. and compile them to direct calls instead of treating it like a call to
  16805. a closure? We would also drop the new \code{fvs} parameter of
  16806. \code{tail\_sum}.
  16807. %
  16808. However, this problem is not so trivial, because a global function may
  16809. \emph{escape} and become involved in applications that also involve
  16810. closures. Consider the following example in which the application
  16811. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16812. application because the \code{lambda} may flow into \code{f}, but the
  16813. \code{inc} function might also flow into \code{f}:
  16814. \begin{center}
  16815. \begin{minipage}{\textwidth}
  16816. % lambda_test_30.rkt
  16817. {\if\edition\racketEd
  16818. \begin{lstlisting}
  16819. (define (inc [x : Integer]) : Integer
  16820. (+ x 1))
  16821. (let ([y (read)])
  16822. (let ([f (if (eq? (read) 0)
  16823. inc
  16824. (lambda: ([x : Integer]) : Integer (- x y)))])
  16825. (f 41)))
  16826. \end{lstlisting}
  16827. \fi}
  16828. {\if\edition\pythonEd\pythonColor
  16829. \begin{lstlisting}
  16830. def add1(x : int) -> int:
  16831. return x + 1
  16832. y = input_int()
  16833. g : Callable[[int], int] = lambda x: x - y
  16834. f = add1 if input_int() == 0 else g
  16835. print(f(41))
  16836. \end{lstlisting}
  16837. \fi}
  16838. \end{minipage}
  16839. \end{center}
  16840. If a global function name is used in any way other than as the
  16841. operator in a direct call, then we say that the function
  16842. \emph{escapes}. If a global function does not escape, then we do not
  16843. need to perform closure conversion on the function.
  16844. \begin{exercise}\normalfont\normalsize
  16845. Implement an auxiliary function for detecting which global
  16846. functions escape. Using that function, implement an improved version
  16847. of closure conversion that does not apply closure conversion to
  16848. global functions that do not escape but instead compiles them as
  16849. regular functions. Create several new test cases that check whether
  16850. your compiler properly detects whether global functions escape or not.
  16851. \end{exercise}
  16852. So far we have reduced the overhead of calling global functions, but
  16853. it would also be nice to reduce the overhead of calling a
  16854. \code{lambda} when we can determine at compile time which
  16855. \code{lambda} will be called. We refer to such calls as \emph{known
  16856. calls}. Consider the following example in which a \code{lambda} is
  16857. bound to \code{f} and then applied.
  16858. {\if\edition\racketEd
  16859. % lambda_test_9.rkt
  16860. \begin{lstlisting}
  16861. (let ([y (read)])
  16862. (let ([f (lambda: ([x : Integer]) : Integer
  16863. (+ x y))])
  16864. (f 21)))
  16865. \end{lstlisting}
  16866. \fi}
  16867. {\if\edition\pythonEd\pythonColor
  16868. \begin{lstlisting}
  16869. y = input_int()
  16870. f : Callable[[int],int] = lambda x: x + y
  16871. print(f(21))
  16872. \end{lstlisting}
  16873. \fi}
  16874. %
  16875. \noindent Closure conversion compiles the application
  16876. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16877. %
  16878. {\if\edition\racketEd
  16879. \begin{lstlisting}
  16880. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16881. (let ([y2 (vector-ref fvs6 1)])
  16882. (+ x3 y2)))
  16883. (define (main) : Integer
  16884. (let ([y2 (read)])
  16885. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16886. ((vector-ref f4 0) f4 21))))
  16887. \end{lstlisting}
  16888. \fi}
  16889. {\if\edition\pythonEd\pythonColor
  16890. \begin{lstlisting}
  16891. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16892. y_1 = fvs_4[1]
  16893. return x_2 + y_1[0]
  16894. def main() -> int:
  16895. y_1 = (777,)
  16896. y_1[0] = input_int()
  16897. f_0 = (lambda_3, y_1)
  16898. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16899. return 0
  16900. \end{lstlisting}
  16901. \fi}
  16902. %
  16903. \noindent However, we can instead compile the application
  16904. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16905. %
  16906. {\if\edition\racketEd
  16907. \begin{lstlisting}
  16908. (define (main) : Integer
  16909. (let ([y2 (read)])
  16910. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16911. ((fun-ref lambda5 1) f4 21))))
  16912. \end{lstlisting}
  16913. \fi}
  16914. {\if\edition\pythonEd\pythonColor
  16915. \begin{lstlisting}
  16916. def main() -> int:
  16917. y_1 = (777,)
  16918. y_1[0] = input_int()
  16919. f_0 = (lambda_3, y_1)
  16920. print(lambda_3(f_0, 21))
  16921. return 0
  16922. \end{lstlisting}
  16923. \fi}
  16924. The problem of determining which \code{lambda} will be called from a
  16925. particular application is quite challenging in general and the topic
  16926. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16927. following exercise we recommend that you compile an application to a
  16928. direct call when the operator is a variable and \racket{the variable
  16929. is \code{let}-bound to a closure}\python{the previous assignment to
  16930. the variable is a closure}. This can be accomplished by maintaining
  16931. an environment that maps variables to function names. Extend the
  16932. environment whenever you encounter a closure on the right-hand side of
  16933. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16934. name of the global function for the closure. This pass should come
  16935. after closure conversion.
  16936. \begin{exercise}\normalfont\normalsize
  16937. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16938. compiles known calls into direct calls. Verify that your compiler is
  16939. successful in this regard on several example programs.
  16940. \end{exercise}
  16941. These exercises only scratch the surface of closure optimization. A
  16942. good next step for the interested reader is to look at the work of
  16943. \citet{Keep:2012ab}.
  16944. \section{Further Reading}
  16945. The notion of lexically scoped functions predates modern computers by
  16946. about a decade. They were invented by \citet{Church:1932aa}, who
  16947. proposed the lambda calculus as a foundation for logic. Anonymous
  16948. functions were included in the LISP~\citep{McCarthy:1960dz}
  16949. programming language but were initially dynamically scoped. The Scheme
  16950. dialect of LISP adopted lexical scoping, and
  16951. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16952. Scheme programs. However, environments were represented as linked
  16953. lists, so variable look-up was linear in the size of the
  16954. environment. \citet{Appel91} gives a detailed description of several
  16955. closure representations. In this chapter we represent environments
  16956. using flat closures, which were invented by
  16957. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16958. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16959. closures, variable look-up is constant time but the time to create a
  16960. closure is proportional to the number of its free variables. Flat
  16961. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16962. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16963. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16964. % compilers)
  16965. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16966. \chapter{Dynamic Typing}
  16967. \label{ch:Ldyn}
  16968. \index{subject}{dynamic typing}
  16969. \setcounter{footnote}{0}
  16970. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16971. typed language that is a subset of \racket{Racket}\python{Python}. The
  16972. focus on dynamic typing is in contrast to the previous chapters, which
  16973. have studied the compilation of statically typed languages. In
  16974. dynamically typed languages such as \LangDyn{}, a particular
  16975. expression may produce a value of a different type each time it is
  16976. executed. Consider the following example with a conditional \code{if}
  16977. expression that may return a Boolean or an integer depending on the
  16978. input to the program:
  16979. % part of dynamic_test_25.rkt
  16980. {\if\edition\racketEd
  16981. \begin{lstlisting}
  16982. (not (if (eq? (read) 1) #f 0))
  16983. \end{lstlisting}
  16984. \fi}
  16985. {\if\edition\pythonEd\pythonColor
  16986. \begin{lstlisting}
  16987. not (False if input_int() == 1 else 0)
  16988. \end{lstlisting}
  16989. \fi}
  16990. Languages that allow expressions to produce different kinds of values
  16991. are called \emph{polymorphic}, a word composed of the Greek roots
  16992. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16993. There are several kinds of polymorphism in programming languages, such as
  16994. subtype polymorphism\index{subject}{subtype polymorphism} and
  16995. parametric polymorphism\index{subject}{parametric polymorphism}
  16996. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16997. study in this chapter does not have a special name; it is the kind
  16998. that arises in dynamically typed languages.
  16999. Another characteristic of dynamically typed languages is that
  17000. their primitive operations, such as \code{not}, are often defined to operate
  17001. on many different types of values. In fact, in
  17002. \racket{Racket}\python{Python}, the \code{not} operator produces a
  17003. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  17004. given anything else it returns \FALSE{}.
  17005. Furthermore, even when primitive operations restrict their inputs to
  17006. values of a certain type, this restriction is enforced at runtime
  17007. instead of during compilation. For example, the tuple read
  17008. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  17009. results in a runtime error because the first argument must
  17010. be a tuple, not a Boolean.
  17011. \section{The \LangDyn{} Language}
  17012. \newcommand{\LdynGrammarRacket}{
  17013. \begin{array}{rcl}
  17014. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  17015. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  17016. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  17017. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  17018. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  17019. \end{array}
  17020. }
  17021. \newcommand{\LdynASTRacket}{
  17022. \begin{array}{lcl}
  17023. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17024. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  17025. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  17026. \end{array}
  17027. }
  17028. \begin{figure}[tp]
  17029. \centering
  17030. \begin{tcolorbox}[colback=white]
  17031. \small
  17032. {\if\edition\racketEd
  17033. \[
  17034. \begin{array}{l}
  17035. \gray{\LintGrammarRacket{}} \\ \hline
  17036. \gray{\LvarGrammarRacket{}} \\ \hline
  17037. \gray{\LifGrammarRacket{}} \\ \hline
  17038. \gray{\LwhileGrammarRacket} \\ \hline
  17039. \gray{\LtupGrammarRacket} \\ \hline
  17040. \LdynGrammarRacket \\
  17041. \begin{array}{rcl}
  17042. \LangDynM{} &::=& \Def\ldots\; \Exp
  17043. \end{array}
  17044. \end{array}
  17045. \]
  17046. \fi}
  17047. {\if\edition\pythonEd\pythonColor
  17048. \[
  17049. \begin{array}{rcl}
  17050. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17051. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17052. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17053. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17054. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17055. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17056. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17057. \MID \CLEN{\Exp} \\
  17058. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17059. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17060. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17061. \MID \Var\mathop{\key{=}}\Exp \\
  17062. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17063. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17064. &\MID& \CRETURN{\Exp} \\
  17065. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17066. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17067. \end{array}
  17068. \]
  17069. \fi}
  17070. \end{tcolorbox}
  17071. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17072. \label{fig:r7-concrete-syntax}
  17073. \index{subject}{Ldyn@\LangDyn{} concrete syntax}
  17074. \end{figure}
  17075. \begin{figure}[tp]
  17076. \centering
  17077. \begin{tcolorbox}[colback=white]
  17078. \small
  17079. {\if\edition\racketEd
  17080. \[
  17081. \begin{array}{l}
  17082. \gray{\LintASTRacket{}} \\ \hline
  17083. \gray{\LvarASTRacket{}} \\ \hline
  17084. \gray{\LifASTRacket{}} \\ \hline
  17085. \gray{\LwhileASTRacket} \\ \hline
  17086. \gray{\LtupASTRacket} \\ \hline
  17087. \LdynASTRacket \\
  17088. \begin{array}{lcl}
  17089. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17090. \end{array}
  17091. \end{array}
  17092. \]
  17093. \fi}
  17094. {\if\edition\pythonEd\pythonColor
  17095. \[
  17096. \begin{array}{rcl}
  17097. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17098. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17099. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17100. \MID \code{Is()} \\
  17101. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17102. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17103. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17104. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17105. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17106. &\MID& \VAR{\Var{}}
  17107. \MID \BOOL{\itm{bool}}
  17108. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17109. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17110. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17111. &\MID& \LEN{\Exp} \\
  17112. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17113. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17114. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17115. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17116. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17117. &\MID& \RETURN{\Exp} \\
  17118. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17119. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17120. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17121. \end{array}
  17122. \]
  17123. \fi}
  17124. \end{tcolorbox}
  17125. \caption{The abstract syntax of \LangDyn{}.}
  17126. \label{fig:r7-syntax}
  17127. \index{subject}{Ldyn@\LangDyn{} abstract syntax}
  17128. \end{figure}
  17129. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17130. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17131. %
  17132. There is no type checker for \LangDyn{} because it checks types only
  17133. at runtime.
  17134. The definitional interpreter for \LangDyn{} is presented in
  17135. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17136. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17137. \INT{n}. Instead of simply returning the integer \code{n} (as
  17138. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17139. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17140. value} that combines an underlying value with a tag that identifies
  17141. what kind of value it is. We define the following \racket{struct}\python{class}
  17142. to represent tagged values:
  17143. %
  17144. {\if\edition\racketEd
  17145. \begin{lstlisting}
  17146. (struct Tagged (value tag) #:transparent)
  17147. \end{lstlisting}
  17148. \fi}
  17149. {\if\edition\pythonEd\pythonColor
  17150. \begin{minipage}{\textwidth}
  17151. \begin{lstlisting}
  17152. @dataclass(eq=True)
  17153. class Tagged(Value):
  17154. value : Value
  17155. tag : str
  17156. def __str__(self):
  17157. return str(self.value)
  17158. \end{lstlisting}
  17159. \end{minipage}
  17160. \fi}
  17161. %
  17162. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17163. \code{Vector}, and \code{Procedure}.}
  17164. %
  17165. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17166. \skey{tuple}, and \skey{function}.}
  17167. %
  17168. Tags are closely related to types but do not always capture all the
  17169. information that a type does.
  17170. %
  17171. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17172. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17173. Any)} is tagged with \code{Procedure}.}
  17174. %
  17175. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17176. is tagged with \skey{tuple} and a function of type
  17177. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17178. is tagged with \skey{function}.}
  17179. Next consider the match case for accessing the element of a tuple.
  17180. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17181. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17182. argument is a tuple and the second is an integer.
  17183. \racket{
  17184. If they are not, a \code{trapped-error} is raised. Recall from
  17185. section~\ref{sec:interp_Lint} that when a definition interpreter
  17186. raises a \code{trapped-error} error, the compiled code must also
  17187. signal an error by exiting with return code \code{255}. A
  17188. \code{trapped-error} is also raised if the index is not less than the
  17189. length of the vector.
  17190. }
  17191. %
  17192. \python{If they are not, an exception is raised. The compiled code
  17193. must also signal an error by exiting with return code \code{255}. A
  17194. exception is also raised if the index is not less than the length of the
  17195. tuple or if it is negative.}
  17196. \begin{figure}[tbp]
  17197. \begin{tcolorbox}[colback=white]
  17198. {\if\edition\racketEd
  17199. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17200. (define ((interp-Ldyn-exp env) ast)
  17201. (define recur (interp-Ldyn-exp env))
  17202. (match ast
  17203. [(Var x) (dict-ref env x)]
  17204. [(Int n) (Tagged n 'Integer)]
  17205. [(Bool b) (Tagged b 'Boolean)]
  17206. [(Lambda xs rt body)
  17207. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17208. [(Prim 'vector es)
  17209. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17210. [(Prim 'vector-ref (list e1 e2))
  17211. (define vec (recur e1)) (define i (recur e2))
  17212. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17213. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17214. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17215. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17216. [(Prim 'vector-set! (list e1 e2 e3))
  17217. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17218. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17219. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17220. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17221. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17222. (Tagged (void) 'Void)]
  17223. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17224. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17225. [(Prim 'or (list e1 e2))
  17226. (define v1 (recur e1))
  17227. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17228. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17229. [(Prim op (list e1))
  17230. #:when (set-member? type-predicates op)
  17231. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17232. [(Prim op es)
  17233. (define args (map recur es))
  17234. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17235. (unless (for/or ([expected-tags (op-tags op)])
  17236. (equal? expected-tags tags))
  17237. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17238. (tag-value
  17239. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17240. [(If q t f)
  17241. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17242. [(Apply f es)
  17243. (define new-f (recur f)) (define args (map recur es))
  17244. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17245. (match f-val
  17246. [`(function ,xs ,body ,lam-env)
  17247. (unless (eq? (length xs) (length args))
  17248. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17249. (define new-env (append (map cons xs args) lam-env))
  17250. ((interp-Ldyn-exp new-env) body)]
  17251. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17252. \end{lstlisting}
  17253. \fi}
  17254. {\if\edition\pythonEd\pythonColor
  17255. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17256. class InterpLdyn(InterpLlambda):
  17257. def interp_exp(self, e, env):
  17258. match e:
  17259. case Constant(n):
  17260. return self.tag(super().interp_exp(e, env))
  17261. case Tuple(es, Load()):
  17262. return self.tag(super().interp_exp(e, env))
  17263. case Lambda(params, body):
  17264. return self.tag(super().interp_exp(e, env))
  17265. case Call(Name('input_int'), []):
  17266. return self.tag(super().interp_exp(e, env))
  17267. case BinOp(left, Add(), right):
  17268. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17269. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17270. case BinOp(left, Sub(), right):
  17271. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17272. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17273. case UnaryOp(USub(), e1):
  17274. v = self.interp_exp(e1, env)
  17275. return self.tag(- self.untag(v, 'int', e))
  17276. case IfExp(test, body, orelse):
  17277. v = self.interp_exp(test, env)
  17278. if self.untag(v, 'bool', e):
  17279. return self.interp_exp(body, env)
  17280. else:
  17281. return self.interp_exp(orelse, env)
  17282. case UnaryOp(Not(), e1):
  17283. v = self.interp_exp(e1, env)
  17284. return self.tag(not self.untag(v, 'bool', e))
  17285. case BoolOp(And(), values):
  17286. left = values[0]; right = values[1]
  17287. l = self.interp_exp(left, env)
  17288. if self.untag(l, 'bool', e):
  17289. return self.interp_exp(right, env)
  17290. else:
  17291. return self.tag(False)
  17292. case BoolOp(Or(), values):
  17293. left = values[0]; right = values[1]
  17294. l = self.interp_exp(left, env)
  17295. if self.untag(l, 'bool', e):
  17296. return self.tag(True)
  17297. else:
  17298. return self.interp_exp(right, env)
  17299. \end{lstlisting}
  17300. \fi}
  17301. \end{tcolorbox}
  17302. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17303. \label{fig:interp-Ldyn}
  17304. \end{figure}
  17305. {\if\edition\pythonEd\pythonColor
  17306. \begin{figure}[tbp]
  17307. \begin{tcolorbox}[colback=white]
  17308. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17309. # interp_exp continued
  17310. case Compare(left, [cmp], [right]):
  17311. l = self.interp_exp(left, env)
  17312. r = self.interp_exp(right, env)
  17313. if l.tag == r.tag:
  17314. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17315. else:
  17316. raise Exception('interp Compare unexpected '
  17317. + repr(l) + ' ' + repr(r))
  17318. case Subscript(tup, index, Load()):
  17319. t = self.interp_exp(tup, env)
  17320. n = self.interp_exp(index, env)
  17321. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17322. case Call(Name('len'), [tup]):
  17323. t = self.interp_exp(tup, env)
  17324. return self.tag(len(self.untag(t, 'tuple', e)))
  17325. case _:
  17326. return self.tag(super().interp_exp(e, env))
  17327. def interp_stmt(self, s, env, cont):
  17328. match s:
  17329. case If(test, body, orelse):
  17330. v = self.interp_exp(test, env)
  17331. match self.untag(v, 'bool', s):
  17332. case True:
  17333. return self.interp_stmts(body + cont, env)
  17334. case False:
  17335. return self.interp_stmts(orelse + cont, env)
  17336. case While(test, body, []):
  17337. v = self.interp_exp(test, env)
  17338. if self.untag(v, 'bool', test):
  17339. self.interp_stmts(body + [s] + cont, env)
  17340. else:
  17341. return self.interp_stmts(cont, env)
  17342. case Assign([Subscript(tup, index)], value):
  17343. tup = self.interp_exp(tup, env)
  17344. index = self.interp_exp(index, env)
  17345. tup_v = self.untag(tup, 'tuple', s)
  17346. index_v = self.untag(index, 'int', s)
  17347. tup_v[index_v] = self.interp_exp(value, env)
  17348. return self.interp_stmts(cont, env)
  17349. case FunctionDef(name, params, bod, dl, returns, comment):
  17350. if isinstance(params, ast.arguments):
  17351. ps = [p.arg for p in params.args]
  17352. else:
  17353. ps = [x for (x,t) in params]
  17354. env[name] = self.tag(Function(name, ps, bod, env))
  17355. return self.interp_stmts(cont, env)
  17356. case _:
  17357. return super().interp_stmt(s, env, cont)
  17358. \end{lstlisting}
  17359. \end{tcolorbox}
  17360. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17361. \label{fig:interp-Ldyn-2}
  17362. \end{figure}
  17363. \fi}
  17364. \begin{figure}[tbp]
  17365. \begin{tcolorbox}[colback=white]
  17366. {\if\edition\racketEd
  17367. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17368. (define (interp-op op)
  17369. (match op
  17370. ['+ fx+]
  17371. ['- fx-]
  17372. ['read read-fixnum]
  17373. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17374. ['< (lambda (v1 v2)
  17375. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17376. ['<= (lambda (v1 v2)
  17377. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17378. ['> (lambda (v1 v2)
  17379. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17380. ['>= (lambda (v1 v2)
  17381. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17382. ['boolean? boolean?]
  17383. ['integer? fixnum?]
  17384. ['void? void?]
  17385. ['vector? vector?]
  17386. ['vector-length vector-length]
  17387. ['procedure? (match-lambda
  17388. [`(functions ,xs ,body ,env) #t] [else #f])]
  17389. [else (error 'interp-op "unknown operator" op)]))
  17390. (define (op-tags op)
  17391. (match op
  17392. ['+ '((Integer Integer))]
  17393. ['- '((Integer Integer) (Integer))]
  17394. ['read '(())]
  17395. ['not '((Boolean))]
  17396. ['< '((Integer Integer))]
  17397. ['<= '((Integer Integer))]
  17398. ['> '((Integer Integer))]
  17399. ['>= '((Integer Integer))]
  17400. ['vector-length '((Vector))]))
  17401. (define type-predicates
  17402. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17403. (define (tag-value v)
  17404. (cond [(boolean? v) (Tagged v 'Boolean)]
  17405. [(fixnum? v) (Tagged v 'Integer)]
  17406. [(procedure? v) (Tagged v 'Procedure)]
  17407. [(vector? v) (Tagged v 'Vector)]
  17408. [(void? v) (Tagged v 'Void)]
  17409. [else (error 'tag-value "unidentified value ~a" v)]))
  17410. (define (check-tag val expected ast)
  17411. (define tag (Tagged-tag val))
  17412. (unless (eq? tag expected)
  17413. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17414. \end{lstlisting}
  17415. \fi}
  17416. {\if\edition\pythonEd\pythonColor
  17417. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17418. class InterpLdyn(InterpLlambda):
  17419. def tag(self, v):
  17420. if v is True or v is False:
  17421. return Tagged(v, 'bool')
  17422. elif isinstance(v, int):
  17423. return Tagged(v, 'int')
  17424. elif isinstance(v, Function):
  17425. return Tagged(v, 'function')
  17426. elif isinstance(v, tuple):
  17427. return Tagged(v, 'tuple')
  17428. elif isinstance(v, type(None)):
  17429. return Tagged(v, 'none')
  17430. else:
  17431. raise Exception('tag: unexpected ' + repr(v))
  17432. def untag(self, v, expected_tag, ast):
  17433. match v:
  17434. case Tagged(val, tag) if tag == expected_tag:
  17435. return val
  17436. case _:
  17437. raise TrappedError('expected Tagged value with '
  17438. + expected_tag + ', not ' + ' ' + repr(v))
  17439. def apply_fun(self, fun, args, e):
  17440. f = self.untag(fun, 'function', e)
  17441. return super().apply_fun(f, args, e)
  17442. \end{lstlisting}
  17443. \fi}
  17444. \end{tcolorbox}
  17445. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17446. \label{fig:interp-Ldyn-aux}
  17447. \end{figure}
  17448. %\clearpage
  17449. \section{Representation of Tagged Values}
  17450. The interpreter for \LangDyn{} introduced a new kind of value: the
  17451. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17452. represent tagged values at the bit level. Because almost every
  17453. operation in \LangDyn{} involves manipulating tagged values, the
  17454. representation must be efficient. Recall that all our values are 64
  17455. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17456. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17457. $011$ for procedures, and $101$ for the void value\python{,
  17458. \key{None}}. We define the following auxiliary function for mapping
  17459. types to tag codes:
  17460. %
  17461. {\if\edition\racketEd
  17462. \begin{align*}
  17463. \itm{tagof}(\key{Integer}) &= 001 \\
  17464. \itm{tagof}(\key{Boolean}) &= 100 \\
  17465. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17466. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17467. \itm{tagof}(\key{Void}) &= 101
  17468. \end{align*}
  17469. \fi}
  17470. {\if\edition\pythonEd\pythonColor
  17471. \begin{align*}
  17472. \itm{tagof}(\key{IntType()}) &= 001 \\
  17473. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17474. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17475. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17476. \itm{tagof}(\key{type(None)}) &= 101
  17477. \end{align*}
  17478. \fi}
  17479. %
  17480. This stealing of 3 bits comes at some price: integers are now restricted
  17481. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17482. affect tuples and procedures because those values are addresses, and
  17483. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17484. they are always $000$. Thus, we do not lose information by overwriting
  17485. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17486. to recover the original address.
  17487. To make tagged values into first-class entities, we can give them a
  17488. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17489. operations such as \code{Inject} and \code{Project} for creating and
  17490. using them, yielding the statically typed \LangAny{} intermediate
  17491. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17492. section~\ref{sec:compile-r7}; in the next section we describe the
  17493. \LangAny{} language in greater detail.
  17494. \section{The \LangAny{} Language}
  17495. \label{sec:Rany-lang}
  17496. \newcommand{\LanyASTRacket}{
  17497. \begin{array}{lcl}
  17498. \Type &::= & \ANYTY \\
  17499. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17500. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17501. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17502. \itm{op} &::= & \code{any-vector-length}
  17503. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17504. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17505. \MID \code{procedure?} \MID \code{void?} \\
  17506. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17507. \end{array}
  17508. }
  17509. \newcommand{\LanyASTPython}{
  17510. \begin{array}{lcl}
  17511. \Type &::= & \key{AnyType()} \\
  17512. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17513. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17514. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17515. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17516. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17517. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17518. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17519. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17520. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17521. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17522. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17523. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17524. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17525. \end{array}
  17526. }
  17527. \begin{figure}[tp]
  17528. \centering
  17529. \begin{tcolorbox}[colback=white]
  17530. \small
  17531. {\if\edition\racketEd
  17532. \[
  17533. \begin{array}{l}
  17534. \gray{\LintOpAST} \\ \hline
  17535. \gray{\LvarASTRacket{}} \\ \hline
  17536. \gray{\LifASTRacket{}} \\ \hline
  17537. \gray{\LwhileASTRacket{}} \\ \hline
  17538. \gray{\LtupASTRacket{}} \\ \hline
  17539. \gray{\LfunASTRacket} \\ \hline
  17540. \gray{\LlambdaASTRacket} \\ \hline
  17541. \LanyASTRacket \\
  17542. \begin{array}{lcl}
  17543. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17544. \end{array}
  17545. \end{array}
  17546. \]
  17547. \fi}
  17548. {\if\edition\pythonEd\pythonColor
  17549. \[
  17550. \begin{array}{l}
  17551. \gray{\LintASTPython} \\ \hline
  17552. \gray{\LvarASTPython{}} \\ \hline
  17553. \gray{\LifASTPython{}} \\ \hline
  17554. \gray{\LwhileASTPython{}} \\ \hline
  17555. \gray{\LtupASTPython{}} \\ \hline
  17556. \gray{\LfunASTPython} \\ \hline
  17557. \gray{\LlambdaASTPython} \\ \hline
  17558. \LanyASTPython \\
  17559. \begin{array}{lcl}
  17560. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17561. \end{array}
  17562. \end{array}
  17563. \]
  17564. \fi}
  17565. \end{tcolorbox}
  17566. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17567. \label{fig:Lany-syntax}
  17568. \index{subject}{Lany@\LangAny{} abstract syntax}
  17569. \end{figure}
  17570. The definition of the abstract syntax of \LangAny{} is given in
  17571. figure~\ref{fig:Lany-syntax}.
  17572. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17573. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17574. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17575. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17576. converts the tagged value produced by expression $e$ into a value of
  17577. type $T$ or halts the program if the type tag does not match $T$.
  17578. %
  17579. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17580. restricted to be a flat type (the nonterminal $\FType$) which
  17581. simplifies the implementation and complies with the needs for
  17582. compiling \LangDyn{}.
  17583. The \racket{\code{any-vector}} operators
  17584. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17585. operations so that they can be applied to a value of type
  17586. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17587. tuple operations in that the index is not restricted to a literal
  17588. integer in the grammar but is allowed to be any expression.
  17589. \racket{The type predicates such as
  17590. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17591. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17592. the predicate and return {\FALSE} otherwise.}
  17593. \racket{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}
  17594. and it uses the auxiliary functions presented in figure~\ref{fig:type-check-Lany-aux}.}
  17595. \python{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}.}
  17596. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17597. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17598. \begin{figure}[btp]
  17599. \begin{tcolorbox}[colback=white]
  17600. {\if\edition\racketEd
  17601. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17602. (define type-check-Lany-class
  17603. (class type-check-Llambda-class
  17604. (super-new)
  17605. (inherit check-type-equal?)
  17606. (define/override (type-check-exp env)
  17607. (lambda (e)
  17608. (define recur (type-check-exp env))
  17609. (match e
  17610. [(Inject e1 ty)
  17611. (unless (flat-ty? ty)
  17612. (error 'type-check "may only inject from flat type, not ~a" ty))
  17613. (define-values (new-e1 e-ty) (recur e1))
  17614. (check-type-equal? e-ty ty e)
  17615. (values (Inject new-e1 ty) 'Any)]
  17616. [(Project e1 ty)
  17617. (unless (flat-ty? ty)
  17618. (error 'type-check "may only project to flat type, not ~a" ty))
  17619. (define-values (new-e1 e-ty) (recur e1))
  17620. (check-type-equal? e-ty 'Any e)
  17621. (values (Project new-e1 ty) ty)]
  17622. [(Prim 'any-vector-length (list e1))
  17623. (define-values (e1^ t1) (recur e1))
  17624. (check-type-equal? t1 'Any e)
  17625. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17626. [(Prim 'any-vector-ref (list e1 e2))
  17627. (define-values (e1^ t1) (recur e1))
  17628. (define-values (e2^ t2) (recur e2))
  17629. (check-type-equal? t1 'Any e)
  17630. (check-type-equal? t2 'Integer e)
  17631. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17632. [(Prim 'any-vector-set! (list e1 e2 e3))
  17633. (define-values (e1^ t1) (recur e1))
  17634. (define-values (e2^ t2) (recur e2))
  17635. (define-values (e3^ t3) (recur e3))
  17636. (check-type-equal? t1 'Any e)
  17637. (check-type-equal? t2 'Integer e)
  17638. (check-type-equal? t3 'Any e)
  17639. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17640. [(Prim pred (list e1))
  17641. #:when (set-member? (type-predicates) pred)
  17642. (define-values (new-e1 e-ty) (recur e1))
  17643. (check-type-equal? e-ty 'Any e)
  17644. (values (Prim pred (list new-e1)) 'Boolean)]
  17645. [(Prim 'eq? (list arg1 arg2))
  17646. (define-values (e1 t1) (recur arg1))
  17647. (define-values (e2 t2) (recur arg2))
  17648. (match* (t1 t2)
  17649. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17650. [(other wise) (check-type-equal? t1 t2 e)])
  17651. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17652. [else ((super type-check-exp env) e)])))
  17653. ))
  17654. \end{lstlisting}
  17655. \fi}
  17656. {\if\edition\pythonEd\pythonColor
  17657. \begin{lstlisting}
  17658. class TypeCheckLany(TypeCheckLlambda):
  17659. def type_check_exp(self, e, env):
  17660. match e:
  17661. case Inject(value, typ):
  17662. self.check_exp(value, typ, env)
  17663. return AnyType()
  17664. case Project(value, typ):
  17665. self.check_exp(value, AnyType(), env)
  17666. return typ
  17667. case Call(Name('any_tuple_load'), [tup, index]):
  17668. self.check_exp(tup, AnyType(), env)
  17669. self.check_exp(index, IntType(), env)
  17670. return AnyType()
  17671. case Call(Name('any_len'), [tup]):
  17672. self.check_exp(tup, AnyType(), env)
  17673. return IntType()
  17674. case Call(Name('arity'), [fun]):
  17675. ty = self.type_check_exp(fun, env)
  17676. match ty:
  17677. case FunctionType(ps, rt):
  17678. return IntType()
  17679. case TupleType([FunctionType(ps,rs)]):
  17680. return IntType()
  17681. case _:
  17682. raise Exception('type check arity unexpected ' + repr(ty))
  17683. case Call(Name('make_any'), [value, tag]):
  17684. self.type_check_exp(value, env)
  17685. self.check_exp(tag, IntType(), env)
  17686. return AnyType()
  17687. case AnnLambda(params, returns, body):
  17688. new_env = {x:t for (x,t) in env.items()}
  17689. for (x,t) in params:
  17690. new_env[x] = t
  17691. return_t = self.type_check_exp(body, new_env)
  17692. self.check_type_equal(returns, return_t, e)
  17693. return FunctionType([t for (x,t) in params], return_t)
  17694. case _:
  17695. return super().type_check_exp(e, env)
  17696. \end{lstlisting}
  17697. \fi}
  17698. \end{tcolorbox}
  17699. \caption{Type checker for the \LangAny{} language.}
  17700. \label{fig:type-check-Lany}
  17701. \end{figure}
  17702. {\if\edition\racketEd
  17703. \begin{figure}[tbp]
  17704. \begin{tcolorbox}[colback=white]
  17705. \begin{lstlisting}
  17706. (define/override (operator-types)
  17707. (append
  17708. '((integer? . ((Any) . Boolean))
  17709. (vector? . ((Any) . Boolean))
  17710. (procedure? . ((Any) . Boolean))
  17711. (void? . ((Any) . Boolean)))
  17712. (super operator-types)))
  17713. (define/public (type-predicates)
  17714. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17715. (define/public (flat-ty? ty)
  17716. (match ty
  17717. [(or `Integer `Boolean `Void) #t]
  17718. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17719. [`(,ts ... -> ,rt)
  17720. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17721. [else #f]))
  17722. \end{lstlisting}
  17723. \end{tcolorbox}
  17724. \caption{Auxiliary methods for type checking \LangAny{}.}
  17725. \label{fig:type-check-Lany-aux}
  17726. \end{figure}
  17727. \fi}
  17728. \begin{figure}[tbp]
  17729. \begin{tcolorbox}[colback=white]
  17730. {\if\edition\racketEd
  17731. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17732. (define interp-Lany-class
  17733. (class interp-Llambda-class
  17734. (super-new)
  17735. (define/override (interp-op op)
  17736. (match op
  17737. ['boolean? (match-lambda
  17738. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17739. [else #f])]
  17740. ['integer? (match-lambda
  17741. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17742. [else #f])]
  17743. ['vector? (match-lambda
  17744. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17745. [else #f])]
  17746. ['procedure? (match-lambda
  17747. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17748. [else #f])]
  17749. ['eq? (match-lambda*
  17750. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17751. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17752. [ls (apply (super interp-op op) ls)])]
  17753. ['any-vector-ref (lambda (v i)
  17754. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17755. ['any-vector-set! (lambda (v i a)
  17756. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17757. ['any-vector-length (lambda (v)
  17758. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17759. [else (super interp-op op)]))
  17760. (define/override ((interp-exp env) e)
  17761. (define recur (interp-exp env))
  17762. (match e
  17763. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17764. [(Project e ty2) (apply-project (recur e) ty2)]
  17765. [else ((super interp-exp env) e)]))
  17766. ))
  17767. (define (interp-Lany p)
  17768. (send (new interp-Lany-class) interp-program p))
  17769. \end{lstlisting}
  17770. \fi}
  17771. {\if\edition\pythonEd\pythonColor
  17772. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17773. class InterpLany(InterpLlambda):
  17774. def interp_exp(self, e, env):
  17775. match e:
  17776. case Inject(value, typ):
  17777. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17778. case Project(value, typ):
  17779. match self.interp_exp(value, env):
  17780. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17781. return val
  17782. case _:
  17783. raise Exception('failed project to ' + self.type_to_tag(typ))
  17784. case Call(Name('any_tuple_load'), [tup, index]):
  17785. match self.interp_exp(tup, env):
  17786. case Tagged(v, tag):
  17787. return v[self.interp_exp(index, env)]
  17788. case _:
  17789. raise Exception('in any_tuple_load untagged value')
  17790. case Call(Name('any_len'), [value]):
  17791. match self.interp_exp(value, env):
  17792. case Tagged(value, tag):
  17793. return len(value)
  17794. case _:
  17795. raise Exception('interp any_len untagged value')
  17796. case Call(Name('arity'), [fun]):
  17797. return self.arity(self.interp_exp(fun, env))
  17798. case _:
  17799. return super().interp_exp(e, env)
  17800. \end{lstlisting}
  17801. \fi}
  17802. \end{tcolorbox}
  17803. \caption{Interpreter for \LangAny{}.}
  17804. \label{fig:interp-Lany}
  17805. \end{figure}
  17806. \begin{figure}[btp]
  17807. \begin{tcolorbox}[colback=white]
  17808. {\if\edition\racketEd
  17809. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17810. (define/public (apply-inject v tg) (Tagged v tg))
  17811. (define/public (apply-project v ty2)
  17812. (define tag2 (any-tag ty2))
  17813. (match v
  17814. [(Tagged v1 tag1)
  17815. (cond
  17816. [(eq? tag1 tag2)
  17817. (match ty2
  17818. [`(Vector ,ts ...)
  17819. (define l1 ((interp-op 'vector-length) v1))
  17820. (cond
  17821. [(eq? l1 (length ts)) v1]
  17822. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17823. l1 (length ts))])]
  17824. [`(,ts ... -> ,rt)
  17825. (match v1
  17826. [`(function ,xs ,body ,env)
  17827. (cond [(eq? (length xs) (length ts)) v1]
  17828. [else
  17829. (error 'apply-project "arity mismatch ~a != ~a"
  17830. (length xs) (length ts))])]
  17831. [else (error 'apply-project "expected function not ~a" v1)])]
  17832. [else v1])]
  17833. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17834. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17835. \end{lstlisting}
  17836. \fi}
  17837. {\if\edition\pythonEd\pythonColor
  17838. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17839. class InterpLany(InterpLlambda):
  17840. def type_to_tag(self, typ):
  17841. match typ:
  17842. case FunctionType(params, rt):
  17843. return 'function'
  17844. case TupleType(fields):
  17845. return 'tuple'
  17846. case IntType():
  17847. return 'int'
  17848. case BoolType():
  17849. return 'bool'
  17850. case _:
  17851. raise Exception('type_to_tag unexpected ' + repr(typ))
  17852. def arity(self, v):
  17853. match v:
  17854. case Function(name, params, body, env):
  17855. return len(params)
  17856. case _:
  17857. raise Exception('Lany arity unexpected ' + repr(v))
  17858. \end{lstlisting}
  17859. \fi}
  17860. \end{tcolorbox}
  17861. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17862. \label{fig:interp-Lany-aux}
  17863. \end{figure}
  17864. \clearpage
  17865. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17866. \label{sec:compile-r7}
  17867. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17868. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17869. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17870. is that given any subexpression $e$ in the \LangDyn{} program, the
  17871. pass will produce an expression $e'$ in \LangAny{} that has type
  17872. \ANYTY{}. For example, the first row in
  17873. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17874. \TRUE{}, which must be injected to produce an expression of type
  17875. \ANYTY{}.
  17876. %
  17877. The compilation of addition is shown in the second row of
  17878. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17879. representative of many primitive operations: the arguments have type
  17880. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17881. be performed.
  17882. The compilation of \key{lambda} (third row of
  17883. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17884. produce type annotations: we simply use \ANYTY{}.
  17885. %
  17886. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17887. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17888. this pass has to account for some differences in behavior between
  17889. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17890. permissive than \LangAny{} regarding what kind of values can be used
  17891. in various places. For example, the condition of an \key{if} does
  17892. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17893. of the same type (in that case the result is \code{\#f}).}
  17894. \begin{figure}[btp]
  17895. \centering
  17896. \begin{tcolorbox}[colback=white]
  17897. {\if\edition\racketEd
  17898. \begin{tabular}{lll}
  17899. \begin{minipage}{0.27\textwidth}
  17900. \begin{lstlisting}
  17901. #t
  17902. \end{lstlisting}
  17903. \end{minipage}
  17904. &
  17905. $\Rightarrow$
  17906. &
  17907. \begin{minipage}{0.65\textwidth}
  17908. \begin{lstlisting}
  17909. (inject #t Boolean)
  17910. \end{lstlisting}
  17911. \end{minipage}
  17912. \\[2ex]\hline
  17913. \begin{minipage}{0.27\textwidth}
  17914. \begin{lstlisting}
  17915. (+ |$e_1$| |$e_2$|)
  17916. \end{lstlisting}
  17917. \end{minipage}
  17918. &
  17919. $\Rightarrow$
  17920. &
  17921. \begin{minipage}{0.65\textwidth}
  17922. \begin{lstlisting}
  17923. (inject
  17924. (+ (project |$e'_1$| Integer)
  17925. (project |$e'_2$| Integer))
  17926. Integer)
  17927. \end{lstlisting}
  17928. \end{minipage}
  17929. \\[2ex]\hline
  17930. \begin{minipage}{0.27\textwidth}
  17931. \begin{lstlisting}
  17932. (lambda (|$x_1 \ldots$|) |$e$|)
  17933. \end{lstlisting}
  17934. \end{minipage}
  17935. &
  17936. $\Rightarrow$
  17937. &
  17938. \begin{minipage}{0.65\textwidth}
  17939. \begin{lstlisting}
  17940. (inject
  17941. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17942. (Any|$\ldots$|Any -> Any))
  17943. \end{lstlisting}
  17944. \end{minipage}
  17945. \\[2ex]\hline
  17946. \begin{minipage}{0.27\textwidth}
  17947. \begin{lstlisting}
  17948. (|$e_0$| |$e_1 \ldots e_n$|)
  17949. \end{lstlisting}
  17950. \end{minipage}
  17951. &
  17952. $\Rightarrow$
  17953. &
  17954. \begin{minipage}{0.65\textwidth}
  17955. \begin{lstlisting}
  17956. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17957. \end{lstlisting}
  17958. \end{minipage}
  17959. \\[2ex]\hline
  17960. \begin{minipage}{0.27\textwidth}
  17961. \begin{lstlisting}
  17962. (vector-ref |$e_1$| |$e_2$|)
  17963. \end{lstlisting}
  17964. \end{minipage}
  17965. &
  17966. $\Rightarrow$
  17967. &
  17968. \begin{minipage}{0.65\textwidth}
  17969. \begin{lstlisting}
  17970. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17971. \end{lstlisting}
  17972. \end{minipage}
  17973. \\[2ex]\hline
  17974. \begin{minipage}{0.27\textwidth}
  17975. \begin{lstlisting}
  17976. (if |$e_1$| |$e_2$| |$e_3$|)
  17977. \end{lstlisting}
  17978. \end{minipage}
  17979. &
  17980. $\Rightarrow$
  17981. &
  17982. \begin{minipage}{0.65\textwidth}
  17983. \begin{lstlisting}
  17984. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17985. \end{lstlisting}
  17986. \end{minipage}
  17987. \\[2ex]\hline
  17988. \begin{minipage}{0.27\textwidth}
  17989. \begin{lstlisting}
  17990. (eq? |$e_1$| |$e_2$|)
  17991. \end{lstlisting}
  17992. \end{minipage}
  17993. &
  17994. $\Rightarrow$
  17995. &
  17996. \begin{minipage}{0.65\textwidth}
  17997. \begin{lstlisting}
  17998. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17999. \end{lstlisting}
  18000. \end{minipage}
  18001. \\[2ex]\hline
  18002. \begin{minipage}{0.27\textwidth}
  18003. \begin{lstlisting}
  18004. (not |$e_1$|)
  18005. \end{lstlisting}
  18006. \end{minipage}
  18007. &
  18008. $\Rightarrow$
  18009. &
  18010. \begin{minipage}{0.65\textwidth}
  18011. \begin{lstlisting}
  18012. (if (eq? |$e'_1$| (inject #f Boolean))
  18013. (inject #t Boolean) (inject #f Boolean))
  18014. \end{lstlisting}
  18015. \end{minipage}
  18016. \end{tabular}
  18017. \fi}
  18018. {\if\edition\pythonEd\pythonColor
  18019. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  18020. \begin{minipage}{0.23\textwidth}
  18021. \begin{lstlisting}
  18022. True
  18023. \end{lstlisting}
  18024. \end{minipage}
  18025. &
  18026. $\Rightarrow$
  18027. &
  18028. \begin{minipage}{0.7\textwidth}
  18029. \begin{lstlisting}
  18030. Inject(True, BoolType())
  18031. \end{lstlisting}
  18032. \end{minipage}
  18033. \\[2ex]\hline
  18034. \begin{minipage}{0.23\textwidth}
  18035. \begin{lstlisting}
  18036. |$e_1$| + |$e_2$|
  18037. \end{lstlisting}
  18038. \end{minipage}
  18039. &
  18040. $\Rightarrow$
  18041. &
  18042. \begin{minipage}{0.7\textwidth}
  18043. \begin{lstlisting}
  18044. Inject(Project(|$e'_1$|, IntType())
  18045. + Project(|$e'_2$|, IntType()),
  18046. IntType())
  18047. \end{lstlisting}
  18048. \end{minipage}
  18049. \\[2ex]\hline
  18050. \begin{minipage}{0.23\textwidth}
  18051. \begin{lstlisting}
  18052. lambda |$x_1 \ldots$|: |$e$|
  18053. \end{lstlisting}
  18054. \end{minipage}
  18055. &
  18056. $\Rightarrow$
  18057. &
  18058. \begin{minipage}{0.7\textwidth}
  18059. \begin{lstlisting}
  18060. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18061. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18062. \end{lstlisting}
  18063. \end{minipage}
  18064. \\[2ex]\hline
  18065. \begin{minipage}{0.23\textwidth}
  18066. \begin{lstlisting}
  18067. |$e_0$|(|$e_1 \ldots e_n$|)
  18068. \end{lstlisting}
  18069. \end{minipage}
  18070. &
  18071. $\Rightarrow$
  18072. &
  18073. \begin{minipage}{0.7\textwidth}
  18074. \begin{lstlisting}
  18075. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18076. AnyType())), |$e'_1, \ldots, e'_n$|)
  18077. \end{lstlisting}
  18078. \end{minipage}
  18079. \\[2ex]\hline
  18080. \begin{minipage}{0.23\textwidth}
  18081. \begin{lstlisting}
  18082. |$e_1$|[|$e_2$|]
  18083. \end{lstlisting}
  18084. \end{minipage}
  18085. &
  18086. $\Rightarrow$
  18087. &
  18088. \begin{minipage}{0.7\textwidth}
  18089. \begin{lstlisting}
  18090. Call(Name('any_tuple_load'),
  18091. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18092. \end{lstlisting}
  18093. \end{minipage}
  18094. %% \begin{minipage}{0.23\textwidth}
  18095. %% \begin{lstlisting}
  18096. %% |$e_2$| if |$e_1$| else |$e_3$|
  18097. %% \end{lstlisting}
  18098. %% \end{minipage}
  18099. %% &
  18100. %% $\Rightarrow$
  18101. %% &
  18102. %% \begin{minipage}{0.7\textwidth}
  18103. %% \begin{lstlisting}
  18104. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18105. %% \end{lstlisting}
  18106. %% \end{minipage}
  18107. %% \\[2ex]\hline
  18108. %% \begin{minipage}{0.23\textwidth}
  18109. %% \begin{lstlisting}
  18110. %% (eq? |$e_1$| |$e_2$|)
  18111. %% \end{lstlisting}
  18112. %% \end{minipage}
  18113. %% &
  18114. %% $\Rightarrow$
  18115. %% &
  18116. %% \begin{minipage}{0.7\textwidth}
  18117. %% \begin{lstlisting}
  18118. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18119. %% \end{lstlisting}
  18120. %% \end{minipage}
  18121. %% \\[2ex]\hline
  18122. %% \begin{minipage}{0.23\textwidth}
  18123. %% \begin{lstlisting}
  18124. %% (not |$e_1$|)
  18125. %% \end{lstlisting}
  18126. %% \end{minipage}
  18127. %% &
  18128. %% $\Rightarrow$
  18129. %% &
  18130. %% \begin{minipage}{0.7\textwidth}
  18131. %% \begin{lstlisting}
  18132. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18133. %% (inject #t Boolean) (inject #f Boolean))
  18134. %% \end{lstlisting}
  18135. %% \end{minipage}
  18136. %% \\[2ex]\hline
  18137. \\\hline
  18138. \end{tabular}
  18139. \fi}
  18140. \end{tcolorbox}
  18141. \caption{Cast insertion.}
  18142. \label{fig:compile-r7-Lany}
  18143. \end{figure}
  18144. \section{Reveal Casts}
  18145. \label{sec:reveal-casts-Lany}
  18146. % TODO: define R'_6
  18147. In the \code{reveal\_casts} pass, we recommend compiling
  18148. \code{Project} into a conditional expression that checks whether the
  18149. value's tag matches the target type; if it does, the value is
  18150. converted to a value of the target type by removing the tag; if it
  18151. does not, the program exits.
  18152. %
  18153. {\if\edition\racketEd
  18154. %
  18155. To perform these actions we need a new primitive operation,
  18156. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18157. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18158. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18159. underlying value from a tagged value. The \code{ValueOf} form
  18160. includes the type for the underlying value that is used by the type
  18161. checker.
  18162. %
  18163. \fi}
  18164. %
  18165. {\if\edition\pythonEd\pythonColor
  18166. %
  18167. To perform these actions we need two new AST classes: \code{TagOf} and
  18168. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18169. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18170. the underlying value from a tagged value. The \code{ValueOf}
  18171. operation includes the type for the underlying value that is used by
  18172. the type checker.
  18173. %
  18174. \fi}
  18175. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18176. \code{Project} can be translated as follows:
  18177. \begin{center}
  18178. \begin{minipage}{1.0\textwidth}
  18179. {\if\edition\racketEd
  18180. \begin{lstlisting}
  18181. (Project |$e$| |$\FType$|)
  18182. |$\Rightarrow$|
  18183. (Let |$\itm{tmp}$| |$e'$|
  18184. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18185. (Int |$\itm{tagof}(\FType)$|)))
  18186. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18187. (Exit)))
  18188. \end{lstlisting}
  18189. \fi}
  18190. {\if\edition\pythonEd\pythonColor
  18191. \begin{lstlisting}
  18192. Project(|$e$|, |$\FType$|)
  18193. |$\Rightarrow$|
  18194. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18195. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18196. [Constant(|$\itm{tagof}(\FType)$|)]),
  18197. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18198. Call(Name('exit'), [])))
  18199. \end{lstlisting}
  18200. \fi}
  18201. \end{minipage}
  18202. \end{center}
  18203. If the target type of the projection is a tuple or function type, then
  18204. there is a bit more work to do. For tuples, check that the length of
  18205. the tuple type matches the length of the tuple. For functions, check
  18206. that the number of parameters in the function type matches the
  18207. function's arity.
  18208. Regarding \code{Inject}, we recommend compiling it to a slightly
  18209. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18210. takes a tag instead of a type.
  18211. \begin{center}
  18212. \begin{minipage}{1.0\textwidth}
  18213. {\if\edition\racketEd
  18214. \begin{lstlisting}
  18215. (Inject |$e$| |$\FType$|)
  18216. |$\Rightarrow$|
  18217. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18218. \end{lstlisting}
  18219. \fi}
  18220. {\if\edition\pythonEd\pythonColor
  18221. \begin{lstlisting}
  18222. Inject(|$e$|, |$\FType$|)
  18223. |$\Rightarrow$|
  18224. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18225. \end{lstlisting}
  18226. \fi}
  18227. \end{minipage}
  18228. \end{center}
  18229. {\if\edition\pythonEd\pythonColor
  18230. %
  18231. The introduction of \code{make\_any} makes it difficult to use
  18232. bidirectional type checking because we no longer have an expected type
  18233. to use for type checking the expression $e'$. Thus, we run into
  18234. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18235. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18236. annotated lambda) that contains its return type and the types of its
  18237. parameters.
  18238. %
  18239. \fi}
  18240. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18241. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18242. translation of \code{Project}.}
  18243. {\if\edition\racketEd
  18244. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18245. combine the projection action with the vector operation. Also, the
  18246. read and write operations allow arbitrary expressions for the index, so
  18247. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18248. cannot guarantee that the index is within bounds. Thus, we insert code
  18249. to perform bounds checking at runtime. The translation for
  18250. \code{any-vector-ref} is as follows, and the other two operations are
  18251. translated in a similar way:
  18252. \begin{center}
  18253. \begin{minipage}{0.95\textwidth}
  18254. \begin{lstlisting}
  18255. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18256. |$\Rightarrow$|
  18257. (Let |$v$| |$e'_1$|
  18258. (Let |$i$| |$e'_2$|
  18259. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18260. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18261. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18262. (Exit))
  18263. (Exit))))
  18264. \end{lstlisting}
  18265. \end{minipage}
  18266. \end{center}
  18267. \fi}
  18268. %
  18269. {\if\edition\pythonEd\pythonColor
  18270. %
  18271. The \code{any\_tuple\_load} operation combines the projection action
  18272. with the load operation. Also, the load operation allows arbitrary
  18273. expressions for the index, so the type checker for \LangAny{}
  18274. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18275. within bounds. Thus, we insert code to perform bounds checking at
  18276. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18277. \begin{lstlisting}
  18278. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18279. |$\Rightarrow$|
  18280. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18281. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18282. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18283. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18284. Call(Name('exit'), [])),
  18285. Call(Name('exit'), [])))
  18286. \end{lstlisting}
  18287. \fi}
  18288. {\if\edition\pythonEd\pythonColor
  18289. \section{Assignment Conversion}
  18290. \label{sec:convert-assignments-Lany}
  18291. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18292. \code{AnnLambda} AST classes.
  18293. \section{Closure Conversion}
  18294. \label{sec:closure-conversion-Lany}
  18295. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18296. \code{AnnLambda} AST classes.
  18297. \fi}
  18298. \section{Remove Complex Operands}
  18299. \label{sec:rco-Lany}
  18300. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18301. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18302. %
  18303. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18304. complex expressions. Their subexpressions must be atomic.}
  18305. \section{Explicate Control and \LangCAny{}}
  18306. \label{sec:explicate-Lany}
  18307. The output of \code{explicate\_control} is the \LangCAny{} language,
  18308. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18309. %
  18310. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18311. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18312. note that the index argument of \code{vector-ref} and
  18313. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18314. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18315. %
  18316. \python{Update the auxiliary functions \code{explicate\_tail},
  18317. \code{explicate\_effect}, and \code{explicate\_pred} as
  18318. appropriate to handle the new expressions in \LangCAny{}. }
  18319. \newcommand{\CanyASTPython}{
  18320. \begin{array}{lcl}
  18321. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18322. &\MID& \key{TagOf}\LP \Atm \RP
  18323. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18324. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18325. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18326. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18327. \end{array}
  18328. }
  18329. \newcommand{\CanyASTRacket}{
  18330. \begin{array}{lcl}
  18331. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18332. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18333. &\MID& \VALUEOF{\Atm}{\FType} \\
  18334. \Tail &::= & \LP\key{Exit}\RP
  18335. \end{array}
  18336. }
  18337. \begin{figure}[tp]
  18338. \begin{tcolorbox}[colback=white]
  18339. \small
  18340. {\if\edition\racketEd
  18341. \[
  18342. \begin{array}{l}
  18343. \gray{\CvarASTRacket} \\ \hline
  18344. \gray{\CifASTRacket} \\ \hline
  18345. \gray{\CloopASTRacket} \\ \hline
  18346. \gray{\CtupASTRacket} \\ \hline
  18347. \gray{\CfunASTRacket} \\ \hline
  18348. \gray{\ClambdaASTRacket} \\ \hline
  18349. \CanyASTRacket \\
  18350. \begin{array}{lcl}
  18351. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18352. \end{array}
  18353. \end{array}
  18354. \]
  18355. \fi}
  18356. {\if\edition\pythonEd\pythonColor
  18357. \[
  18358. \begin{array}{l}
  18359. \gray{\CifASTPython} \\ \hline
  18360. \gray{\CtupASTPython} \\ \hline
  18361. \gray{\CfunASTPython} \\ \hline
  18362. \gray{\ClambdaASTPython} \\ \hline
  18363. \CanyASTPython \\
  18364. \begin{array}{lcl}
  18365. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18366. \end{array}
  18367. \end{array}
  18368. \]
  18369. \fi}
  18370. \end{tcolorbox}
  18371. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18372. \label{fig:c5-syntax}
  18373. \index{subject}{Cany@\LangCAny{} abstract syntax}
  18374. \end{figure}
  18375. \section{Select Instructions}
  18376. \label{sec:select-Lany}
  18377. \index{subject}{select instructions}
  18378. In the \code{select\_instructions} pass, we translate the primitive
  18379. operations on the \ANYTY{} type to x86 instructions that manipulate
  18380. the three tag bits of the tagged value. In the following descriptions,
  18381. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18382. of translating $e$ into an x86 argument:
  18383. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18384. We recommend compiling the
  18385. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18386. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18387. shifts the destination to the left by the number of bits specified by its
  18388. source argument (in this case three, the length of the tag), and it
  18389. preserves the sign of the integer. We use the \key{orq} instruction to
  18390. combine the tag and the value to form the tagged value.
  18391. {\if\edition\racketEd
  18392. \begin{lstlisting}
  18393. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18394. |$\Rightarrow$|
  18395. movq |$e'$|, |\itm{lhs'}|
  18396. salq $3, |\itm{lhs'}|
  18397. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18398. \end{lstlisting}
  18399. \fi}
  18400. %
  18401. {\if\edition\pythonEd\pythonColor
  18402. \begin{lstlisting}
  18403. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18404. |$\Rightarrow$|
  18405. movq |$e'$|, |\itm{lhs'}|
  18406. salq $3, |\itm{lhs'}|
  18407. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18408. \end{lstlisting}
  18409. \fi}
  18410. %
  18411. The instruction selection\index{subject}{instruction selection} for
  18412. tuples and procedures is different because there is no need to shift
  18413. them to the left. The rightmost 3 bits are already zeros, so we simply
  18414. combine the value and the tag using \key{orq}. \\
  18415. %
  18416. {\if\edition\racketEd
  18417. \begin{center}
  18418. \begin{minipage}{\textwidth}
  18419. \begin{lstlisting}
  18420. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18421. |$\Rightarrow$|
  18422. movq |$e'$|, |\itm{lhs'}|
  18423. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18424. \end{lstlisting}
  18425. \end{minipage}
  18426. \end{center}
  18427. \fi}
  18428. %
  18429. {\if\edition\pythonEd\pythonColor
  18430. \begin{lstlisting}
  18431. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18432. |$\Rightarrow$|
  18433. movq |$e'$|, |\itm{lhs'}|
  18434. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18435. \end{lstlisting}
  18436. \fi}
  18437. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18438. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18439. operation extracts the type tag from a value of type \ANYTY{}. The
  18440. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18441. bitwise-and of the value with $111$ ($7$ decimal).
  18442. %
  18443. {\if\edition\racketEd
  18444. \begin{lstlisting}
  18445. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18446. |$\Rightarrow$|
  18447. movq |$e'$|, |\itm{lhs'}|
  18448. andq $7, |\itm{lhs'}|
  18449. \end{lstlisting}
  18450. \fi}
  18451. %
  18452. {\if\edition\pythonEd\pythonColor
  18453. \begin{lstlisting}
  18454. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18455. |$\Rightarrow$|
  18456. movq |$e'$|, |\itm{lhs'}|
  18457. andq $7, |\itm{lhs'}|
  18458. \end{lstlisting}
  18459. \fi}
  18460. \paragraph{\code{ValueOf}}
  18461. The instructions for \key{ValueOf} also differ, depending on whether
  18462. the type $T$ is a pointer (tuple or function) or not (integer or
  18463. Boolean). The following shows the instruction
  18464. selection for integers and
  18465. Booleans, in which we produce an untagged value by shifting it to the
  18466. right by 3 bits:
  18467. %
  18468. {\if\edition\racketEd
  18469. \begin{lstlisting}
  18470. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18471. |$\Rightarrow$|
  18472. movq |$e'$|, |\itm{lhs'}|
  18473. sarq $3, |\itm{lhs'}|
  18474. \end{lstlisting}
  18475. \fi}
  18476. %
  18477. {\if\edition\pythonEd\pythonColor
  18478. \begin{lstlisting}
  18479. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18480. |$\Rightarrow$|
  18481. movq |$e'$|, |\itm{lhs'}|
  18482. sarq $3, |\itm{lhs'}|
  18483. \end{lstlisting}
  18484. \fi}
  18485. %
  18486. In the case for tuples and procedures, we zero out the rightmost 3
  18487. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18488. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18489. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18490. Finally, we apply \code{andq} with the tagged value to get the desired
  18491. result.
  18492. %
  18493. {\if\edition\racketEd
  18494. \begin{lstlisting}
  18495. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18496. |$\Rightarrow$|
  18497. movq $|$-8$|, |\itm{lhs'}|
  18498. andq |$e'$|, |\itm{lhs'}|
  18499. \end{lstlisting}
  18500. \fi}
  18501. %
  18502. {\if\edition\pythonEd\pythonColor
  18503. \begin{lstlisting}
  18504. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18505. |$\Rightarrow$|
  18506. movq $|$-8$|, |\itm{lhs'}|
  18507. andq |$e'$|, |\itm{lhs'}|
  18508. \end{lstlisting}
  18509. \fi}
  18510. %% \paragraph{Type Predicates} We leave it to the reader to
  18511. %% devise a sequence of instructions to implement the type predicates
  18512. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18513. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18514. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18515. operation combines the effect of \code{ValueOf} with accessing the
  18516. length of a tuple from the tag stored at the zero index of the tuple.
  18517. {\if\edition\racketEd
  18518. \begin{lstlisting}
  18519. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18520. |$\Longrightarrow$|
  18521. movq $|$-8$|, %r11
  18522. andq |$e_1'$|, %r11
  18523. movq 0(%r11), %r11
  18524. andq $126, %r11
  18525. sarq $1, %r11
  18526. movq %r11, |$\itm{lhs'}$|
  18527. \end{lstlisting}
  18528. \fi}
  18529. {\if\edition\pythonEd\pythonColor
  18530. \begin{lstlisting}
  18531. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18532. |$\Longrightarrow$|
  18533. movq $|$-8$|, %r11
  18534. andq |$e_1'$|, %r11
  18535. movq 0(%r11), %r11
  18536. andq $126, %r11
  18537. sarq $1, %r11
  18538. movq %r11, |$\itm{lhs'}$|
  18539. \end{lstlisting}
  18540. \fi}
  18541. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18542. This operation combines the effect of \code{ValueOf} with reading an
  18543. element of the tuple (see
  18544. section~\ref{sec:select-instructions-gc}). However, the index may be
  18545. an arbitrary atom, so instead of computing the offset at compile time,
  18546. we must generate instructions to compute the offset at runtime as
  18547. follows. Note the use of the new instruction \code{imulq}.
  18548. \begin{center}
  18549. \begin{minipage}{0.96\textwidth}
  18550. {\if\edition\racketEd
  18551. \begin{lstlisting}
  18552. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18553. |$\Longrightarrow$|
  18554. movq |$\neg 111$|, %r11
  18555. andq |$e_1'$|, %r11
  18556. movq |$e_2'$|, %rax
  18557. addq $1, %rax
  18558. imulq $8, %rax
  18559. addq %rax, %r11
  18560. movq 0(%r11) |$\itm{lhs'}$|
  18561. \end{lstlisting}
  18562. \fi}
  18563. %
  18564. {\if\edition\pythonEd\pythonColor
  18565. \begin{lstlisting}
  18566. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18567. |$\Longrightarrow$|
  18568. movq $|$-8$|, %r11
  18569. andq |$e_1'$|, %r11
  18570. movq |$e_2'$|, %rax
  18571. addq $1, %rax
  18572. imulq $8, %rax
  18573. addq %rax, %r11
  18574. movq 0(%r11) |$\itm{lhs'}$|
  18575. \end{lstlisting}
  18576. \fi}
  18577. \end{minipage}
  18578. \end{center}
  18579. % $ pacify font lock
  18580. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18581. %% The code generation for
  18582. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18583. %% analogous to the above translation for reading from a tuple.
  18584. \section{Register Allocation for \LangAny{} }
  18585. \label{sec:register-allocation-Lany}
  18586. \index{subject}{register allocation}
  18587. There is an interesting interaction between tagged values and garbage
  18588. collection that has an impact on register allocation. A variable of
  18589. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18590. that needs to be inspected and copied during garbage collection. Thus,
  18591. we need to treat variables of type \ANYTY{} in a similar way to
  18592. variables of tuple type for purposes of register allocation,
  18593. with particular attention to the following:
  18594. \begin{itemize}
  18595. \item If a variable of type \ANYTY{} is live during a function call,
  18596. then it must be spilled. This can be accomplished by changing
  18597. \code{build\_interference} to mark all variables of type \ANYTY{}
  18598. that are live after a \code{callq} to be interfering with all the
  18599. registers.
  18600. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18601. the root stack instead of the normal procedure call stack.
  18602. \end{itemize}
  18603. Another concern regarding the root stack is that the garbage collector
  18604. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18605. tagged value that points to a tuple, and (3) a tagged value that is
  18606. not a tuple. We enable this differentiation by choosing not to use the
  18607. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18608. reserved for identifying plain old pointers to tuples. That way, if
  18609. one of the first three bits is set, then we have a tagged value and
  18610. inspecting the tag can differentiate between tuples ($010$) and the
  18611. other kinds of values.
  18612. %% \begin{exercise}\normalfont
  18613. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18614. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18615. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18616. %% compiler on these new programs and all of your previously created test
  18617. %% programs.
  18618. %% \end{exercise}
  18619. \begin{exercise}\normalfont\normalsize
  18620. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18621. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18622. by removing type annotations. Add five more test programs that
  18623. specifically rely on the language being dynamically typed. That is,
  18624. they should not be legal programs in a statically typed language, but
  18625. nevertheless they should be valid \LangDyn{} programs that run to
  18626. completion without error.
  18627. \end{exercise}
  18628. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18629. for the compilation of \LangDyn{}.
  18630. \begin{figure}[bthp]
  18631. \begin{tcolorbox}[colback=white]
  18632. {\if\edition\racketEd
  18633. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18634. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18635. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18636. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18637. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18638. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18639. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18640. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18641. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18642. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18643. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18644. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18645. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18646. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18647. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18648. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18649. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18650. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18651. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18652. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18653. \path[->,bend left=15] (Lfun) edge [above] node
  18654. {\ttfamily\footnotesize shrink} (Lfun-2);
  18655. \path[->,bend left=15] (Lfun-2) edge [above] node
  18656. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18657. \path[->,bend left=15] (Lfun-3) edge [above] node
  18658. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18659. \path[->,bend left=15] (Lfun-4) edge [left] node
  18660. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18661. \path[->,bend left=15] (Lfun-5) edge [below] node
  18662. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18663. \path[->,bend left=15] (Lfun-6) edge [below] node
  18664. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18665. \path[->,bend right=15] (Lfun-7) edge [above] node
  18666. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18667. \path[->,bend right=15] (F1-2) edge [right] node
  18668. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18669. \path[->,bend right=15] (F1-3) edge [below] node
  18670. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18671. \path[->,bend right=15] (F1-4) edge [below] node
  18672. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18673. \path[->,bend left=15] (F1-5) edge [above] node
  18674. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18675. \path[->,bend left=10] (F1-6) edge [below] node
  18676. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18677. \path[->,bend left=15] (C3-2) edge [right] node
  18678. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18679. \path[->,bend right=15] (x86-2) edge [right] node
  18680. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18681. \path[->,bend right=15] (x86-2-1) edge [below] node
  18682. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18683. \path[->,bend right=15] (x86-2-2) edge [right] node
  18684. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18685. \path[->,bend left=15] (x86-3) edge [above] node
  18686. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18687. \path[->,bend left=15] (x86-4) edge [right] node
  18688. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18689. \end{tikzpicture}
  18690. \fi}
  18691. {\if\edition\pythonEd\pythonColor
  18692. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18693. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18694. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18695. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18696. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18697. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18698. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18699. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18700. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18701. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18702. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18703. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18704. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18705. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18706. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18707. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18708. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18709. \path[->,bend left=15] (Lfun) edge [above] node
  18710. {\ttfamily\footnotesize shrink} (Lfun-2);
  18711. \path[->,bend left=15] (Lfun-2) edge [above] node
  18712. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18713. \path[->,bend left=15] (Lfun-3) edge [above] node
  18714. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18715. \path[->,bend left=15] (Lfun-4) edge [left] node
  18716. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18717. \path[->,bend left=15] (Lfun-5) edge [below] node
  18718. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18719. \path[->,bend right=15] (Lfun-6) edge [above] node
  18720. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18721. \path[->,bend right=15] (Lfun-7) edge [above] node
  18722. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18723. \path[->,bend right=15] (F1-2) edge [right] node
  18724. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18725. \path[->,bend right=15] (F1-3) edge [below] node
  18726. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18727. \path[->,bend left=15] (F1-5) edge [above] node
  18728. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18729. \path[->,bend left=10] (F1-6) edge [below] node
  18730. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18731. \path[->,bend right=15] (C3-2) edge [right] node
  18732. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18733. \path[->,bend right=15] (x86-2) edge [below] node
  18734. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18735. \path[->,bend right=15] (x86-3) edge [below] node
  18736. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18737. \path[->,bend left=15] (x86-4) edge [above] node
  18738. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18739. \end{tikzpicture}
  18740. \fi}
  18741. \end{tcolorbox}
  18742. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18743. \label{fig:Ldyn-passes}
  18744. \end{figure}
  18745. % Further Reading
  18746. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18747. %% {\if\edition\pythonEd\pythonColor
  18748. %% \chapter{Objects}
  18749. %% \label{ch:Lobject}
  18750. %% \index{subject}{objects}
  18751. %% \index{subject}{classes}
  18752. %% \setcounter{footnote}{0}
  18753. %% \fi}
  18754. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18755. \chapter{Gradual Typing}
  18756. \label{ch:Lgrad}
  18757. \index{subject}{gradual typing}
  18758. \setcounter{footnote}{0}
  18759. This chapter studies the language \LangGrad{}, in which the programmer
  18760. can choose between static and dynamic type checking in different parts
  18761. of a program, thereby mixing the statically typed \LangLam{} language
  18762. with the dynamically typed \LangDyn{}. There are several approaches to
  18763. mixing static and dynamic typing, including multilanguage
  18764. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18765. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18766. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18767. programmer controls the amount of static versus dynamic checking by
  18768. adding or removing type annotations on parameters and
  18769. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18770. The definition of the concrete syntax of \LangGrad{} is shown in
  18771. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18772. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18773. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18774. annotations are optional, which is specified in the grammar using the
  18775. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18776. annotations are not optional, but we use the \CANYTY{} type when a type
  18777. annotation is absent.
  18778. %
  18779. Both the type checker and the interpreter for \LangGrad{} require some
  18780. interesting changes to enable gradual typing, which we discuss in the
  18781. next two sections.
  18782. \newcommand{\LgradGrammarRacket}{
  18783. \begin{array}{lcl}
  18784. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18785. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18786. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18787. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18788. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18789. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18790. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18791. \end{array}
  18792. }
  18793. \newcommand{\LgradASTRacket}{
  18794. \begin{array}{lcl}
  18795. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18796. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18797. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18798. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18799. \itm{op} &::=& \code{procedure-arity} \\
  18800. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18801. \end{array}
  18802. }
  18803. \newcommand{\LgradGrammarPython}{
  18804. \begin{array}{lcl}
  18805. \Type &::=& \key{Any}
  18806. \MID \key{int}
  18807. \MID \key{bool}
  18808. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18809. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18810. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18811. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18812. \MID \CARITY{\Exp} \\
  18813. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18814. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18815. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18816. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18817. \end{array}
  18818. }
  18819. \newcommand{\LgradASTPython}{
  18820. \begin{array}{lcl}
  18821. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18822. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18823. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18824. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18825. &\MID& \ARITY{\Exp} \\
  18826. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18827. \MID \RETURN{\Exp} \\
  18828. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18829. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18830. \end{array}
  18831. }
  18832. \begin{figure}[tbp]
  18833. \centering
  18834. \begin{tcolorbox}[colback=white]
  18835. \vspace{-5pt}
  18836. \small
  18837. {\if\edition\racketEd
  18838. \[
  18839. \begin{array}{l}
  18840. \gray{\LintGrammarRacket{}} \\ \hline
  18841. \gray{\LvarGrammarRacket{}} \\ \hline
  18842. \gray{\LifGrammarRacket{}} \\ \hline
  18843. \gray{\LwhileGrammarRacket} \\ \hline
  18844. \gray{\LtupGrammarRacket} \\ \hline
  18845. \LgradGrammarRacket \\
  18846. \begin{array}{lcl}
  18847. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18848. \end{array}
  18849. \end{array}
  18850. \]
  18851. \fi}
  18852. {\if\edition\pythonEd\pythonColor
  18853. \[
  18854. \begin{array}{l}
  18855. \gray{\LintGrammarPython{}} \\ \hline
  18856. \gray{\LvarGrammarPython{}} \\ \hline
  18857. \gray{\LifGrammarPython{}} \\ \hline
  18858. \gray{\LwhileGrammarPython} \\ \hline
  18859. \gray{\LtupGrammarPython} \\ \hline
  18860. \LgradGrammarPython \\
  18861. \begin{array}{lcl}
  18862. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18863. \end{array}
  18864. \end{array}
  18865. \]
  18866. \fi}
  18867. \end{tcolorbox}
  18868. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18869. \label{fig:Lgrad-concrete-syntax}
  18870. \index{subject}{L?@\LangGrad{} concrete syntax}
  18871. \end{figure}
  18872. \begin{figure}[tbp]
  18873. \centering
  18874. \begin{tcolorbox}[colback=white]
  18875. \small
  18876. {\if\edition\racketEd
  18877. \[
  18878. \begin{array}{l}
  18879. \gray{\LintOpAST} \\ \hline
  18880. \gray{\LvarASTRacket{}} \\ \hline
  18881. \gray{\LifASTRacket{}} \\ \hline
  18882. \gray{\LwhileASTRacket{}} \\ \hline
  18883. \gray{\LtupASTRacket{}} \\ \hline
  18884. \LgradASTRacket \\
  18885. \begin{array}{lcl}
  18886. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18887. \end{array}
  18888. \end{array}
  18889. \]
  18890. \fi}
  18891. {\if\edition\pythonEd\pythonColor
  18892. \[
  18893. \begin{array}{l}
  18894. \gray{\LintASTPython{}} \\ \hline
  18895. \gray{\LvarASTPython{}} \\ \hline
  18896. \gray{\LifASTPython{}} \\ \hline
  18897. \gray{\LwhileASTPython} \\ \hline
  18898. \gray{\LtupASTPython} \\ \hline
  18899. \LgradASTPython \\
  18900. \begin{array}{lcl}
  18901. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18902. \end{array}
  18903. \end{array}
  18904. \]
  18905. \fi}
  18906. \end{tcolorbox}
  18907. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18908. \label{fig:Lgrad-syntax}
  18909. \index{subject}{L?@\LangGrad{} abstract syntax}
  18910. \end{figure}
  18911. % TODO: more road map -Jeremy
  18912. %\clearpage
  18913. \section{Type Checking \LangGrad{}}
  18914. \label{sec:gradual-type-check}
  18915. We begin by discussing the type checking of a partially typed variant
  18916. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18917. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18918. statically typed, so there is nothing special happening there with
  18919. respect to type checking. On the other hand, the \code{inc} function
  18920. does not have type annotations, so the type checker assigns the type
  18921. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18922. \code{+} operator inside \code{inc}. It expects both arguments to have
  18923. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18924. a gradually typed language, such differences are allowed so long as
  18925. the types are \emph{consistent}; that is, they are equal except in
  18926. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18927. is consistent with every other type. Figure~\ref{fig:consistent}
  18928. shows the definition of the
  18929. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18930. %
  18931. So the type checker allows the \code{+} operator to be applied
  18932. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18933. %
  18934. Next consider the call to the \code{map} function shown in
  18935. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18936. tuple. The \code{inc} function has type
  18937. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18938. but parameter \code{f} of \code{map} has type
  18939. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18940. The type checker for \LangGrad{} accepts this call because the two types are
  18941. consistent.
  18942. \begin{figure}[hbtp]
  18943. % gradual_test_9.rkt
  18944. \begin{tcolorbox}[colback=white]
  18945. {\if\edition\racketEd
  18946. \begin{lstlisting}
  18947. (define (map [f : (Integer -> Integer)]
  18948. [v : (Vector Integer Integer)])
  18949. : (Vector Integer Integer)
  18950. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18951. (define (inc x) (+ x 1))
  18952. (vector-ref (map inc (vector 0 41)) 1)
  18953. \end{lstlisting}
  18954. \fi}
  18955. {\if\edition\pythonEd\pythonColor
  18956. \begin{lstlisting}
  18957. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18958. return f(v[0]), f(v[1])
  18959. def inc(x):
  18960. return x + 1
  18961. t = map(inc, (0, 41))
  18962. print(t[1])
  18963. \end{lstlisting}
  18964. \fi}
  18965. \end{tcolorbox}
  18966. \caption{A partially typed version of the \code{map} example.}
  18967. \label{fig:gradual-map}
  18968. \end{figure}
  18969. \begin{figure}[tbp]
  18970. \begin{tcolorbox}[colback=white]
  18971. {\if\edition\racketEd
  18972. \begin{lstlisting}
  18973. (define/public (consistent? t1 t2)
  18974. (match* (t1 t2)
  18975. [('Integer 'Integer) #t]
  18976. [('Boolean 'Boolean) #t]
  18977. [('Void 'Void) #t]
  18978. [('Any t2) #t]
  18979. [(t1 'Any) #t]
  18980. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18981. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18982. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18983. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18984. (consistent? rt1 rt2))]
  18985. [(other wise) #f]))
  18986. \end{lstlisting}
  18987. \fi}
  18988. {\if\edition\pythonEd\pythonColor
  18989. \begin{lstlisting}
  18990. def consistent(self, t1, t2):
  18991. match (t1, t2):
  18992. case (AnyType(), _):
  18993. return True
  18994. case (_, AnyType()):
  18995. return True
  18996. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18997. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18998. case (TupleType(ts1), TupleType(ts2)):
  18999. return all(map(self.consistent, ts1, ts2))
  19000. case (_, _):
  19001. return t1 == t2
  19002. \end{lstlisting}
  19003. \fi}
  19004. \vspace{-5pt}
  19005. \end{tcolorbox}
  19006. \caption{The consistency method on types.}
  19007. \label{fig:consistent}
  19008. \end{figure}
  19009. It is also helpful to consider how gradual typing handles programs with an
  19010. error, such as applying \code{map} to a function that sometimes
  19011. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  19012. type checker for \LangGrad{} accepts this program because the type of
  19013. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  19014. \code{map}; that is,
  19015. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  19016. is consistent with
  19017. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19018. One might say that a gradual type checker is optimistic in that it
  19019. accepts programs that might execute without a runtime type error.
  19020. %
  19021. The definition of the type checker for \LangGrad{} is shown in
  19022. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  19023. and \ref{fig:type-check-Lgradual-3}.
  19024. %% \begin{figure}[tp]
  19025. %% \centering
  19026. %% \fbox{
  19027. %% \begin{minipage}{0.96\textwidth}
  19028. %% \small
  19029. %% \[
  19030. %% \begin{array}{lcl}
  19031. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  19032. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  19033. %% \end{array}
  19034. %% \]
  19035. %% \end{minipage}
  19036. %% }
  19037. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  19038. %% \label{fig:Lgrad-prime-syntax}
  19039. %% \end{figure}
  19040. \begin{figure}[tbp]
  19041. \begin{tcolorbox}[colback=white]
  19042. {\if\edition\racketEd
  19043. \begin{lstlisting}
  19044. (define (map [f : (Integer -> Integer)]
  19045. [v : (Vector Integer Integer)])
  19046. : (Vector Integer Integer)
  19047. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19048. (define (inc x) (+ x 1))
  19049. (define (true) #t)
  19050. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  19051. (vector-ref (map maybe_inc (vector 0 41)) 0)
  19052. \end{lstlisting}
  19053. \fi}
  19054. {\if\edition\pythonEd\pythonColor
  19055. \begin{lstlisting}
  19056. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19057. return f(v[0]), f(v[1])
  19058. def inc(x):
  19059. return x + 1
  19060. def true():
  19061. return True
  19062. def maybe_inc(x):
  19063. return inc(x) if input_int() == 0 else true()
  19064. t = map(maybe_inc, (0, 41))
  19065. print(t[1])
  19066. \end{lstlisting}
  19067. \fi}
  19068. \vspace{-5pt}
  19069. \end{tcolorbox}
  19070. \caption{A variant of the \code{map} example with an error.}
  19071. \label{fig:map-maybe_inc}
  19072. \end{figure}
  19073. Running this program with input \code{1} triggers an
  19074. error when the \code{maybe\_inc} function returns
  19075. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19076. performs checking at runtime to ensure the integrity of the static
  19077. types, such as the
  19078. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19079. annotation on
  19080. parameter \code{f} of \code{map}.
  19081. Here we give a preview of how the runtime checking is accomplished;
  19082. the following sections provide the details.
  19083. The runtime checking is carried out by a new \code{Cast} AST node that
  19084. is generated in a new pass named \code{cast\_insert}. The output of
  19085. \code{cast\_insert} is a program in the \LangCast{} language, which
  19086. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19087. %
  19088. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19089. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19090. inserted every time the type checker encounters two types that are
  19091. consistent but not equal. In the \code{inc} function, \code{x} is
  19092. cast to \INTTY{} and the result of the \code{+} is cast to
  19093. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19094. is cast from
  19095. \racket{\code{(Any -> Any)}}
  19096. \python{\code{Callable[[Any], Any]}}
  19097. to
  19098. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19099. %
  19100. In the next section we see how to interpret the \code{Cast} node.
  19101. \begin{figure}[btp]
  19102. \begin{tcolorbox}[colback=white]
  19103. {\if\edition\racketEd
  19104. \begin{lstlisting}
  19105. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19106. : (Vector Integer Integer)
  19107. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19108. (define (inc [x : Any]) : Any
  19109. (cast (+ (cast x Any Integer) 1) Integer Any))
  19110. (define (true) : Any (cast #t Boolean Any))
  19111. (define (maybe_inc [x : Any]) : Any
  19112. (if (eq? 0 (read)) (inc x) (true)))
  19113. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19114. (vector 0 41)) 0)
  19115. \end{lstlisting}
  19116. \fi}
  19117. {\if\edition\pythonEd\pythonColor
  19118. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19119. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19120. return f(v[0]), f(v[1])
  19121. def inc(x : Any) -> Any:
  19122. return Cast(Cast(x, Any, int) + 1, int, Any)
  19123. def true() -> Any:
  19124. return Cast(True, bool, Any)
  19125. def maybe_inc(x : Any) -> Any:
  19126. return inc(x) if input_int() == 0 else true()
  19127. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19128. (0, 41))
  19129. print(t[1])
  19130. \end{lstlisting}
  19131. \fi}
  19132. \vspace{-5pt}
  19133. \end{tcolorbox}
  19134. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19135. and \code{maybe\_inc} example.}
  19136. \label{fig:map-cast}
  19137. \end{figure}
  19138. {\if\edition\pythonEd\pythonColor
  19139. \begin{figure}[tbp]
  19140. \begin{tcolorbox}[colback=white]
  19141. \begin{lstlisting}
  19142. class TypeCheckLgrad(TypeCheckLlambda):
  19143. def type_check_exp(self, e, env) -> Type:
  19144. match e:
  19145. case Name(id):
  19146. return env[id]
  19147. case Constant(value) if isinstance(value, bool):
  19148. return BoolType()
  19149. case Constant(value) if isinstance(value, int):
  19150. return IntType()
  19151. case Call(Name('input_int'), []):
  19152. return IntType()
  19153. case BinOp(left, op, right):
  19154. left_type = self.type_check_exp(left, env)
  19155. self.check_consistent(left_type, IntType(), left)
  19156. right_type = self.type_check_exp(right, env)
  19157. self.check_consistent(right_type, IntType(), right)
  19158. return IntType()
  19159. case IfExp(test, body, orelse):
  19160. test_t = self.type_check_exp(test, env)
  19161. self.check_consistent(test_t, BoolType(), test)
  19162. body_t = self.type_check_exp(body, env)
  19163. orelse_t = self.type_check_exp(orelse, env)
  19164. self.check_consistent(body_t, orelse_t, e)
  19165. return self.join_types(body_t, orelse_t)
  19166. case Call(func, args):
  19167. func_t = self.type_check_exp(func, env)
  19168. args_t = [self.type_check_exp(arg, env) for arg in args]
  19169. match func_t:
  19170. case FunctionType(params_t, return_t) \
  19171. if len(params_t) == len(args_t):
  19172. for (arg_t, param_t) in zip(args_t, params_t):
  19173. self.check_consistent(param_t, arg_t, e)
  19174. return return_t
  19175. case AnyType():
  19176. return AnyType()
  19177. case _:
  19178. raise Exception('type_check_exp: in call, unexpected '
  19179. + repr(func_t))
  19180. ...
  19181. case _:
  19182. raise Exception('type_check_exp: unexpected ' + repr(e))
  19183. \end{lstlisting}
  19184. \end{tcolorbox}
  19185. \caption{Type checking expressions in the \LangGrad{} language.}
  19186. \label{fig:type-check-Lgradual-1}
  19187. \end{figure}
  19188. \begin{figure}[tbp]
  19189. \begin{tcolorbox}[colback=white]
  19190. \begin{lstlisting}
  19191. def check_exp(self, e, expected_ty, env):
  19192. match e:
  19193. case Lambda(params, body):
  19194. match expected_ty:
  19195. case FunctionType(params_t, return_t):
  19196. new_env = env.copy().update(zip(params, params_t))
  19197. e.has_type = expected_ty
  19198. body_ty = self.type_check_exp(body, new_env)
  19199. self.check_consistent(body_ty, return_t)
  19200. case AnyType():
  19201. new_env = env.copy().update((p, AnyType()) for p in params)
  19202. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19203. body_ty = self.type_check_exp(body, new_env)
  19204. case _:
  19205. raise Exception('lambda is not of type ' + str(expected_ty))
  19206. case _:
  19207. e_ty = self.type_check_exp(e, env)
  19208. self.check_consistent(e_ty, expected_ty, e)
  19209. \end{lstlisting}
  19210. \end{tcolorbox}
  19211. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19212. \label{fig:type-check-Lgradual-2}
  19213. \end{figure}
  19214. \begin{figure}[tbp]
  19215. \begin{tcolorbox}[colback=white]
  19216. \begin{lstlisting}
  19217. def type_check_stmt(self, s, env, return_type):
  19218. match s:
  19219. case Assign([Name(id)], value):
  19220. value_ty = self.type_check_exp(value, env)
  19221. if id in env:
  19222. self.check_consistent(env[id], value_ty, value)
  19223. else:
  19224. env[id] = value_ty
  19225. ...
  19226. case _:
  19227. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19228. def type_check_stmts(self, ss, env, return_type):
  19229. for s in ss:
  19230. self.type_check_stmt(s, env, return_type)
  19231. \end{lstlisting}
  19232. \end{tcolorbox}
  19233. \caption{Type checking statements in the \LangGrad{} language.}
  19234. \label{fig:type-check-Lgradual-3}
  19235. \end{figure}
  19236. \clearpage
  19237. \begin{figure}[tbp]
  19238. \begin{tcolorbox}[colback=white]
  19239. \begin{lstlisting}
  19240. def join_types(self, t1, t2):
  19241. match (t1, t2):
  19242. case (AnyType(), _):
  19243. return t2
  19244. case (_, AnyType()):
  19245. return t1
  19246. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19247. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19248. self.join_types(rt1,rt2))
  19249. case (TupleType(ts1), TupleType(ts2)):
  19250. return TupleType(list(map(self.join_types, ts1, ts2)))
  19251. case (_, _):
  19252. return t1
  19253. def check_consistent(self, t1, t2, e):
  19254. if not self.consistent(t1, t2):
  19255. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19256. + repr(t2) + ' in ' + repr(e))
  19257. \end{lstlisting}
  19258. \end{tcolorbox}
  19259. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19260. \label{fig:type-check-Lgradual-aux}
  19261. \end{figure}
  19262. \fi}
  19263. {\if\edition\racketEd
  19264. \begin{figure}[tbp]
  19265. \begin{tcolorbox}[colback=white]
  19266. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19267. (define/override (type-check-exp env)
  19268. (lambda (e)
  19269. (define recur (type-check-exp env))
  19270. (match e
  19271. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19272. (define-values (new-es ts)
  19273. (for/lists (exprs types) ([e es])
  19274. (recur e)))
  19275. (define t-ret (type-check-op op ts e))
  19276. (values (Prim op new-es) t-ret)]
  19277. [(Prim 'eq? (list e1 e2))
  19278. (define-values (e1^ t1) (recur e1))
  19279. (define-values (e2^ t2) (recur e2))
  19280. (check-consistent? t1 t2 e)
  19281. (define T (meet t1 t2))
  19282. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19283. [(Prim 'and (list e1 e2))
  19284. (recur (If e1 e2 (Bool #f)))]
  19285. [(Prim 'or (list e1 e2))
  19286. (define tmp (gensym 'tmp))
  19287. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19288. [(If e1 e2 e3)
  19289. (define-values (e1^ T1) (recur e1))
  19290. (define-values (e2^ T2) (recur e2))
  19291. (define-values (e3^ T3) (recur e3))
  19292. (check-consistent? T1 'Boolean e)
  19293. (check-consistent? T2 T3 e)
  19294. (define Tif (meet T2 T3))
  19295. (values (If e1^ e2^ e3^) Tif)]
  19296. [(SetBang x e1)
  19297. (define-values (e1^ T1) (recur e1))
  19298. (define varT (dict-ref env x))
  19299. (check-consistent? T1 varT e)
  19300. (values (SetBang x e1^) 'Void)]
  19301. [(WhileLoop e1 e2)
  19302. (define-values (e1^ T1) (recur e1))
  19303. (check-consistent? T1 'Boolean e)
  19304. (define-values (e2^ T2) ((type-check-exp env) e2))
  19305. (values (WhileLoop e1^ e2^) 'Void)]
  19306. [(Prim 'vector-length (list e1))
  19307. (define-values (e1^ t) (recur e1))
  19308. (match t
  19309. [`(Vector ,ts ...)
  19310. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19311. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19312. \end{lstlisting}
  19313. \end{tcolorbox}
  19314. \caption{Type checker for the \LangGrad{} language, part 1.}
  19315. \label{fig:type-check-Lgradual-1}
  19316. \end{figure}
  19317. \begin{figure}[tbp]
  19318. \begin{tcolorbox}[colback=white]
  19319. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19320. [(Prim 'vector-ref (list e1 e2))
  19321. (define-values (e1^ t1) (recur e1))
  19322. (define-values (e2^ t2) (recur e2))
  19323. (check-consistent? t2 'Integer e)
  19324. (match t1
  19325. [`(Vector ,ts ...)
  19326. (match e2^
  19327. [(Int i)
  19328. (unless (and (0 . <= . i) (i . < . (length ts)))
  19329. (error 'type-check "invalid index ~a in ~a" i e))
  19330. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19331. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19332. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19333. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19334. [(Prim 'vector-set! (list e1 e2 e3) )
  19335. (define-values (e1^ t1) (recur e1))
  19336. (define-values (e2^ t2) (recur e2))
  19337. (define-values (e3^ t3) (recur e3))
  19338. (check-consistent? t2 'Integer e)
  19339. (match t1
  19340. [`(Vector ,ts ...)
  19341. (match e2^
  19342. [(Int i)
  19343. (unless (and (0 . <= . i) (i . < . (length ts)))
  19344. (error 'type-check "invalid index ~a in ~a" i e))
  19345. (check-consistent? (list-ref ts i) t3 e)
  19346. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19347. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19348. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19349. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19350. [(Apply e1 e2s)
  19351. (define-values (e1^ T1) (recur e1))
  19352. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19353. (match T1
  19354. [`(,T1ps ... -> ,T1rt)
  19355. (for ([T2 T2s] [Tp T1ps])
  19356. (check-consistent? T2 Tp e))
  19357. (values (Apply e1^ e2s^) T1rt)]
  19358. [`Any (values (Apply e1^ e2s^) 'Any)]
  19359. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19360. [(Lambda params Tr e1)
  19361. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19362. (match p
  19363. [`[,x : ,T] (values x T)]
  19364. [(? symbol? x) (values x 'Any)])))
  19365. (define-values (e1^ T1)
  19366. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19367. (check-consistent? Tr T1 e)
  19368. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19369. `(,@Ts -> ,Tr))]
  19370. [else ((super type-check-exp env) e)]
  19371. )))
  19372. \end{lstlisting}
  19373. \end{tcolorbox}
  19374. \caption{Type checker for the \LangGrad{} language, part 2.}
  19375. \label{fig:type-check-Lgradual-2}
  19376. \end{figure}
  19377. \begin{figure}[tbp]
  19378. \begin{tcolorbox}[colback=white]
  19379. \begin{lstlisting}
  19380. (define/override (type-check-def env)
  19381. (lambda (e)
  19382. (match e
  19383. [(Def f params rt info body)
  19384. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19385. (match p
  19386. [`[,x : ,T] (values x T)]
  19387. [(? symbol? x) (values x 'Any)])))
  19388. (define new-env (append (map cons xs ps) env))
  19389. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19390. (check-consistent? ty^ rt e)
  19391. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19392. [else (error 'type-check "ill-formed function definition ~a" e)]
  19393. )))
  19394. (define/override (type-check-program e)
  19395. (match e
  19396. [(Program info body)
  19397. (define-values (body^ ty) ((type-check-exp '()) body))
  19398. (check-consistent? ty 'Integer e)
  19399. (ProgramDefsExp info '() body^)]
  19400. [(ProgramDefsExp info ds body)
  19401. (define new-env (for/list ([d ds])
  19402. (cons (Def-name d) (fun-def-type d))))
  19403. (define ds^ (for/list ([d ds])
  19404. ((type-check-def new-env) d)))
  19405. (define-values (body^ ty) ((type-check-exp new-env) body))
  19406. (check-consistent? ty 'Integer e)
  19407. (ProgramDefsExp info ds^ body^)]
  19408. [else (super type-check-program e)]))
  19409. \end{lstlisting}
  19410. \end{tcolorbox}
  19411. \caption{Type checker for the \LangGrad{} language, part 3.}
  19412. \label{fig:type-check-Lgradual-3}
  19413. \end{figure}
  19414. \begin{figure}[tbp]
  19415. \begin{tcolorbox}[colback=white]
  19416. \begin{lstlisting}
  19417. (define/public (join t1 t2)
  19418. (match* (t1 t2)
  19419. [('Integer 'Integer) 'Integer]
  19420. [('Boolean 'Boolean) 'Boolean]
  19421. [('Void 'Void) 'Void]
  19422. [('Any t2) t2]
  19423. [(t1 'Any) t1]
  19424. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19425. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19426. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19427. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19428. -> ,(join rt1 rt2))]))
  19429. (define/public (meet t1 t2)
  19430. (match* (t1 t2)
  19431. [('Integer 'Integer) 'Integer]
  19432. [('Boolean 'Boolean) 'Boolean]
  19433. [('Void 'Void) 'Void]
  19434. [('Any t2) 'Any]
  19435. [(t1 'Any) 'Any]
  19436. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19437. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19438. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19439. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19440. -> ,(meet rt1 rt2))]))
  19441. (define/public (check-consistent? t1 t2 e)
  19442. (unless (consistent? t1 t2)
  19443. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19444. (define explicit-prim-ops
  19445. (set-union
  19446. (type-predicates)
  19447. (set 'procedure-arity 'eq? 'not 'and 'or
  19448. 'vector 'vector-length 'vector-ref 'vector-set!
  19449. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19450. (define/override (fun-def-type d)
  19451. (match d
  19452. [(Def f params rt info body)
  19453. (define ps
  19454. (for/list ([p params])
  19455. (match p
  19456. [`[,x : ,T] T]
  19457. [(? symbol?) 'Any]
  19458. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19459. `(,@ps -> ,rt)]
  19460. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19461. \end{lstlisting}
  19462. \end{tcolorbox}
  19463. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19464. \label{fig:type-check-Lgradual-aux}
  19465. \end{figure}
  19466. \fi}
  19467. \section{Interpreting \LangCast{} }
  19468. \label{sec:interp-casts}
  19469. The runtime behavior of casts involving simple types such as
  19470. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19471. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19472. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19473. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19474. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19475. operator, by checking the value's tag and either retrieving
  19476. the underlying integer or signaling an error if the tag is not the
  19477. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19478. %
  19479. Things get more interesting with casts involving
  19480. \racket{function and tuple types}\python{function, tuple, and array types}.
  19481. Consider the cast of the function \code{maybe\_inc} from
  19482. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19483. to
  19484. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19485. shown in figure~\ref{fig:map-maybe_inc}.
  19486. When the \code{maybe\_inc} function flows through
  19487. this cast at runtime, we don't know whether it will return
  19488. an integer, because that depends on the input from the user.
  19489. The \LangCast{} interpreter therefore delays the checking
  19490. of the cast until the function is applied. To do so it
  19491. wraps \code{maybe\_inc} in a new function that casts its parameter
  19492. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19493. casts the return value from \CANYTY{} to \INTTY{}.
  19494. {\if\edition\pythonEd\pythonColor
  19495. %
  19496. There are further complications regarding casts on mutable data,
  19497. such as the \code{list} type introduced in
  19498. the challenge assignment of section~\ref{sec:arrays}.
  19499. %
  19500. \fi}
  19501. %
  19502. Consider the example presented in figure~\ref{fig:map-bang} that
  19503. defines a partially typed version of \code{map} whose parameter
  19504. \code{v} has type
  19505. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19506. and that updates \code{v} in place
  19507. instead of returning a new tuple. We name this function
  19508. \code{map\_inplace}. We apply \code{map\_inplace} to
  19509. \racket{a tuple}\python{an array} of integers, so the type checker
  19510. inserts a cast from
  19511. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19512. to
  19513. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19514. A naive way for the \LangCast{} interpreter to cast between
  19515. \racket{tuple}\python{array} types would be to build a new
  19516. \racket{tuple}\python{array} whose elements are the result
  19517. of casting each of the original elements to the target
  19518. type. However, this approach is not valid for mutable data structures.
  19519. In the example of figure~\ref{fig:map-bang},
  19520. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19521. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19522. the original one.
  19523. Instead the interpreter needs to create a new kind of value, a
  19524. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19525. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19526. and then applies a
  19527. cast to the resulting value. On a write, the proxy casts the argument
  19528. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19529. \racket{
  19530. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19531. \code{0} from \INTTY{} to \CANYTY{}.
  19532. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19533. from \CANYTY{} to \INTTY{}.
  19534. }
  19535. \python{
  19536. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19537. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19538. For the subscript on the left of the assignment,
  19539. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19540. }
  19541. Finally we consider casts between the \CANYTY{} type and higher-order types
  19542. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19543. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19544. have a type annotation, so it is given type \CANYTY{}. In the call to
  19545. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19546. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19547. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19548. \code{Inject}, but that doesn't work because
  19549. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19550. a flat type. Instead, we must first cast to
  19551. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19552. and then inject to \CANYTY{}.
  19553. \begin{figure}[tbp]
  19554. \begin{tcolorbox}[colback=white]
  19555. % gradual_test_11.rkt
  19556. {\if\edition\racketEd
  19557. \begin{lstlisting}
  19558. (define (map_inplace [f : (Any -> Any)]
  19559. [v : (Vector Any Any)]) : Void
  19560. (begin
  19561. (vector-set! v 0 (f (vector-ref v 0)))
  19562. (vector-set! v 1 (f (vector-ref v 1)))))
  19563. (define (inc x) (+ x 1))
  19564. (let ([v (vector 0 41)])
  19565. (begin (map_inplace inc v) (vector-ref v 1)))
  19566. \end{lstlisting}
  19567. \fi}
  19568. {\if\edition\pythonEd\pythonColor
  19569. \begin{lstlisting}
  19570. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19571. i = 0
  19572. while i != len(v):
  19573. v[i] = f(v[i])
  19574. i = i + 1
  19575. def inc(x : int) -> int:
  19576. return x + 1
  19577. v = [0, 41]
  19578. map_inplace(inc, v)
  19579. print(v[1])
  19580. \end{lstlisting}
  19581. \fi}
  19582. \end{tcolorbox}
  19583. \caption{An example involving casts on arrays.}
  19584. \label{fig:map-bang}
  19585. \end{figure}
  19586. \begin{figure}[btp]
  19587. \begin{tcolorbox}[colback=white]
  19588. {\if\edition\racketEd
  19589. \begin{lstlisting}
  19590. (define (map_inplace [f : (Any -> Any)] v) : Void
  19591. (begin
  19592. (vector-set! v 0 (f (vector-ref v 0)))
  19593. (vector-set! v 1 (f (vector-ref v 1)))))
  19594. (define (inc x) (+ x 1))
  19595. (let ([v (vector 0 41)])
  19596. (begin (map_inplace inc v) (vector-ref v 1)))
  19597. \end{lstlisting}
  19598. \fi}
  19599. {\if\edition\pythonEd\pythonColor
  19600. \begin{lstlisting}
  19601. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19602. i = 0
  19603. while i != len(v):
  19604. v[i] = f(v[i])
  19605. i = i + 1
  19606. def inc(x):
  19607. return x + 1
  19608. v = [0, 41]
  19609. map_inplace(inc, v)
  19610. print(v[1])
  19611. \end{lstlisting}
  19612. \fi}
  19613. \end{tcolorbox}
  19614. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19615. \label{fig:map-any}
  19616. \end{figure}
  19617. \begin{figure}[tbp]
  19618. \begin{tcolorbox}[colback=white]
  19619. {\if\edition\racketEd
  19620. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19621. (define/public (apply_cast v s t)
  19622. (match* (s t)
  19623. [(t1 t2) #:when (equal? t1 t2) v]
  19624. [('Any t2)
  19625. (match t2
  19626. [`(,ts ... -> ,rt)
  19627. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19628. (define v^ (apply-project v any->any))
  19629. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19630. [`(Vector ,ts ...)
  19631. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19632. (define v^ (apply-project v vec-any))
  19633. (apply_cast v^ vec-any `(Vector ,@ts))]
  19634. [else (apply-project v t2)])]
  19635. [(t1 'Any)
  19636. (match t1
  19637. [`(,ts ... -> ,rt)
  19638. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19639. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19640. (apply-inject v^ (any-tag any->any))]
  19641. [`(Vector ,ts ...)
  19642. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19643. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19644. (apply-inject v^ (any-tag vec-any))]
  19645. [else (apply-inject v (any-tag t1))])]
  19646. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19647. (define x (gensym 'x))
  19648. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19649. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19650. (define cast-writes
  19651. (for/list ([t1 ts1] [t2 ts2])
  19652. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19653. `(vector-proxy ,(vector v (apply vector cast-reads)
  19654. (apply vector cast-writes)))]
  19655. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19656. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19657. `(function ,xs ,(Cast
  19658. (Apply (Value v)
  19659. (for/list ([x xs][t1 ts1][t2 ts2])
  19660. (Cast (Var x) t2 t1)))
  19661. rt1 rt2) ())]
  19662. ))
  19663. \end{lstlisting}
  19664. \fi}
  19665. {\if\edition\pythonEd\pythonColor
  19666. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19667. def apply_cast(self, value, src, tgt):
  19668. match (src, tgt):
  19669. case (AnyType(), FunctionType(ps2, rt2)):
  19670. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19671. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19672. case (AnyType(), TupleType(ts2)):
  19673. anytup = TupleType([AnyType() for t1 in ts2])
  19674. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19675. case (AnyType(), ListType(t2)):
  19676. anylist = ListType([AnyType() for t1 in ts2])
  19677. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19678. case (AnyType(), AnyType()):
  19679. return value
  19680. case (AnyType(), _):
  19681. return self.apply_project(value, tgt)
  19682. case (FunctionType(ps1,rt1), AnyType()):
  19683. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19684. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19685. case (TupleType(ts1), AnyType()):
  19686. anytup = TupleType([AnyType() for t1 in ts1])
  19687. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19688. case (ListType(t1), AnyType()):
  19689. anylist = ListType(AnyType())
  19690. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19691. case (_, AnyType()):
  19692. return self.apply_inject(value, src)
  19693. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19694. params = [generate_name('x') for p in ps2]
  19695. args = [Cast(Name(x), t2, t1)
  19696. for (x,t1,t2) in zip(params, ps1, ps2)]
  19697. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19698. return Function('cast', params, [Return(body)], {})
  19699. case (TupleType(ts1), TupleType(ts2)):
  19700. x = generate_name('x')
  19701. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19702. for (t1,t2) in zip(ts1,ts2)]
  19703. return ProxiedTuple(value, reads)
  19704. case (ListType(t1), ListType(t2)):
  19705. x = generate_name('x')
  19706. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19707. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19708. return ProxiedList(value, read, write)
  19709. case (t1, t2) if t1 == t2:
  19710. return value
  19711. case (t1, t2):
  19712. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19713. def apply_inject(self, value, src):
  19714. return Tagged(value, self.type_to_tag(src))
  19715. def apply_project(self, value, tgt):
  19716. match value:
  19717. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19718. return val
  19719. case _:
  19720. raise Exception('apply_project, unexpected ' + repr(value))
  19721. \end{lstlisting}
  19722. \fi}
  19723. \end{tcolorbox}
  19724. \caption{The \code{apply\_cast} auxiliary method.}
  19725. \label{fig:apply_cast}
  19726. \end{figure}
  19727. The \LangCast{} interpreter uses an auxiliary function named
  19728. \code{apply\_cast} to cast a value from a source type to a target type,
  19729. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19730. the kinds of casts that we've discussed in this section.
  19731. %
  19732. The definition of the interpreter for \LangCast{} is shown in
  19733. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19734. dispatching to \code{apply\_cast}.
  19735. \racket{To handle the addition of tuple
  19736. proxies, we update the tuple primitives in \code{interp-op} using the
  19737. functions given in figure~\ref{fig:guarded-tuple}.}
  19738. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19739. \begin{figure}[tbp]
  19740. \begin{tcolorbox}[colback=white]
  19741. {\if\edition\racketEd
  19742. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19743. (define interp-Lcast-class
  19744. (class interp-Llambda-class
  19745. (super-new)
  19746. (inherit apply-fun apply-inject apply-project)
  19747. (define/override (interp-op op)
  19748. (match op
  19749. ['vector-length guarded-vector-length]
  19750. ['vector-ref guarded-vector-ref]
  19751. ['vector-set! guarded-vector-set!]
  19752. ['any-vector-ref (lambda (v i)
  19753. (match v [`(tagged ,v^ ,tg)
  19754. (guarded-vector-ref v^ i)]))]
  19755. ['any-vector-set! (lambda (v i a)
  19756. (match v [`(tagged ,v^ ,tg)
  19757. (guarded-vector-set! v^ i a)]))]
  19758. ['any-vector-length (lambda (v)
  19759. (match v [`(tagged ,v^ ,tg)
  19760. (guarded-vector-length v^)]))]
  19761. [else (super interp-op op)]
  19762. ))
  19763. (define/override ((interp-exp env) e)
  19764. (define (recur e) ((interp-exp env) e))
  19765. (match e
  19766. [(Value v) v]
  19767. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19768. [else ((super interp-exp env) e)]))
  19769. ))
  19770. (define (interp-Lcast p)
  19771. (send (new interp-Lcast-class) interp-program p))
  19772. \end{lstlisting}
  19773. \fi}
  19774. {\if\edition\pythonEd\pythonColor
  19775. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19776. class InterpLcast(InterpLany):
  19777. def interp_exp(self, e, env):
  19778. match e:
  19779. case Cast(value, src, tgt):
  19780. v = self.interp_exp(value, env)
  19781. return self.apply_cast(v, src, tgt)
  19782. case ValueExp(value):
  19783. return value
  19784. ...
  19785. case _:
  19786. return super().interp_exp(e, env)
  19787. \end{lstlisting}
  19788. \fi}
  19789. \end{tcolorbox}
  19790. \caption{The interpreter for \LangCast{}.}
  19791. \label{fig:interp-Lcast}
  19792. \end{figure}
  19793. {\if\edition\racketEd
  19794. \begin{figure}[tbp]
  19795. \begin{tcolorbox}[colback=white]
  19796. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19797. (define (guarded-vector-ref vec i)
  19798. (match vec
  19799. [`(vector-proxy ,proxy)
  19800. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19801. (define rd (vector-ref (vector-ref proxy 1) i))
  19802. (apply-fun rd (list val) 'guarded-vector-ref)]
  19803. [else (vector-ref vec i)]))
  19804. (define (guarded-vector-set! vec i arg)
  19805. (match vec
  19806. [`(vector-proxy ,proxy)
  19807. (define wr (vector-ref (vector-ref proxy 2) i))
  19808. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19809. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19810. [else (vector-set! vec i arg)]))
  19811. (define (guarded-vector-length vec)
  19812. (match vec
  19813. [`(vector-proxy ,proxy)
  19814. (guarded-vector-length (vector-ref proxy 0))]
  19815. [else (vector-length vec)]))
  19816. \end{lstlisting}
  19817. %% {\if\edition\pythonEd\pythonColor
  19818. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19819. %% UNDER CONSTRUCTION
  19820. %% \end{lstlisting}
  19821. %% \fi}
  19822. \end{tcolorbox}
  19823. \caption{The \code{guarded-vector} auxiliary functions.}
  19824. \label{fig:guarded-tuple}
  19825. \end{figure}
  19826. \fi}
  19827. {\if\edition\pythonEd\pythonColor
  19828. \section{Overload Resolution }
  19829. \label{sec:gradual-resolution}
  19830. Recall that when we added support for arrays in
  19831. section~\ref{sec:arrays}, the syntax for the array operations were the
  19832. same as for tuple operations (for example, accessing an element and
  19833. getting the length). So we performed overload resolution, with a pass
  19834. named \code{resolve}, to separate the array and tuple operations. In
  19835. particular, we introduced the primitives \code{array\_load},
  19836. \code{array\_store}, and \code{array\_len}.
  19837. For gradual typing, we further overload these operators to work on
  19838. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19839. updated with new cases for the \CANYTY{} type, translating the element
  19840. access and length operations to the primitives \code{any\_load},
  19841. \code{any\_store}, and \code{any\_len}.
  19842. \fi}
  19843. \section{Cast Insertion }
  19844. \label{sec:gradual-insert-casts}
  19845. In our discussion of type checking of \LangGrad{}, we mentioned how
  19846. the runtime aspect of type checking is carried out by the \code{Cast}
  19847. AST node, which is added to the program by a new pass named
  19848. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19849. language. We now discuss the details of this pass.
  19850. The \code{cast\_insert} pass is closely related to the type checker
  19851. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19852. In particular, the type checker allows implicit casts between
  19853. consistent types. The job of the \code{cast\_insert} pass is to make
  19854. those casts explicit. It does so by inserting
  19855. \code{Cast} nodes into the AST.
  19856. %
  19857. For the most part, the implicit casts occur in places where the type
  19858. checker checks two types for consistency. Consider the case for
  19859. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19860. checker requires that the type of the left operand is consistent with
  19861. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19862. \code{Cast} around the left operand, converting from its type to
  19863. \INTTY{}. The story is similar for the right operand. It is not always
  19864. necessary to insert a cast, for example, if the left operand already has type
  19865. \INTTY{} then there is no need for a \code{Cast}.
  19866. Some of the implicit casts are not as straightforward. One such case
  19867. arises with the
  19868. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19869. see that the type checker requires that the two branches have
  19870. consistent types and that type of the conditional expression is the
  19871. meet of the branches' types. In the target language \LangCast{}, both
  19872. branches will need to have the same type, and that type
  19873. will be the type of the conditional expression. Thus, each branch requires
  19874. a \code{Cast} to convert from its type to the meet of the branches' types.
  19875. The case for the function call exhibits another interesting situation. If
  19876. the function expression is of type \CANYTY{}, then it needs to be cast
  19877. to a function type so that it can be used in a function call in
  19878. \LangCast{}. Which function type should it be cast to? The parameter
  19879. and return types are unknown, so we can simply use \CANYTY{} for all
  19880. of them. Furthermore, in \LangCast{} the argument types will need to
  19881. exactly match the parameter types, so we must cast all the arguments
  19882. to type \CANYTY{} (if they are not already of that type).
  19883. {\if\edition\racketEd
  19884. %
  19885. Likewise, the cases for the tuple operators \code{vector-length},
  19886. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19887. where the tuple expression is of type \CANYTY{}. Instead of
  19888. handling these situations with casts, we recommend translating
  19889. the special-purpose variants of the tuple operators that handle
  19890. tuples of type \CANYTY{}: \code{any-vector-length},
  19891. \code{any-vector-ref}, and \code{any-vector-set!}.
  19892. %
  19893. \fi}
  19894. \section{Lower Casts }
  19895. \label{sec:lower_casts}
  19896. The next step in the journey toward x86 is the \code{lower\_casts}
  19897. pass that translates the casts in \LangCast{} to the lower-level
  19898. \code{Inject} and \code{Project} operators and new operators for
  19899. proxies, extending the \LangLam{} language to \LangProxy{}.
  19900. The \LangProxy{} language can also be described as an extension of
  19901. \LangAny{}, with the addition of proxies. We recommend creating an
  19902. auxiliary function named \code{lower\_cast} that takes an expression
  19903. (in \LangCast{}), a source type, and a target type and translates it
  19904. to an expression in \LangProxy{}.
  19905. The \code{lower\_cast} function can follow a code structure similar to
  19906. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19907. the interpreter for \LangCast{}, because it must handle the same cases
  19908. as \code{apply\_cast} and it needs to mimic the behavior of
  19909. \code{apply\_cast}. The most interesting cases concern
  19910. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19911. {\if\edition\racketEd
  19912. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19913. type to another tuple type is accomplished by creating a proxy that
  19914. intercepts the operations on the underlying tuple. Here we make the
  19915. creation of the proxy explicit with the \code{vector-proxy} AST
  19916. node. It takes three arguments: the first is an expression for the
  19917. tuple, the second is a tuple of functions for casting an element that is
  19918. being read from the tuple, and the third is a tuple of functions for
  19919. casting an element that is being written to the array. You can create
  19920. the functions for reading and writing using lambda expressions. Also,
  19921. as we show in the next section, we need to differentiate these tuples
  19922. of functions from the user-created ones, so we recommend using a new
  19923. AST node named \code{raw-vector} instead of \code{vector}.
  19924. %
  19925. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19926. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19927. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19928. \fi}
  19929. {\if\edition\pythonEd\pythonColor
  19930. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19931. type to another array type is accomplished by creating a proxy that
  19932. intercepts the operations on the underlying array. Here we make the
  19933. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19934. takes fives arguments: the first is an expression for the array, the
  19935. second is a function for casting an element that is being read from
  19936. the array, the third is a function for casting an element that is
  19937. being written to the array, the fourth is the type of the underlying
  19938. array, and the fifth is the type of the proxied array. You can create
  19939. the functions for reading and writing using lambda expressions.
  19940. A cast between two tuple types can be handled in a similar manner. We
  19941. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19942. immutable, so there is no need for a function to cast the value during
  19943. a write. Because there is a separate element type for each slot in
  19944. the tuple, we need more than one function for casting during a read:
  19945. we need a tuple of functions.
  19946. %
  19947. Also, as we show in the next section, we need to differentiate these
  19948. tuples from the user-created ones, so we recommend using a new AST
  19949. node named \code{RawTuple} instead of \code{Tuple} to create the
  19950. tuples of functions.
  19951. %
  19952. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19953. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19954. that involves casting an array of integers to an array of \CANYTY{}.
  19955. \fi}
  19956. \begin{figure}[tbp]
  19957. \begin{tcolorbox}[colback=white]
  19958. {\if\edition\racketEd
  19959. \begin{lstlisting}
  19960. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19961. (begin
  19962. (vector-set! v 0 (f (vector-ref v 0)))
  19963. (vector-set! v 1 (f (vector-ref v 1)))))
  19964. (define (inc [x : Any]) : Any
  19965. (inject (+ (project x Integer) 1) Integer))
  19966. (let ([v (vector 0 41)])
  19967. (begin
  19968. (map_inplace inc (vector-proxy v
  19969. (raw-vector (lambda: ([x9 : Integer]) : Any
  19970. (inject x9 Integer))
  19971. (lambda: ([x9 : Integer]) : Any
  19972. (inject x9 Integer)))
  19973. (raw-vector (lambda: ([x9 : Any]) : Integer
  19974. (project x9 Integer))
  19975. (lambda: ([x9 : Any]) : Integer
  19976. (project x9 Integer)))))
  19977. (vector-ref v 1)))
  19978. \end{lstlisting}
  19979. \fi}
  19980. {\if\edition\pythonEd\pythonColor
  19981. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19982. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19983. i = 0
  19984. while i != array_len(v):
  19985. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19986. i = (i + 1)
  19987. def inc(x : int) -> int:
  19988. return (x + 1)
  19989. def main() -> int:
  19990. v = [0, 41]
  19991. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19992. print(array_load(v, 1))
  19993. return 0
  19994. \end{lstlisting}
  19995. \fi}
  19996. \end{tcolorbox}
  19997. \caption{Output of \code{lower\_casts} on the example shown in
  19998. figure~\ref{fig:map-bang}.}
  19999. \label{fig:map-bang-lower-cast}
  20000. \end{figure}
  20001. A cast from one function type to another function type is accomplished
  20002. by generating a \code{lambda} whose parameter and return types match
  20003. the target function type. The body of the \code{lambda} should cast
  20004. the parameters from the target type to the source type. (Yes,
  20005. backward! Functions are contravariant\index{subject}{contravariant}
  20006. in the parameters.) Afterward, call the underlying function and then
  20007. cast the result from the source return type to the target return type.
  20008. Figure~\ref{fig:map-lower-cast} shows the output of the
  20009. \code{lower\_casts} pass on the \code{map} example given in
  20010. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  20011. call to \code{map} is wrapped in a \code{lambda}.
  20012. \begin{figure}[tbp]
  20013. \begin{tcolorbox}[colback=white]
  20014. {\if\edition\racketEd
  20015. \begin{lstlisting}
  20016. (define (map [f : (Integer -> Integer)]
  20017. [v : (Vector Integer Integer)])
  20018. : (Vector Integer Integer)
  20019. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20020. (define (inc [x : Any]) : Any
  20021. (inject (+ (project x Integer) 1) Integer))
  20022. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  20023. (project (inc (inject x9 Integer)) Integer))
  20024. (vector 0 41)) 1)
  20025. \end{lstlisting}
  20026. \fi}
  20027. {\if\edition\pythonEd\pythonColor
  20028. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20029. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  20030. return (f(v[0]), f(v[1]),)
  20031. def inc(x : any) -> any:
  20032. return inject((project(x, int) + 1), int)
  20033. def main() -> int:
  20034. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  20035. print(t[1])
  20036. return 0
  20037. \end{lstlisting}
  20038. \fi}
  20039. \end{tcolorbox}
  20040. \caption{Output of \code{lower\_casts} on the example shown in
  20041. figure~\ref{fig:gradual-map}.}
  20042. \label{fig:map-lower-cast}
  20043. \end{figure}
  20044. %\pagebreak
  20045. \section{Differentiate Proxies }
  20046. \label{sec:differentiate-proxies}
  20047. So far, the responsibility of differentiating tuples and tuple proxies
  20048. has been the job of the interpreter.
  20049. %
  20050. \racket{For example, the interpreter for \LangCast{} implements
  20051. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  20052. figure~\ref{fig:guarded-tuple}.}
  20053. %
  20054. In the \code{differentiate\_proxies} pass we shift this responsibility
  20055. to the generated code.
  20056. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20057. we used the type \TUPLETYPENAME{} for both
  20058. real tuples and tuple proxies.
  20059. \python{Similarly, we use the type \code{list} for both arrays and
  20060. array proxies.}
  20061. In \LangPVec{} we return the
  20062. \TUPLETYPENAME{} type to its original
  20063. meaning, as the type of just tuples, and we introduce a new type,
  20064. \PTUPLETYNAME{}, whose values
  20065. can be either real tuples or tuple
  20066. proxies.
  20067. %
  20068. {\if\edition\pythonEd\pythonColor
  20069. Likewise, we return the
  20070. \ARRAYTYPENAME{} type to its original
  20071. meaning, as the type of arrays, and we introduce a new type,
  20072. \PARRAYTYNAME{}, whose values
  20073. can be either arrays or array proxies.
  20074. These new types come with a suite of new primitive operations.
  20075. \fi}
  20076. {\if\edition\racketEd
  20077. A tuple proxy is represented by a tuple containing three things: (1) the
  20078. underlying tuple, (2) a tuple of functions for casting elements that
  20079. are read from the tuple, and (3) a tuple of functions for casting
  20080. values to be written to the tuple. So, we define the following
  20081. abbreviation for the type of a tuple proxy:
  20082. \[
  20083. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20084. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20085. \]
  20086. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20087. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20088. %
  20089. Next we describe each of the new primitive operations.
  20090. \begin{description}
  20091. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20092. (\key{PVector} $T \ldots$)]\ \\
  20093. %
  20094. This operation brands a vector as a value of the \code{PVector} type.
  20095. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20096. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20097. %
  20098. This operation brands a vector proxy as value of the \code{PVector} type.
  20099. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20100. \BOOLTY{}] \ \\
  20101. %
  20102. This returns true if the value is a tuple proxy and false if it is a
  20103. real tuple.
  20104. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20105. (\key{Vector} $T \ldots$)]\ \\
  20106. %
  20107. Assuming that the input is a tuple, this operation returns the
  20108. tuple.
  20109. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20110. $\to$ \INTTY{}]\ \\
  20111. %
  20112. Given a tuple proxy, this operation returns the length of the tuple.
  20113. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20114. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20115. %
  20116. Given a tuple proxy, this operation returns the $i$th element of the
  20117. tuple.
  20118. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20119. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20120. Given a tuple proxy, this operation writes a value to the $i$th element
  20121. of the tuple.
  20122. \end{description}
  20123. \fi}
  20124. {\if\edition\pythonEd\pythonColor
  20125. %
  20126. A tuple proxy is represented by a tuple containing (1) the underlying
  20127. tuple and (2) a tuple of functions for casting elements that are read
  20128. from the tuple. The \LangPVec{} language includes the following AST
  20129. classes and primitive functions.
  20130. \begin{description}
  20131. \item[\code{InjectTuple}] \ \\
  20132. %
  20133. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20134. \item[\code{InjectTupleProxy}]\ \\
  20135. %
  20136. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20137. \item[\code{is\_tuple\_proxy}]\ \\
  20138. %
  20139. This primitive returns true if the value is a tuple proxy and false
  20140. if it is a tuple.
  20141. \item[\code{project\_tuple}]\ \\
  20142. %
  20143. Converts a tuple that is branded as \PTUPLETYNAME{}
  20144. back to a tuple.
  20145. \item[\code{proxy\_tuple\_len}]\ \\
  20146. %
  20147. Given a tuple proxy, returns the length of the underlying tuple.
  20148. \item[\code{proxy\_tuple\_load}]\ \\
  20149. %
  20150. Given a tuple proxy, returns the $i$th element of the underlying
  20151. tuple.
  20152. \end{description}
  20153. An array proxy is represented by a tuple containing (1) the underlying
  20154. array, (2) a function for casting elements that are read from the
  20155. array, and (3) a function for casting elements that are written to the
  20156. array. The \LangPVec{} language includes the following AST classes
  20157. and primitive functions.
  20158. \begin{description}
  20159. \item[\code{InjectList}]\ \\
  20160. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20161. \item[\code{InjectListProxy}]\ \\
  20162. %
  20163. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20164. \item[\code{is\_array\_proxy}]\ \\
  20165. %
  20166. Returns true if the value is an array proxy and false if it is an
  20167. array.
  20168. \item[\code{project\_array}]\ \\
  20169. %
  20170. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20171. array.
  20172. \item[\code{proxy\_array\_len}]\ \\
  20173. %
  20174. Given an array proxy, returns the length of the underlying array.
  20175. \item[\code{proxy\_array\_load}]\ \\
  20176. %
  20177. Given an array proxy, returns the $i$th element of the underlying
  20178. array.
  20179. \item[\code{proxy\_array\_store}]\ \\
  20180. %
  20181. Given an array proxy, writes a value to the $i$th element of the
  20182. underlying array.
  20183. \end{description}
  20184. \fi}
  20185. Now we discuss the translation that differentiates tuples and arrays
  20186. from proxies. First, every type annotation in the program is
  20187. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20188. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20189. places. For example, we wrap every tuple creation with an
  20190. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20191. %
  20192. {\if\edition\racketEd
  20193. \begin{minipage}{0.96\textwidth}
  20194. \begin{lstlisting}
  20195. (vector |$e_1 \ldots e_n$|)
  20196. |$\Rightarrow$|
  20197. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20198. \end{lstlisting}
  20199. \end{minipage}
  20200. \fi}
  20201. {\if\edition\pythonEd\pythonColor
  20202. \begin{lstlisting}
  20203. Tuple(|$e_1, \ldots, e_n$|)
  20204. |$\Rightarrow$|
  20205. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20206. \end{lstlisting}
  20207. \fi}
  20208. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20209. AST node that we introduced in the previous
  20210. section does not get injected.
  20211. {\if\edition\racketEd
  20212. \begin{lstlisting}
  20213. (raw-vector |$e_1 \ldots e_n$|)
  20214. |$\Rightarrow$|
  20215. (vector |$e'_1 \ldots e'_n$|)
  20216. \end{lstlisting}
  20217. \fi}
  20218. {\if\edition\pythonEd\pythonColor
  20219. \begin{lstlisting}
  20220. RawTuple(|$e_1, \ldots, e_n$|)
  20221. |$\Rightarrow$|
  20222. Tuple(|$e'_1, \ldots, e'_n$|)
  20223. \end{lstlisting}
  20224. \fi}
  20225. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20226. translates as follows:
  20227. %
  20228. {\if\edition\racketEd
  20229. \begin{lstlisting}
  20230. (vector-proxy |$e_1~e_2~e_3$|)
  20231. |$\Rightarrow$|
  20232. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20233. \end{lstlisting}
  20234. \fi}
  20235. {\if\edition\pythonEd\pythonColor
  20236. \begin{lstlisting}
  20237. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20238. |$\Rightarrow$|
  20239. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20240. \end{lstlisting}
  20241. \fi}
  20242. We translate the element access operations into conditional
  20243. expressions that check whether the value is a proxy and then dispatch
  20244. to either the appropriate proxy tuple operation or the regular tuple
  20245. operation.
  20246. {\if\edition\racketEd
  20247. \begin{lstlisting}
  20248. (vector-ref |$e_1$| |$i$|)
  20249. |$\Rightarrow$|
  20250. (let ([|$v~e_1$|])
  20251. (if (proxy? |$v$|)
  20252. (proxy-vector-ref |$v$| |$i$|)
  20253. (vector-ref (project-vector |$v$|) |$i$|)
  20254. \end{lstlisting}
  20255. \fi}
  20256. %
  20257. Note that in the branch for a tuple, we must apply
  20258. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20259. from the tuple.
  20260. The translation of array operations is similar to the ones for tuples.
  20261. \section{Reveal Casts }
  20262. \label{sec:reveal-casts-gradual}
  20263. {\if\edition\racketEd
  20264. Recall that the \code{reveal\_casts} pass
  20265. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20266. \code{Inject} and \code{Project} into lower-level operations.
  20267. %
  20268. In particular, \code{Project} turns into a conditional expression that
  20269. inspects the tag and retrieves the underlying value. Here we need to
  20270. augment the translation of \code{Project} to handle the situation in which
  20271. the target type is \code{PVector}. Instead of using
  20272. \code{vector-length} we need to use \code{proxy-vector-length}.
  20273. \begin{lstlisting}
  20274. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20275. |$\Rightarrow$|
  20276. (let |$\itm{tmp}$| |$e'$|
  20277. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20278. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20279. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20280. (exit)))
  20281. \end{lstlisting}
  20282. \fi}
  20283. %
  20284. {\if\edition\pythonEd\pythonColor
  20285. Recall that the $\itm{tagof}$ function determines the bits used to
  20286. identify values of different types, and it is used in the \code{reveal\_casts}
  20287. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20288. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20289. decimal), just like the tuple and array types.
  20290. \fi}
  20291. %
  20292. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20293. \pagebreak
  20294. \section{Closure Conversion }
  20295. \label{sec:closure-conversion-gradual}
  20296. The auxiliary function that translates type annotations needs to be
  20297. updated to handle the \PTUPLETYNAME{}
  20298. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20299. %
  20300. Otherwise, the only other changes are adding cases that copy the new
  20301. AST nodes.
  20302. \section{Select Instructions }
  20303. \label{sec:select-instructions-gradual}
  20304. \index{subject}{select instructions}
  20305. Recall that the \code{select\_instructions} pass is responsible for
  20306. lowering the primitive operations into x86 instructions. So, we need
  20307. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20308. to x86. To do so, the first question we need to answer is how to
  20309. differentiate between tuple and tuple proxies\python{, and likewise for
  20310. arrays and array proxies}. We need just one bit to accomplish this;
  20311. we use the bit in position $63$ of the 64-bit tag at the front of
  20312. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20313. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20314. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20315. it that way.
  20316. {\if\edition\racketEd
  20317. \begin{lstlisting}
  20318. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20319. |$\Rightarrow$|
  20320. movq |$e'_1$|, |$\itm{lhs'}$|
  20321. \end{lstlisting}
  20322. \fi}
  20323. {\if\edition\pythonEd\pythonColor
  20324. \begin{lstlisting}
  20325. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20326. |$\Rightarrow$|
  20327. movq |$e'_1$|, |$\itm{lhs'}$|
  20328. \end{lstlisting}
  20329. \fi}
  20330. \python{The translation for \code{InjectList} is also a move instruction.}
  20331. \noindent On the other hand,
  20332. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20333. $63$ to $1$.
  20334. %
  20335. {\if\edition\racketEd
  20336. \begin{lstlisting}
  20337. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20338. |$\Rightarrow$|
  20339. movq |$e'_1$|, %r11
  20340. movq |$(1 << 63)$|, %rax
  20341. orq 0(%r11), %rax
  20342. movq %rax, 0(%r11)
  20343. movq %r11, |$\itm{lhs'}$|
  20344. \end{lstlisting}
  20345. \fi}
  20346. {\if\edition\pythonEd\pythonColor
  20347. \begin{lstlisting}
  20348. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20349. |$\Rightarrow$|
  20350. movq |$e'_1$|, %r11
  20351. movq |$(1 << 63)$|, %rax
  20352. orq 0(%r11), %rax
  20353. movq %rax, 0(%r11)
  20354. movq %r11, |$\itm{lhs'}$|
  20355. \end{lstlisting}
  20356. \fi}
  20357. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20358. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20359. The \racket{\code{proxy?} operation consumes}%
  20360. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20361. consume}
  20362. the information so carefully stashed away by the injections. It
  20363. isolates bit $63$ to tell whether the value is a proxy.
  20364. %
  20365. {\if\edition\racketEd
  20366. \begin{lstlisting}
  20367. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20368. |$\Rightarrow$|
  20369. movq |$e_1'$|, %r11
  20370. movq 0(%r11), %rax
  20371. sarq $63, %rax
  20372. andq $1, %rax
  20373. movq %rax, |$\itm{lhs'}$|
  20374. \end{lstlisting}
  20375. \fi}%
  20376. %
  20377. {\if\edition\pythonEd\pythonColor
  20378. \begin{lstlisting}
  20379. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20380. |$\Rightarrow$|
  20381. movq |$e_1'$|, %r11
  20382. movq 0(%r11), %rax
  20383. sarq $63, %rax
  20384. andq $1, %rax
  20385. movq %rax, |$\itm{lhs'}$|
  20386. \end{lstlisting}
  20387. \fi}%
  20388. %
  20389. The \racket{\code{project-vector} operation is}
  20390. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20391. straightforward to translate, so we leave that to the reader.
  20392. Regarding the element access operations for tuples\python{ and arrays}, the
  20393. runtime provides procedures that implement them (they are recursive
  20394. functions!), so here we simply need to translate these tuple
  20395. operations into the appropriate function call. For example, here is
  20396. the translation for
  20397. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20398. {\if\edition\racketEd
  20399. \begin{minipage}{0.96\textwidth}
  20400. \begin{lstlisting}
  20401. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20402. |$\Rightarrow$|
  20403. movq |$e_1'$|, %rdi
  20404. movq |$e_2'$|, %rsi
  20405. callq proxy_vector_ref
  20406. movq %rax, |$\itm{lhs'}$|
  20407. \end{lstlisting}
  20408. \end{minipage}
  20409. \fi}
  20410. {\if\edition\pythonEd\pythonColor
  20411. \begin{lstlisting}
  20412. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20413. |$\Rightarrow$|
  20414. movq |$e_1'$|, %rdi
  20415. movq |$e_2'$|, %rsi
  20416. callq proxy_vector_ref
  20417. movq %rax, |$\itm{lhs'}$|
  20418. \end{lstlisting}
  20419. \fi}
  20420. {\if\edition\pythonEd\pythonColor
  20421. % TODO: revisit the names vecof for python -Jeremy
  20422. We translate
  20423. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20424. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20425. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20426. \fi}
  20427. We have another batch of operations to deal with: those for the
  20428. \CANYTY{} type. Recall that we generate an
  20429. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20430. there is a element access on something of type \CANYTY{}, and
  20431. similarly for
  20432. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20433. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20434. section~\ref{sec:select-Lany} we selected instructions for these
  20435. operations on the basis of the idea that the underlying value was a tuple or
  20436. array. But in the current setting, the underlying value is of type
  20437. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20438. functions to deal with this:
  20439. \code{proxy\_vector\_ref},
  20440. \code{proxy\_vector\_set}, and
  20441. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20442. to determine whether the value is a proxy, and then
  20443. dispatches to the the appropriate code.
  20444. %
  20445. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20446. can be translated as follows.
  20447. We begin by projecting the underlying value out of the tagged value and
  20448. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20449. {\if\edition\racketEd
  20450. \begin{lstlisting}
  20451. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20452. |$\Rightarrow$|
  20453. movq |$\neg 111$|, %rdi
  20454. andq |$e_1'$|, %rdi
  20455. movq |$e_2'$|, %rsi
  20456. callq proxy_vector_ref
  20457. movq %rax, |$\itm{lhs'}$|
  20458. \end{lstlisting}
  20459. \fi}
  20460. {\if\edition\pythonEd\pythonColor
  20461. \begin{lstlisting}
  20462. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20463. |$\Rightarrow$|
  20464. movq |$\neg 111$|, %rdi
  20465. andq |$e_1'$|, %rdi
  20466. movq |$e_2'$|, %rsi
  20467. callq proxy_vector_ref
  20468. movq %rax, |$\itm{lhs'}$|
  20469. \end{lstlisting}
  20470. \fi}
  20471. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20472. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20473. are translated in a similar way. Alternatively, you could generate
  20474. instructions to open-code
  20475. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20476. and \code{proxy\_vector\_length} functions.
  20477. \begin{exercise}\normalfont\normalsize
  20478. Implement a compiler for the gradually typed \LangGrad{} language by
  20479. extending and adapting your compiler for \LangLam{}. Create ten new
  20480. partially typed test programs. In addition to testing with these
  20481. new programs, test your compiler on all the tests for \LangLam{}
  20482. and for \LangDyn{}.
  20483. %
  20484. \racket{Sometimes you may get a type-checking error on the
  20485. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20486. the \CANYTY{} type around each subexpression that has caused a type
  20487. error. Although \LangDyn{} does not have explicit casts, you can
  20488. induce one by wrapping the subexpression \code{e} with a call to
  20489. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20490. %
  20491. \python{Sometimes you may get a type-checking error on the
  20492. \LangDyn{} programs, but you can adapt them by inserting a
  20493. temporary variable of type \CANYTY{} that is initialized with the
  20494. troublesome expression.}
  20495. \end{exercise}
  20496. \begin{figure}[t]
  20497. \begin{tcolorbox}[colback=white]
  20498. {\if\edition\racketEd
  20499. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20500. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20501. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20502. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20503. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20504. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20505. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20506. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20507. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20508. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20509. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20510. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20511. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20512. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20513. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20514. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20515. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20516. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20517. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20518. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20519. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20520. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20521. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20522. \path[->,bend left=15] (Lgradual) edge [above] node
  20523. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20524. \path[->,bend left=15] (Lgradual2) edge [above] node
  20525. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20526. \path[->,bend left=15] (Lgradual3) edge [above] node
  20527. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20528. \path[->,bend left=15] (Lgradual4) edge [left] node
  20529. {\ttfamily\footnotesize shrink} (Lgradualr);
  20530. \path[->,bend left=15] (Lgradualr) edge [above] node
  20531. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20532. \path[->,bend right=15] (Lgradualp) edge [above] node
  20533. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20534. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20535. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20536. \path[->,bend right=15] (Llambdapp) edge [above] node
  20537. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20538. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20539. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20540. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20541. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20542. \path[->,bend left=15] (F1-2) edge [above] node
  20543. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20544. \path[->,bend left=15] (F1-3) edge [left] node
  20545. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20546. \path[->,bend left=15] (F1-4) edge [below] node
  20547. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20548. \path[->,bend right=15] (F1-5) edge [above] node
  20549. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20550. \path[->,bend right=15] (F1-6) edge [above] node
  20551. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20552. \path[->,bend right=15] (C3-2) edge [right] node
  20553. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20554. \path[->,bend right=15] (x86-2) edge [right] node
  20555. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20556. \path[->,bend right=15] (x86-2-1) edge [below] node
  20557. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20558. \path[->,bend right=15] (x86-2-2) edge [right] node
  20559. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20560. \path[->,bend left=15] (x86-3) edge [above] node
  20561. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20562. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20563. \end{tikzpicture}
  20564. \fi}
  20565. {\if\edition\pythonEd\pythonColor
  20566. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20567. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20568. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20569. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20570. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20571. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20572. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20573. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20574. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20575. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20576. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20577. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20578. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20579. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20580. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20581. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20582. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20583. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20584. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20585. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20586. \path[->,bend left=15] (Lgradual) edge [above] node
  20587. {\ttfamily\footnotesize shrink} (Lgradual2);
  20588. \path[->,bend left=15] (Lgradual2) edge [above] node
  20589. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20590. \path[->,bend left=15] (Lgradual3) edge [above] node
  20591. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20592. \path[->,bend left=15] (Lgradual4) edge [left] node
  20593. {\ttfamily\footnotesize resolve} (Lgradualr);
  20594. \path[->,bend left=15] (Lgradualr) edge [below] node
  20595. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20596. \path[->,bend right=15] (Lgradualp) edge [above] node
  20597. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20598. \path[->,bend right=15] (Llambdapp) edge [above] node
  20599. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20600. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20601. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20602. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20603. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20604. \path[->,bend left=15] (F1-1) edge [above] node
  20605. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20606. \path[->,bend left=15] (F1-2) edge [above] node
  20607. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20608. \path[->,bend left=15] (F1-3) edge [right] node
  20609. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20610. \path[->,bend right=15] (F1-5) edge [above] node
  20611. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20612. \path[->,bend right=15] (F1-6) edge [above] node
  20613. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20614. \path[->,bend right=15] (C3-2) edge [right] node
  20615. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20616. \path[->,bend right=15] (x86-2) edge [below] node
  20617. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20618. \path[->,bend right=15] (x86-3) edge [below] node
  20619. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20620. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20621. \end{tikzpicture}
  20622. \fi}
  20623. \end{tcolorbox}
  20624. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20625. \label{fig:Lgradual-passes}
  20626. \end{figure}
  20627. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20628. needed for the compilation of \LangGrad{}.
  20629. \section{Further Reading}
  20630. This chapter just scratches the surface of gradual typing. The basic
  20631. approach described here is missing two key ingredients that one would
  20632. want in an implementation of gradual typing: blame
  20633. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20634. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20635. problem addressed by blame tracking is that when a cast on a
  20636. higher-order value fails, it often does so at a point in the program
  20637. that is far removed from the original cast. Blame tracking is a
  20638. technique for propagating extra information through casts and proxies
  20639. so that when a cast fails, the error message can point back to the
  20640. original location of the cast in the source program.
  20641. The problem addressed by space-efficient casts also relates to
  20642. higher-order casts. It turns out that in partially typed programs, a
  20643. function or tuple can flow through a great many casts at runtime. With
  20644. the approach described in this chapter, each cast adds another
  20645. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20646. considerable space, but it also makes the function calls and tuple
  20647. operations slow. For example, a partially typed version of quicksort
  20648. could, in the worst case, build a chain of proxies of length $O(n)$
  20649. around the tuple, changing the overall time complexity of the
  20650. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20651. solution to this problem by representing casts using the coercion
  20652. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20653. long chains of proxies by compressing them into a concise normal
  20654. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20655. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20656. the Grift compiler:
  20657. \begin{center}
  20658. \url{https://github.com/Gradual-Typing/Grift}
  20659. \end{center}
  20660. There are also interesting interactions between gradual typing and
  20661. other language features, such as generics, information-flow types, and
  20662. type inference, to name a few. We recommend to the reader the
  20663. online gradual typing bibliography for more material:
  20664. \begin{center}
  20665. \url{http://samth.github.io/gradual-typing-bib/}
  20666. \end{center}
  20667. % TODO: challenge problem:
  20668. % type analysis and type specialization?
  20669. % coercions?
  20670. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20671. \chapter{Generics}
  20672. \label{ch:Lpoly}
  20673. \setcounter{footnote}{0}
  20674. This chapter studies the compilation of
  20675. generics\index{subject}{generics} (aka parametric
  20676. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20677. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20678. enable programmers to make code more reusable by parameterizing
  20679. functions and data structures with respect to the types on which they
  20680. operate. For example, figure~\ref{fig:map-poly} revisits the
  20681. \code{map} example and this time gives it a more fitting type. This
  20682. \code{map} function is parameterized with respect to the element type
  20683. of the tuple. The type of \code{map} is the following generic type
  20684. specified by the \code{All} type with parameter \code{T}:
  20685. {\if\edition\racketEd
  20686. \begin{lstlisting}
  20687. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20688. \end{lstlisting}
  20689. \fi}
  20690. {\if\edition\pythonEd\pythonColor
  20691. \begin{lstlisting}
  20692. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20693. \end{lstlisting}
  20694. \fi}
  20695. %
  20696. The idea is that \code{map} can be used at \emph{all} choices of a
  20697. type for parameter \code{T}. In the example shown in
  20698. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20699. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20700. \code{T}, but we could have just as well applied \code{map} to a tuple
  20701. of Booleans.
  20702. %
  20703. A \emph{monomorphic} function is simply one that is not generic.
  20704. %
  20705. We use the term \emph{instantiation} for the process (within the
  20706. language implementation) of turning a generic function into a
  20707. monomorphic one, where the type parameters have been replaced by
  20708. types.
  20709. {\if\edition\pythonEd\pythonColor
  20710. %
  20711. In Python, when writing a generic function such as \code{map}, one
  20712. does not explicitly write its generic type (using \code{All}).
  20713. Instead, that the function is generic is implied by the use of type
  20714. variables (such as \code{T}) in the type annotations of its
  20715. parameters.
  20716. %
  20717. \fi}
  20718. \begin{figure}[tbp]
  20719. % poly_test_2.rkt
  20720. \begin{tcolorbox}[colback=white]
  20721. {\if\edition\racketEd
  20722. \begin{lstlisting}
  20723. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20724. (define (map f v)
  20725. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20726. (define (inc [x : Integer]) : Integer (+ x 1))
  20727. (vector-ref (map inc (vector 0 41)) 1)
  20728. \end{lstlisting}
  20729. \fi}
  20730. {\if\edition\pythonEd\pythonColor
  20731. \begin{lstlisting}
  20732. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20733. return (f(tup[0]), f(tup[1]))
  20734. def add1(x : int) -> int:
  20735. return x + 1
  20736. t = map(add1, (0, 41))
  20737. print(t[1])
  20738. \end{lstlisting}
  20739. \fi}
  20740. \end{tcolorbox}
  20741. \caption{A generic version of the \code{map} function.}
  20742. \label{fig:map-poly}
  20743. \end{figure}
  20744. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20745. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20746. shows the definition of the abstract syntax.
  20747. %
  20748. {\if\edition\racketEd
  20749. We add a second form for function definitions in which a type
  20750. declaration comes before the \code{define}. In the abstract syntax,
  20751. the return type in the \code{Def} is \CANYTY{}, but that should be
  20752. ignored in favor of the return type in the type declaration. (The
  20753. \CANYTY{} comes from using the same parser as discussed in
  20754. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20755. enables the use of an \code{All} type for a function, thereby making
  20756. it generic.
  20757. \fi}
  20758. %
  20759. The grammar for types is extended to include the type of a generic
  20760. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20761. abstract syntax)}.
  20762. \newcommand{\LpolyGrammarRacket}{
  20763. \begin{array}{lcl}
  20764. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20765. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20766. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20767. \end{array}
  20768. }
  20769. \newcommand{\LpolyASTRacket}{
  20770. \begin{array}{lcl}
  20771. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20772. \Def &::=& \DECL{\Var}{\Type} \\
  20773. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20774. \end{array}
  20775. }
  20776. \newcommand{\LpolyGrammarPython}{
  20777. \begin{array}{lcl}
  20778. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20779. \end{array}
  20780. }
  20781. \newcommand{\LpolyASTPython}{
  20782. \begin{array}{lcl}
  20783. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20784. \MID \key{GenericVar}\LP\Var\RP
  20785. \end{array}
  20786. }
  20787. \begin{figure}[tp]
  20788. \centering
  20789. \begin{tcolorbox}[colback=white]
  20790. \footnotesize
  20791. {\if\edition\racketEd
  20792. \[
  20793. \begin{array}{l}
  20794. \gray{\LintGrammarRacket{}} \\ \hline
  20795. \gray{\LvarGrammarRacket{}} \\ \hline
  20796. \gray{\LifGrammarRacket{}} \\ \hline
  20797. \gray{\LwhileGrammarRacket} \\ \hline
  20798. \gray{\LtupGrammarRacket} \\ \hline
  20799. \gray{\LfunGrammarRacket} \\ \hline
  20800. \gray{\LlambdaGrammarRacket} \\ \hline
  20801. \LpolyGrammarRacket \\
  20802. \begin{array}{lcl}
  20803. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20804. \end{array}
  20805. \end{array}
  20806. \]
  20807. \fi}
  20808. {\if\edition\pythonEd\pythonColor
  20809. \[
  20810. \begin{array}{l}
  20811. \gray{\LintGrammarPython{}} \\ \hline
  20812. \gray{\LvarGrammarPython{}} \\ \hline
  20813. \gray{\LifGrammarPython{}} \\ \hline
  20814. \gray{\LwhileGrammarPython} \\ \hline
  20815. \gray{\LtupGrammarPython} \\ \hline
  20816. \gray{\LfunGrammarPython} \\ \hline
  20817. \gray{\LlambdaGrammarPython} \\\hline
  20818. \LpolyGrammarPython \\
  20819. \begin{array}{lcl}
  20820. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20821. \end{array}
  20822. \end{array}
  20823. \]
  20824. \fi}
  20825. \end{tcolorbox}
  20826. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20827. (figure~\ref{fig:Llam-concrete-syntax}).}
  20828. \label{fig:Lpoly-concrete-syntax}
  20829. \index{subject}{Lgen@\LangPoly{} concrete syntax}
  20830. \end{figure}
  20831. \begin{figure}[tp]
  20832. \centering
  20833. \begin{tcolorbox}[colback=white]
  20834. \footnotesize
  20835. {\if\edition\racketEd
  20836. \[
  20837. \begin{array}{l}
  20838. \gray{\LintOpAST} \\ \hline
  20839. \gray{\LvarASTRacket{}} \\ \hline
  20840. \gray{\LifASTRacket{}} \\ \hline
  20841. \gray{\LwhileASTRacket{}} \\ \hline
  20842. \gray{\LtupASTRacket{}} \\ \hline
  20843. \gray{\LfunASTRacket} \\ \hline
  20844. \gray{\LlambdaASTRacket} \\ \hline
  20845. \LpolyASTRacket \\
  20846. \begin{array}{lcl}
  20847. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20848. \end{array}
  20849. \end{array}
  20850. \]
  20851. \fi}
  20852. {\if\edition\pythonEd\pythonColor
  20853. \[
  20854. \begin{array}{l}
  20855. \gray{\LintASTPython} \\ \hline
  20856. \gray{\LvarASTPython{}} \\ \hline
  20857. \gray{\LifASTPython{}} \\ \hline
  20858. \gray{\LwhileASTPython{}} \\ \hline
  20859. \gray{\LtupASTPython{}} \\ \hline
  20860. \gray{\LfunASTPython} \\ \hline
  20861. \gray{\LlambdaASTPython} \\ \hline
  20862. \LpolyASTPython \\
  20863. \begin{array}{lcl}
  20864. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20865. \end{array}
  20866. \end{array}
  20867. \]
  20868. \fi}
  20869. \end{tcolorbox}
  20870. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20871. (figure~\ref{fig:Llam-syntax}).}
  20872. \label{fig:Lpoly-syntax}
  20873. \index{subject}{Lgen@\LangPoly{} abstract syntax}
  20874. \end{figure}
  20875. By including the \code{All} type in the $\Type$ nonterminal of the
  20876. grammar we choose to make generics first class, which has interesting
  20877. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20878. not include syntax for the \code{All} type. It is inferred for functions whose
  20879. type annotations contain type variables.} Many languages with generics, such as
  20880. C++~\citep{stroustrup88:_param_types} and Standard
  20881. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20882. may be helpful to see an example of first-class generics in action. In
  20883. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20884. whose parameter is a generic function. Indeed, because the grammar for
  20885. $\Type$ includes the \code{All} type, a generic function may also be
  20886. returned from a function or stored inside a tuple. The body of
  20887. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20888. and also to an integer, which would not be possible if \code{f} were
  20889. not generic.
  20890. \begin{figure}[tbp]
  20891. \begin{tcolorbox}[colback=white]
  20892. {\if\edition\racketEd
  20893. \begin{lstlisting}
  20894. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20895. (define (apply_twice f)
  20896. (if (f #t) (f 42) (f 777)))
  20897. (: id (All (T) (T -> T)))
  20898. (define (id x) x)
  20899. (apply_twice id)
  20900. \end{lstlisting}
  20901. \fi}
  20902. {\if\edition\pythonEd\pythonColor
  20903. \begin{lstlisting}
  20904. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20905. if f(True):
  20906. return f(42)
  20907. else:
  20908. return f(777)
  20909. def id(x: T) -> T:
  20910. return x
  20911. print(apply_twice(id))
  20912. \end{lstlisting}
  20913. \fi}
  20914. \end{tcolorbox}
  20915. \caption{An example illustrating first-class generics.}
  20916. \label{fig:apply-twice}
  20917. \end{figure}
  20918. The type checker for \LangPoly{} shown in
  20919. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20920. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20921. {\if\edition\pythonEd\pythonColor
  20922. %
  20923. Regarding function definitions, if the type annotations on its
  20924. parameters contain generic variables, then the function is generic and
  20925. therefore its type is an \code{All} type wrapped around a function
  20926. type. Otherwise the function is monomorphic and its type is simply
  20927. a function type.
  20928. %
  20929. \fi}
  20930. The type checking of a function application is extended to handle the
  20931. case in which the operator expression is a generic function. In that case
  20932. the type arguments are deduced by matching the types of the parameters
  20933. with the types of the arguments.
  20934. %
  20935. The \code{match\_types} auxiliary function
  20936. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20937. recursively descending through a parameter type \code{param\_ty} and
  20938. the corresponding argument type \code{arg\_ty}, making sure that they
  20939. are equal except when there is a type parameter in the parameter
  20940. type. Upon encountering a type parameter for the first time, the
  20941. algorithm deduces an association of the type parameter to the
  20942. corresponding part of the argument type. If it is not the first time
  20943. that the type parameter has been encountered, the algorithm looks up
  20944. its deduced type and makes sure that it is equal to the corresponding
  20945. part of the argument type. The return type of the application is the
  20946. return type of the generic function with the type parameters
  20947. replaced by the deduced type arguments, using the
  20948. \code{substitute\_type} auxiliary function, which is also listed in
  20949. figure~\ref{fig:type-check-Lpoly-aux}.
  20950. The type checker extends type equality to handle the \code{All} type.
  20951. This is not quite as simple as for other types, such as function and
  20952. tuple types, because two \code{All} types can be syntactically
  20953. different even though they are equivalent. For example,
  20954. \begin{center}
  20955. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20956. \end{center}
  20957. is equivalent to
  20958. \begin{center}
  20959. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20960. \end{center}
  20961. Two generic types are equal if they differ only in
  20962. the choice of the names of the type parameters. The definition of type
  20963. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20964. parameters in one type to match the type parameters of the other type.
  20965. {\if\edition\racketEd
  20966. %
  20967. The type checker also ensures that only defined type variables appear
  20968. in type annotations. The \code{check\_well\_formed} function for which
  20969. the definition is shown in figure~\ref{fig:well-formed-types}
  20970. recursively inspects a type, making sure that each type variable has
  20971. been defined.
  20972. %
  20973. \fi}
  20974. \begin{figure}[tbp]
  20975. \begin{tcolorbox}[colback=white]
  20976. {\if\edition\racketEd
  20977. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20978. (define type-check-poly-class
  20979. (class type-check-Llambda-class
  20980. (super-new)
  20981. (inherit check-type-equal?)
  20982. (define/override (type-check-apply env e1 es)
  20983. (define-values (e^ ty) ((type-check-exp env) e1))
  20984. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20985. ((type-check-exp env) e)))
  20986. (match ty
  20987. [`(,ty^* ... -> ,rt)
  20988. (for ([arg-ty ty*] [param-ty ty^*])
  20989. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20990. (values e^ es^ rt)]
  20991. [`(All ,xs (,tys ... -> ,rt))
  20992. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20993. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20994. (match_types env^^ param-ty arg-ty)))
  20995. (define targs
  20996. (for/list ([x xs])
  20997. (match (dict-ref env^^ x (lambda () #f))
  20998. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20999. x (Apply e1 es))]
  21000. [ty ty])))
  21001. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  21002. [else (error 'type-check "expected a function, not ~a" ty)]))
  21003. (define/override ((type-check-exp env) e)
  21004. (match e
  21005. [(Lambda `([,xs : ,Ts] ...) rT body)
  21006. (for ([T Ts]) ((check_well_formed env) T))
  21007. ((check_well_formed env) rT)
  21008. ((super type-check-exp env) e)]
  21009. [(HasType e1 ty)
  21010. ((check_well_formed env) ty)
  21011. ((super type-check-exp env) e)]
  21012. [else ((super type-check-exp env) e)]))
  21013. (define/override ((type-check-def env) d)
  21014. (verbose 'type-check "poly/def" d)
  21015. (match d
  21016. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  21017. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  21018. (for ([p ps]) ((check_well_formed ts-env) p))
  21019. ((check_well_formed ts-env) rt)
  21020. (define new-env (append ts-env (map cons xs ps) env))
  21021. (define-values (body^ ty^) ((type-check-exp new-env) body))
  21022. (check-type-equal? ty^ rt body)
  21023. (Generic ts (Def f p:t* rt info body^))]
  21024. [else ((super type-check-def env) d)]))
  21025. (define/override (type-check-program p)
  21026. (match p
  21027. [(Program info body)
  21028. (type-check-program (ProgramDefsExp info '() body))]
  21029. [(ProgramDefsExp info ds body)
  21030. (define ds^ (combine-decls-defs ds))
  21031. (define new-env (for/list ([d ds^])
  21032. (cons (def-name d) (fun-def-type d))))
  21033. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  21034. (define-values (body^ ty) ((type-check-exp new-env) body))
  21035. (check-type-equal? ty 'Integer body)
  21036. (ProgramDefsExp info ds^^ body^)]))
  21037. ))
  21038. \end{lstlisting}
  21039. \fi}
  21040. {\if\edition\pythonEd\pythonColor
  21041. \begin{lstlisting}[basicstyle=\ttfamily\small]
  21042. def type_check_exp(self, e, env):
  21043. match e:
  21044. case Call(Name(f), args) if f in builtin_functions:
  21045. return super().type_check_exp(e, env)
  21046. case Call(func, args):
  21047. func_t = self.type_check_exp(func, env)
  21048. func.has_type = func_t
  21049. match func_t:
  21050. case AllType(ps, FunctionType(p_tys, rt)):
  21051. for arg in args:
  21052. arg.has_type = self.type_check_exp(arg, env)
  21053. arg_tys = [arg.has_type for arg in args]
  21054. deduced = {}
  21055. for (p, a) in zip(p_tys, arg_tys):
  21056. self.match_types(p, a, deduced, e)
  21057. return self.substitute_type(rt, deduced)
  21058. case _:
  21059. return super().type_check_exp(e, env)
  21060. case _:
  21061. return super().type_check_exp(e, env)
  21062. def type_check(self, p):
  21063. match p:
  21064. case Module(body):
  21065. env = {}
  21066. for s in body:
  21067. match s:
  21068. case FunctionDef(name, params, bod, dl, returns, comment):
  21069. params_t = [t for (x,t) in params]
  21070. ty_params = set()
  21071. for t in params_t:
  21072. ty_params |$\mid$|= self.generic_variables(t)
  21073. ty = FunctionType(params_t, returns)
  21074. if len(ty_params) > 0:
  21075. ty = AllType(list(ty_params), ty)
  21076. env[name] = ty
  21077. self.check_stmts(body, IntType(), env)
  21078. case _:
  21079. raise Exception('type_check: unexpected ' + repr(p))
  21080. \end{lstlisting}
  21081. \fi}
  21082. \end{tcolorbox}
  21083. \caption{Type checker for the \LangPoly{} language.}
  21084. \label{fig:type-check-Lpoly}
  21085. \end{figure}
  21086. \begin{figure}[tbp]
  21087. \begin{tcolorbox}[colback=white]
  21088. {\if\edition\racketEd
  21089. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21090. (define/override (type-equal? t1 t2)
  21091. (match* (t1 t2)
  21092. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21093. (define env (map cons xs ys))
  21094. (type-equal? (substitute_type env T1) T2)]
  21095. [(other wise)
  21096. (super type-equal? t1 t2)]))
  21097. (define/public (match_types env pt at)
  21098. (match* (pt at)
  21099. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21100. [('Void 'Void) env] [('Any 'Any) env]
  21101. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21102. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21103. (match_types env^ pt1 at1))]
  21104. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21105. (define env^ (match_types env prt art))
  21106. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21107. (match_types env^^ pt1 at1))]
  21108. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21109. (define env^ (append (map cons pxs axs) env))
  21110. (match_types env^ pt1 at1)]
  21111. [((? symbol? x) at)
  21112. (match (dict-ref env x (lambda () #f))
  21113. [#f (error 'type-check "undefined type variable ~a" x)]
  21114. ['Type (cons (cons x at) env)]
  21115. [t^ (check-type-equal? at t^ 'matching) env])]
  21116. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21117. (define/public (substitute_type env pt)
  21118. (match pt
  21119. ['Integer 'Integer] ['Boolean 'Boolean]
  21120. ['Void 'Void] ['Any 'Any]
  21121. [`(Vector ,ts ...)
  21122. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21123. [`(,ts ... -> ,rt)
  21124. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21125. [`(All ,xs ,t)
  21126. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21127. [(? symbol? x) (dict-ref env x)]
  21128. [else (error 'type-check "expected a type not ~a" pt)]))
  21129. (define/public (combine-decls-defs ds)
  21130. (match ds
  21131. ['() '()]
  21132. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21133. (unless (equal? name f)
  21134. (error 'type-check "name mismatch, ~a != ~a" name f))
  21135. (match type
  21136. [`(All ,xs (,ps ... -> ,rt))
  21137. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21138. (cons (Generic xs (Def name params^ rt info body))
  21139. (combine-decls-defs ds^))]
  21140. [`(,ps ... -> ,rt)
  21141. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21142. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21143. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21144. [`(,(Def f params rt info body) . ,ds^)
  21145. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21146. \end{lstlisting}
  21147. \fi}
  21148. {\if\edition\pythonEd\pythonColor
  21149. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21150. def match_types(self, param_ty, arg_ty, deduced, e):
  21151. match (param_ty, arg_ty):
  21152. case (GenericVar(id), _):
  21153. if id in deduced:
  21154. self.check_type_equal(arg_ty, deduced[id], e)
  21155. else:
  21156. deduced[id] = arg_ty
  21157. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21158. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21159. new_arg_ty = self.substitute_type(arg_ty, rename)
  21160. self.match_types(ty, new_arg_ty, deduced, e)
  21161. case (TupleType(ps), TupleType(ts)):
  21162. for (p, a) in zip(ps, ts):
  21163. self.match_types(p, a, deduced, e)
  21164. case (ListType(p), ListType(a)):
  21165. self.match_types(p, a, deduced, e)
  21166. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21167. for (pp, ap) in zip(pps, aps):
  21168. self.match_types(pp, ap, deduced, e)
  21169. self.match_types(prt, art, deduced, e)
  21170. case (IntType(), IntType()):
  21171. pass
  21172. case (BoolType(), BoolType()):
  21173. pass
  21174. case _:
  21175. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21176. def substitute_type(self, ty, var_map):
  21177. match ty:
  21178. case GenericVar(id):
  21179. return var_map[id]
  21180. case AllType(ps, ty):
  21181. new_map = copy.deepcopy(var_map)
  21182. for p in ps:
  21183. new_map[p] = GenericVar(p)
  21184. return AllType(ps, self.substitute_type(ty, new_map))
  21185. case TupleType(ts):
  21186. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21187. case ListType(ty):
  21188. return ListType(self.substitute_type(ty, var_map))
  21189. case FunctionType(pts, rt):
  21190. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21191. self.substitute_type(rt, var_map))
  21192. case IntType():
  21193. return IntType()
  21194. case BoolType():
  21195. return BoolType()
  21196. case _:
  21197. raise Exception('substitute_type: unexpected ' + repr(ty))
  21198. def check_type_equal(self, t1, t2, e):
  21199. match (t1, t2):
  21200. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21201. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21202. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21203. case (_, _):
  21204. return super().check_type_equal(t1, t2, e)
  21205. \end{lstlisting}
  21206. \fi}
  21207. \end{tcolorbox}
  21208. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21209. \label{fig:type-check-Lpoly-aux}
  21210. \end{figure}
  21211. {\if\edition\racketEd
  21212. \begin{figure}[tbp]
  21213. \begin{tcolorbox}[colback=white]
  21214. \begin{lstlisting}
  21215. (define/public ((check_well_formed env) ty)
  21216. (match ty
  21217. ['Integer (void)]
  21218. ['Boolean (void)]
  21219. ['Void (void)]
  21220. [(? symbol? a)
  21221. (match (dict-ref env a (lambda () #f))
  21222. ['Type (void)]
  21223. [else (error 'type-check "undefined type variable ~a" a)])]
  21224. [`(Vector ,ts ...)
  21225. (for ([t ts]) ((check_well_formed env) t))]
  21226. [`(,ts ... -> ,t)
  21227. (for ([t ts]) ((check_well_formed env) t))
  21228. ((check_well_formed env) t)]
  21229. [`(All ,xs ,t)
  21230. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21231. ((check_well_formed env^) t)]
  21232. [else (error 'type-check "unrecognized type ~a" ty)]))
  21233. \end{lstlisting}
  21234. \end{tcolorbox}
  21235. \caption{Well-formed types.}
  21236. \label{fig:well-formed-types}
  21237. \end{figure}
  21238. \fi}
  21239. % TODO: interpreter for R'_10
  21240. \clearpage
  21241. \section{Compiling Generics}
  21242. \label{sec:compiling-poly}
  21243. Broadly speaking, there are four approaches to compiling generics, as
  21244. follows:
  21245. \begin{description}
  21246. \item[Monomorphization] generates a different version of a generic
  21247. function for each set of type arguments with which it is used,
  21248. producing type-specialized code. This approach results in the most
  21249. efficient code but requires whole-program compilation (no separate
  21250. compilation) and may increase code size. Unfortunately,
  21251. monomorphization is incompatible with first-class generics because
  21252. it is not always possible to determine which generic functions are
  21253. used with which type arguments during compilation. (It can be done
  21254. at runtime with just-in-time compilation.) Monomorphization is
  21255. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21256. generic functions in NESL~\citep{Blelloch:1993aa} and
  21257. ML~\citep{Weeks:2006aa}.
  21258. \item[Uniform representation] generates one version of each generic
  21259. function and requires all values to have a common \emph{boxed} format,
  21260. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21261. generic and monomorphic code is compiled similarly to code in a
  21262. dynamically typed language (like \LangDyn{}), in which primitive
  21263. operators require their arguments to be projected from \CANYTY{} and
  21264. their results to be injected into \CANYTY{}. (In object-oriented
  21265. languages, the projection is accomplished via virtual method
  21266. dispatch.) The uniform representation approach is compatible with
  21267. separate compilation and with first-class generics. However, it
  21268. produces the least efficient code because it introduces overhead in
  21269. the entire program. This approach is used in
  21270. Java~\citep{Bracha:1998fk},
  21271. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21272. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21273. \item[Mixed representation] generates one version of each generic
  21274. function, using a boxed representation for type variables. However,
  21275. monomorphic code is compiled as usual (as in \LangLam{}), and
  21276. conversions are performed at the boundaries between monomorphic code
  21277. and polymorphic code (for example, when a generic function is instantiated
  21278. and called). This approach is compatible with separate compilation
  21279. and first-class generics and maintains efficiency in monomorphic
  21280. code. The trade-off is increased overhead at the boundary between
  21281. monomorphic and generic code. This approach is used in
  21282. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21283. Java 5 with the addition of autoboxing.
  21284. \item[Type passing] uses the unboxed representation in both
  21285. monomorphic and generic code. Each generic function is compiled to a
  21286. single function with extra parameters that describe the type
  21287. arguments. The type information is used by the generated code to
  21288. determine how to access the unboxed values at runtime. This approach is
  21289. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21290. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21291. compilation and first-class generics and maintains the
  21292. efficiency for monomorphic code. There is runtime overhead in
  21293. polymorphic code from dispatching on type information.
  21294. \end{description}
  21295. In this chapter we use the mixed representation approach, partly
  21296. because of its favorable attributes and partly because it is
  21297. straightforward to implement using the tools that we have already
  21298. built to support gradual typing. The work of compiling generic
  21299. functions is performed in two passes, \code{resolve} and
  21300. \code{erase\_types}, that we discuss next. The output of
  21301. \code{erase\_types} is \LangCast{}
  21302. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21303. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21304. \section{Resolve Instantiation}
  21305. \label{sec:generic-resolve}
  21306. Recall that the type checker for \LangPoly{} deduces the type
  21307. arguments at call sites to a generic function. The purpose of the
  21308. \code{resolve} pass is to turn this implicit instantiation into an
  21309. explicit one, by adding \code{inst} nodes to the syntax of the
  21310. intermediate language. An \code{inst} node records the mapping of
  21311. type parameters to type arguments. The semantics of the \code{inst}
  21312. node is to instantiate the result of its first argument, a generic
  21313. function, to produce a monomorphic function. However, because the
  21314. interpreter never analyzes type annotations, instantiation can be a
  21315. no-op and simply return the generic function.
  21316. %
  21317. The output language of the \code{resolve} pass is \LangInst{},
  21318. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21319. {\if\edition\racketEd
  21320. The \code{resolve} pass combines the type declaration and polymorphic
  21321. function into a single definition, using the \code{Poly} form, to make
  21322. polymorphic functions more convenient to process in the next pass of the
  21323. compiler.
  21324. \fi}
  21325. \newcommand{\LinstASTRacket}{
  21326. \begin{array}{lcl}
  21327. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21328. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21329. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21330. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21331. \end{array}
  21332. }
  21333. \newcommand{\LinstASTPython}{
  21334. \begin{array}{lcl}
  21335. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21336. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21337. \end{array}
  21338. }
  21339. \begin{figure}[tp]
  21340. \centering
  21341. \begin{tcolorbox}[colback=white]
  21342. \small
  21343. {\if\edition\racketEd
  21344. \[
  21345. \begin{array}{l}
  21346. \gray{\LintOpAST} \\ \hline
  21347. \gray{\LvarASTRacket{}} \\ \hline
  21348. \gray{\LifASTRacket{}} \\ \hline
  21349. \gray{\LwhileASTRacket{}} \\ \hline
  21350. \gray{\LtupASTRacket{}} \\ \hline
  21351. \gray{\LfunASTRacket} \\ \hline
  21352. \gray{\LlambdaASTRacket} \\ \hline
  21353. \LinstASTRacket \\
  21354. \begin{array}{lcl}
  21355. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21356. \end{array}
  21357. \end{array}
  21358. \]
  21359. \fi}
  21360. {\if\edition\pythonEd\pythonColor
  21361. \[
  21362. \begin{array}{l}
  21363. \gray{\LintASTPython} \\ \hline
  21364. \gray{\LvarASTPython{}} \\ \hline
  21365. \gray{\LifASTPython{}} \\ \hline
  21366. \gray{\LwhileASTPython{}} \\ \hline
  21367. \gray{\LtupASTPython{}} \\ \hline
  21368. \gray{\LfunASTPython} \\ \hline
  21369. \gray{\LlambdaASTPython} \\ \hline
  21370. \LinstASTPython \\
  21371. \begin{array}{lcl}
  21372. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21373. \end{array}
  21374. \end{array}
  21375. \]
  21376. \fi}
  21377. \end{tcolorbox}
  21378. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21379. (figure~\ref{fig:Llam-syntax}).}
  21380. \label{fig:Lpoly-prime-syntax}
  21381. \index{subject}{Linst@\LangInst{} abstract syntax}
  21382. \end{figure}
  21383. The output of the \code{resolve} pass on the generic \code{map}
  21384. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21385. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21386. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21387. \begin{figure}[tbp]
  21388. % poly_test_2.rkt
  21389. \begin{tcolorbox}[colback=white]
  21390. {\if\edition\racketEd
  21391. \begin{lstlisting}
  21392. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21393. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21394. (define (inc [x : Integer]) : Integer (+ x 1))
  21395. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21396. (Integer))
  21397. inc (vector 0 41)) 1)
  21398. \end{lstlisting}
  21399. \fi}
  21400. {\if\edition\pythonEd\pythonColor
  21401. \begin{lstlisting}
  21402. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21403. return (f(tup[0]), f(tup[1]))
  21404. def add1(x : int) -> int:
  21405. return x + 1
  21406. t = inst(map, {T: int})(add1, (0, 41))
  21407. print(t[1])
  21408. \end{lstlisting}
  21409. \fi}
  21410. \end{tcolorbox}
  21411. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21412. \label{fig:map-resolve}
  21413. \end{figure}
  21414. \section{Erase Generic Types}
  21415. \label{sec:erase_types}
  21416. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21417. represent type variables. For example, figure~\ref{fig:map-erase}
  21418. shows the output of the \code{erase\_types} pass on the generic
  21419. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21420. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21421. \code{All} types are removed from the type of \code{map}.
  21422. \begin{figure}[tbp]
  21423. \begin{tcolorbox}[colback=white]
  21424. {\if\edition\racketEd
  21425. \begin{lstlisting}
  21426. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21427. : (Vector Any Any)
  21428. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21429. (define (inc [x : Integer]) : Integer (+ x 1))
  21430. (vector-ref ((cast map
  21431. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21432. ((Integer -> Integer) (Vector Integer Integer)
  21433. -> (Vector Integer Integer)))
  21434. inc (vector 0 41)) 1)
  21435. \end{lstlisting}
  21436. \fi}
  21437. {\if\edition\pythonEd\pythonColor
  21438. \begin{lstlisting}
  21439. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21440. return (f(tup[0]), f(tup[1]))
  21441. def add1(x : int) -> int:
  21442. return (x + 1)
  21443. def main() -> int:
  21444. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21445. print(t[1])
  21446. return 0
  21447. \end{lstlisting}
  21448. {\small
  21449. where\\
  21450. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21451. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21452. }
  21453. \fi}
  21454. \end{tcolorbox}
  21455. \caption{The generic \code{map} example after type erasure.}
  21456. \label{fig:map-erase}
  21457. \end{figure}
  21458. This process of type erasure creates a challenge at points of
  21459. instantiation. For example, consider the instantiation of
  21460. \code{map} shown in figure~\ref{fig:map-resolve}.
  21461. The type of \code{map} is
  21462. %
  21463. {\if\edition\racketEd
  21464. \begin{lstlisting}
  21465. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21466. \end{lstlisting}
  21467. \fi}
  21468. {\if\edition\pythonEd\pythonColor
  21469. \begin{lstlisting}
  21470. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21471. \end{lstlisting}
  21472. \fi}
  21473. %
  21474. \noindent and it is instantiated to
  21475. %
  21476. {\if\edition\racketEd
  21477. \begin{lstlisting}
  21478. ((Integer -> Integer) (Vector Integer Integer)
  21479. -> (Vector Integer Integer))
  21480. \end{lstlisting}
  21481. \fi}
  21482. {\if\edition\pythonEd\pythonColor
  21483. \begin{lstlisting}
  21484. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21485. \end{lstlisting}
  21486. \fi}
  21487. %
  21488. \noindent After erasure, the type of \code{map} is
  21489. %
  21490. {\if\edition\racketEd
  21491. \begin{lstlisting}
  21492. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21493. \end{lstlisting}
  21494. \fi}
  21495. {\if\edition\pythonEd\pythonColor
  21496. \begin{lstlisting}
  21497. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21498. \end{lstlisting}
  21499. \fi}
  21500. %
  21501. \noindent but we need to convert it to the instantiated type. This is
  21502. easy to do in the language \LangCast{} with a single \code{cast}. In
  21503. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21504. \code{map} has been compiled to a \code{cast} from the type of
  21505. \code{map} to the instantiated type. The source and the target type of
  21506. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21507. is the case because both the source and target are obtained from the
  21508. same generic type of \code{map}, replacing the type parameters with
  21509. \CANYTY{} in the former and with the deduced type arguments in the
  21510. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21511. To implement the \code{erase\_types} pass, we first recommend defining
  21512. a recursive function that translates types, named
  21513. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21514. follows.
  21515. %
  21516. {\if\edition\racketEd
  21517. \begin{lstlisting}
  21518. |$T$|
  21519. |$\Rightarrow$|
  21520. Any
  21521. \end{lstlisting}
  21522. \fi}
  21523. {\if\edition\pythonEd\pythonColor
  21524. \begin{lstlisting}
  21525. GenericVar(|$T$|)
  21526. |$\Rightarrow$|
  21527. Any
  21528. \end{lstlisting}
  21529. \fi}
  21530. %
  21531. \noindent The \code{erase\_type} function also removes the generic
  21532. \code{All} types.
  21533. %
  21534. {\if\edition\racketEd
  21535. \begin{lstlisting}
  21536. (All |$xs$| |$T_1$|)
  21537. |$\Rightarrow$|
  21538. |$T'_1$|
  21539. \end{lstlisting}
  21540. \fi}
  21541. {\if\edition\pythonEd\pythonColor
  21542. \begin{lstlisting}
  21543. AllType(|$xs$|, |$T_1$|)
  21544. |$\Rightarrow$|
  21545. |$T'_1$|
  21546. \end{lstlisting}
  21547. \fi}
  21548. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21549. $T_1$.
  21550. %
  21551. In this compiler pass, apply the \code{erase\_type} function to all
  21552. the type annotations in the program.
  21553. Regarding the translation of expressions, the case for \code{Inst} is
  21554. the interesting one. We translate it into a \code{Cast}, as shown
  21555. next.
  21556. The type of the subexpression $e$ is a generic type of the form
  21557. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21558. The source type of the cast is the erasure of $T$, the type $T_s$.
  21559. %
  21560. {\if\edition\racketEd
  21561. %
  21562. The target type $T_t$ is the result of substituting the argument types
  21563. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21564. erasure.
  21565. %
  21566. \begin{lstlisting}
  21567. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21568. |$\Rightarrow$|
  21569. (Cast |$e'$| |$T_s$| |$T_t$|)
  21570. \end{lstlisting}
  21571. %
  21572. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21573. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21574. \fi}
  21575. {\if\edition\pythonEd\pythonColor
  21576. %
  21577. The target type $T_t$ is the result of substituting the deduced
  21578. argument types $d$ in $T$ and then performing type erasure.
  21579. %
  21580. \begin{lstlisting}
  21581. Inst(|$e$|, |$d$|)
  21582. |$\Rightarrow$|
  21583. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21584. \end{lstlisting}
  21585. %
  21586. where
  21587. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21588. \fi}
  21589. Finally, each generic function is translated to a regular
  21590. function in which type erasure has been applied to all the type
  21591. annotations and the body.
  21592. %% \begin{lstlisting}
  21593. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21594. %% |$\Rightarrow$|
  21595. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21596. %% \end{lstlisting}
  21597. \begin{exercise}\normalfont\normalsize
  21598. Implement a compiler for the polymorphic language \LangPoly{} by
  21599. extending and adapting your compiler for \LangGrad{}. Create six new
  21600. test programs that use polymorphic functions. Some of them should
  21601. make use of first-class generics.
  21602. \end{exercise}
  21603. \begin{figure}[tbp]
  21604. \begin{tcolorbox}[colback=white]
  21605. {\if\edition\racketEd
  21606. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21607. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21608. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21609. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21610. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21611. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21612. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21613. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21614. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21615. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21616. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21617. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21618. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21619. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21620. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21621. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21622. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21623. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21624. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21625. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21626. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21627. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21628. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21629. \path[->,bend left=15] (Lpoly) edge [above] node
  21630. {\ttfamily\footnotesize resolve} (Lpolyp);
  21631. \path[->,bend left=15] (Lpolyp) edge [above] node
  21632. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21633. \path[->,bend left=15] (Lgradualp) edge [above] node
  21634. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21635. \path[->,bend left=15] (Llambdapp) edge [left] node
  21636. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21637. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21638. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21639. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21640. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21641. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21642. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21643. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21644. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21645. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21646. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21647. \path[->,bend left=15] (F1-1) edge [above] node
  21648. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21649. \path[->,bend left=15] (F1-2) edge [above] node
  21650. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21651. \path[->,bend left=15] (F1-3) edge [left] node
  21652. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21653. \path[->,bend left=15] (F1-4) edge [below] node
  21654. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21655. \path[->,bend right=15] (F1-5) edge [above] node
  21656. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21657. \path[->,bend right=15] (F1-6) edge [above] node
  21658. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21659. \path[->,bend right=15] (C3-2) edge [right] node
  21660. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21661. \path[->,bend right=15] (x86-2) edge [right] node
  21662. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21663. \path[->,bend right=15] (x86-2-1) edge [below] node
  21664. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21665. \path[->,bend right=15] (x86-2-2) edge [right] node
  21666. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21667. \path[->,bend left=15] (x86-3) edge [above] node
  21668. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21669. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21670. \end{tikzpicture}
  21671. \fi}
  21672. {\if\edition\pythonEd\pythonColor
  21673. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21674. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21675. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21676. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21677. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21678. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21679. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21680. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21681. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21682. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21683. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21684. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21685. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21686. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21687. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21688. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21689. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21690. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21691. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21692. \path[->,bend left=15] (Lgradual) edge [above] node
  21693. {\ttfamily\footnotesize shrink} (Lgradual2);
  21694. \path[->,bend left=15] (Lgradual2) edge [above] node
  21695. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21696. \path[->,bend left=15] (Lgradual3) edge [above] node
  21697. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21698. \path[->,bend left=15] (Lgradual4) edge [left] node
  21699. {\ttfamily\footnotesize resolve} (Lgradualr);
  21700. \path[->,bend left=15] (Lgradualr) edge [below] node
  21701. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21702. \path[->,bend right=15] (Llambdapp) edge [above] node
  21703. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21704. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21705. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21706. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21707. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21708. \path[->,bend right=15] (F1-1) edge [below] node
  21709. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21710. \path[->,bend right=15] (F1-2) edge [below] node
  21711. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21712. \path[->,bend left=15] (F1-3) edge [above] node
  21713. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21714. \path[->,bend left=15] (F1-5) edge [left] node
  21715. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21716. \path[->,bend left=5] (F1-6) edge [below] node
  21717. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21718. \path[->,bend right=15] (C3-2) edge [right] node
  21719. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21720. \path[->,bend right=15] (x86-2) edge [below] node
  21721. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21722. \path[->,bend right=15] (x86-3) edge [below] node
  21723. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21724. \path[->,bend left=15] (x86-4) edge [above] node
  21725. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21726. \end{tikzpicture}
  21727. \fi}
  21728. \end{tcolorbox}
  21729. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21730. \label{fig:Lpoly-passes}
  21731. \end{figure}
  21732. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21733. needed to compile \LangPoly{}.
  21734. % TODO: challenge problem: specialization of instantiations
  21735. % Further Reading
  21736. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21737. \clearpage
  21738. \appendix
  21739. \chapter{Appendix}
  21740. \setcounter{footnote}{0}
  21741. {\if\edition\racketEd
  21742. \section{Interpreters}
  21743. \label{appendix:interp}
  21744. \index{subject}{interpreter}
  21745. We provide interpreters for each of the source languages \LangInt{},
  21746. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21747. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21748. intermediate languages \LangCVar{} and \LangCIf{} are in
  21749. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21750. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21751. \key{interp.rkt} file.
  21752. \section{Utility Functions}
  21753. \label{appendix:utilities}
  21754. The utility functions described in this section are in the
  21755. \key{utilities.rkt} file of the support code.
  21756. \paragraph{\code{interp-tests}}
  21757. This function runs the compiler passes and the interpreters on each of
  21758. the specified tests to check whether each pass is correct. The
  21759. \key{interp-tests} function has the following parameters:
  21760. \begin{description}
  21761. \item[name (a string)] A name to identify the compiler.
  21762. \item[typechecker] A function of exactly one argument that either
  21763. raises an error using the \code{error} function when it encounters a
  21764. type error, or returns \code{\#f} when it encounters a type
  21765. error. If there is no type error, the type checker returns the
  21766. program.
  21767. \item[passes] A list with one entry per pass. An entry is a list
  21768. consisting of four things:
  21769. \begin{enumerate}
  21770. \item a string giving the name of the pass;
  21771. \item the function that implements the pass (a translator from AST
  21772. to AST);
  21773. \item a function that implements the interpreter (a function from
  21774. AST to result value) for the output language; and,
  21775. \item a type checker for the output language. Type checkers for
  21776. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21777. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21778. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21779. type checker entry is optional. The support code does not provide
  21780. type checkers for the x86 languages.
  21781. \end{enumerate}
  21782. \item[source-interp] An interpreter for the source language. The
  21783. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21784. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21785. \item[tests] A list of test numbers that specifies which tests to
  21786. run (explained next).
  21787. \end{description}
  21788. %
  21789. The \key{interp-tests} function assumes that the subdirectory
  21790. \key{tests} has a collection of Racket programs whose names all start
  21791. with the family name, followed by an underscore and then the test
  21792. number, and ending with the file extension \key{.rkt}. Also, for each test
  21793. program that calls \code{read} one or more times, there is a file with
  21794. the same name except that the file extension is \key{.in}, which
  21795. provides the input for the Racket program. If the test program is
  21796. expected to fail type checking, then there should be an empty file of
  21797. the same name with extension \key{.tyerr}.
  21798. \paragraph{\code{compiler-tests}}
  21799. This function runs the compiler passes to generate x86 (a \key{.s}
  21800. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21801. It runs the machine code and checks that the output is $42$. The
  21802. parameters to the \code{compiler-tests} function are similar to those
  21803. of the \code{interp-tests} function, and they consist of
  21804. \begin{itemize}
  21805. \item a compiler name (a string),
  21806. \item a type checker,
  21807. \item description of the passes,
  21808. \item name of a test-family, and
  21809. \item a list of test numbers.
  21810. \end{itemize}
  21811. \paragraph{\code{compile-file}}
  21812. This function takes a description of the compiler passes (see the
  21813. comment for \key{interp-tests}) and returns a function that, given a
  21814. program file name (a string ending in \key{.rkt}), applies all the
  21815. passes and writes the output to a file whose name is the same as the
  21816. program file name with extension \key{.rkt} replaced by \key{.s}.
  21817. \paragraph{\code{read-program}}
  21818. This function takes a file path and parses that file (it must be a
  21819. Racket program) into an abstract syntax tree.
  21820. \paragraph{\code{parse-program}}
  21821. This function takes an S-expression representation of an abstract
  21822. syntax tree and converts it into the struct-based representation.
  21823. \paragraph{\code{assert}}
  21824. This function takes two parameters, a string (\code{msg}) and Boolean
  21825. (\code{bool}), and displays the message \key{msg} if the Boolean
  21826. \key{bool} is false.
  21827. \paragraph{\code{lookup}}
  21828. % remove discussion of lookup? -Jeremy
  21829. This function takes a key and an alist and returns the first value that is
  21830. associated with the given key, if there is one. If not, an error is
  21831. triggered. The alist may contain both immutable pairs (built with
  21832. \key{cons}) and mutable pairs (built with \key{mcons}).
  21833. %The \key{map2} function ...
  21834. \fi} %\racketEd
  21835. \section{x86 Instruction Set Quick Reference}
  21836. \label{sec:x86-quick-reference}
  21837. \index{subject}{x86}
  21838. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21839. do. We write $A \to B$ to mean that the value of $A$ is written into
  21840. location $B$. Address offsets are given in bytes. The instruction
  21841. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21842. registers (such as \code{\%rax}), or memory references (such as
  21843. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21844. reference per instruction. Other operands must be immediates or
  21845. registers.
  21846. \begin{table}[tbp]
  21847. \captionabove{Quick reference for the x86 instructions used in this book.}
  21848. \label{tab:x86-instr}
  21849. \centering
  21850. \begin{tabular}{l|l}
  21851. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21852. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21853. \texttt{negq} $A$ & $- A \to A$ \\
  21854. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21855. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21856. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21857. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21858. \texttt{retq} & Pops the return address and jumps to it. \\
  21859. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21860. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21861. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21862. \texttt{cmpq} $A$, $B$ & \multirow{2}{3.7in}{Compare $A$ and $B$ and set the flag register ($B$ must not be an immediate).} \\
  21863. & \\
  21864. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21865. matches the condition code of the instruction; otherwise go to the
  21866. next instructions. The condition codes are \key{e} for \emph{equal},
  21867. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21868. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21869. \texttt{jl} $L$ & \\
  21870. \texttt{jle} $L$ & \\
  21871. \texttt{jg} $L$ & \\
  21872. \texttt{jge} $L$ & \\
  21873. \texttt{jmp} $L$ & Jump to label $L$. \\
  21874. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21875. \texttt{movzbq} $A$, $B$ &
  21876. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21877. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21878. and the extra bytes of $B$ are set to zero.} \\
  21879. & \\
  21880. & \\
  21881. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21882. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21883. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21884. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21885. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21886. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21887. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21888. description of the condition codes. $A$ must be a single byte register
  21889. (e.g., \texttt{al} or \texttt{cl}).} \\
  21890. \texttt{setl} $A$ & \\
  21891. \texttt{setle} $A$ & \\
  21892. \texttt{setg} $A$ & \\
  21893. \texttt{setge} $A$ &
  21894. \end{tabular}
  21895. \end{table}
  21896. \backmatter
  21897. \addtocontents{toc}{\vspace{11pt}}
  21898. \cleardoublepage % needed for right page number in TOC for References
  21899. %% \nocite{*} is a way to get all the entries in the .bib file to
  21900. %% print in the bibliography:
  21901. \nocite{*}\let\bibname\refname
  21902. \addcontentsline{toc}{fmbm}{\refname}
  21903. \printbibliography
  21904. %\printindex{authors}{Author Index}
  21905. \printindex{subject}{Index}
  21906. \end{document}
  21907. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21908. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21909. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21910. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21911. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21912. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21913. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21914. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21915. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21916. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21917. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21918. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21919. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21920. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21921. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21922. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21923. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21924. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21925. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21926. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21927. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21928. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  21929. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21930. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21931. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21932. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21933. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21934. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21935. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21936. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21937. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21938. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21939. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21940. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21941. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21942. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21943. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21944. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21945. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21946. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21947. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21948. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21949. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21950. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21951. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21952. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21953. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21954. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21955. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21956. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21957. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21958. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21959. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21960. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21961. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21962. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21963. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21964. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21965. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21966. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21967. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21968. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21969. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21970. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21971. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21972. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21973. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21974. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21975. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21976. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21977. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21978. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21979. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21980. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21981. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21982. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21983. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21984. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21985. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21986. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21987. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21988. % LocalWords: pseudocode underapproximation underapproximations LALR
  21989. % LocalWords: semilattices overapproximate incrementing Earley docs
  21990. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21991. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21992. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21993. % LocalWords: LC partialevaluation pythonEd TOC TrappedError