book.tex 836 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. \usepackage[utf8]{inputenc}
  3. %% \usepackage{setspace}
  4. %% \doublespacing
  5. \usepackage{listings}
  6. \usepackage{verbatim}
  7. \usepackage{amssymb}
  8. \usepackage{lmodern} % better typewriter font for code
  9. %\usepackage{wrapfig}
  10. \usepackage{multirow}
  11. \usepackage{tcolorbox}
  12. \usepackage{color}
  13. %\usepackage{ifthen}
  14. \usepackage{upquote}
  15. \usepackage[all]{xy}
  16. \usepackage{url}
  17. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{1}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. %\newcommand{\pythonColor}[0]{\color{purple}}
  29. \newcommand{\pythonColor}[0]{}
  30. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  32. \makeatletter
  33. \newcommand{\captionabove}[2][]{%
  34. \vskip-\abovecaptionskip
  35. \vskip+\belowcaptionskip
  36. \ifx\@nnil#1\@nnil
  37. \caption{#2}%
  38. \else
  39. \caption[#1]{#2}%
  40. \fi
  41. \vskip+\abovecaptionskip
  42. \vskip-\belowcaptionskip
  43. }
  44. %% For multiple indices:
  45. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  46. \makeindex{subject}
  47. %\makeindex{authors}
  48. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  49. \if\edition\racketEd
  50. \lstset{%
  51. language=Lisp,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  54. deletekeywords={read,mapping,vector},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. \if\edition\pythonEd
  62. \lstset{%
  63. language=Python,
  64. basicstyle=\ttfamily\small,
  65. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  66. deletekeywords={},
  67. escapechar=|,
  68. columns=flexible,
  69. %moredelim=[is][\color{red}]{~}{~},
  70. showstringspaces=false
  71. }
  72. \fi
  73. %%% Any shortcut own defined macros place here
  74. %% sample of author macro:
  75. \input{defs}
  76. \newtheorem{exercise}[theorem]{Exercise}
  77. \numberwithin{theorem}{chapter}
  78. \numberwithin{definition}{chapter}
  79. \numberwithin{equation}{chapter}
  80. % Adjusted settings
  81. \setlength{\columnsep}{4pt}
  82. %% \begingroup
  83. %% \setlength{\intextsep}{0pt}%
  84. %% \setlength{\columnsep}{0pt}%
  85. %% \begin{wrapfigure}{r}{0.5\textwidth}
  86. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  87. %% \caption{Basic layout}
  88. %% \end{wrapfigure}
  89. %% \lipsum[1]
  90. %% \endgroup
  91. \def\ShowFrameLinethickness{0.125pt}
  92. \addbibresource{book.bib}
  93. \if\edition\pythonEd
  94. \addbibresource{python.bib}
  95. \fi
  96. \begin{document}
  97. \frontmatter
  98. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  99. \HalfTitle{Essentials of Compilation}
  100. \halftitlepage
  101. \clearemptydoublepage
  102. \Title{Essentials of Compilation}
  103. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  104. %\edition{First Edition}
  105. \BookAuthor{Jeremy G. Siek}
  106. \imprint{The MIT Press\\
  107. Cambridge, Massachusetts\\
  108. London, England}
  109. \begin{copyrightpage}
  110. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  111. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  112. Subject to such license, all rights are reserved. \\[2ex]
  113. \includegraphics{CCBY-logo}
  114. The MIT Press would like to thank the anonymous peer reviewers who
  115. provided comments on drafts of this book. The generous work of
  116. academic experts is essential for establishing the authority and
  117. quality of our publications. We acknowledge with gratitude the
  118. contributions of these otherwise uncredited readers.
  119. This book was set in Times LT Std Roman by the author. Printed and
  120. bound in the United States of America.
  121. {\if\edition\racketEd
  122. Library of Congress Cataloging-in-Publication Data\\
  123. \ \\
  124. Names: Siek, Jeremy, author. \\
  125. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  126. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  127. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  128. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  129. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  130. LC record available at https://lccn.loc.gov/2022015399\\
  131. LC ebook record available at https://lccn.loc.gov/2022015400\\
  132. \ \\
  133. \fi}
  134. %
  135. {\if\edition\pythonEd
  136. Library of Congress Cataloging-in-Publication Data\\
  137. \ \\
  138. Names: Siek, Jeremy, author. \\
  139. Title: Essentials of compilation : an incremental approach in Python / Jeremy G. Siek. \\
  140. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes
  141. bibliographical references and index. \\
  142. Identifiers: LCCN 2022043053 (print) | LCCN 2022043054 (ebook) | ISBN
  143. 9780262048248 | ISBN 9780262375542 (epub) | ISBN 9780262375559 (pdf) \\
  144. Subjects: LCSH: Compilers (Computer programs) | Python (Computer program
  145. language) | Programming languages (Electronic computers) | Computer
  146. programming. \\
  147. Classification: LCC QA76.76.C65 S54 2023 (print) | LCC QA76.76.C65
  148. (ebook) | DDC 005.4/53--dc23/eng/20221117 \\
  149. LC record available at https://lccn.loc.gov/2022043053\\
  150. LC ebook record available at https://lccn.loc.gov/2022043054 \\
  151. \ \\
  152. \fi}
  153. 10 9 8 7 6 5 4 3 2 1
  154. %% Jeremy G. Siek. Available for free viewing
  155. %% or personal downloading under the
  156. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  157. %% license.
  158. %% Copyright in this monograph has been licensed exclusively to The MIT
  159. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  160. %% version to the public in 2022. All inquiries regarding rights should
  161. %% be addressed to The MIT Press, Rights and Permissions Department.
  162. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  163. %% All rights reserved. No part of this book may be reproduced in any
  164. %% form by any electronic or mechanical means (including photocopying,
  165. %% recording, or information storage and retrieval) without permission in
  166. %% writing from the publisher.
  167. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  168. %% United States of America.
  169. %% Library of Congress Cataloging-in-Publication Data is available.
  170. %% ISBN:
  171. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  172. \end{copyrightpage}
  173. \dedication{This book is dedicated to Katie, my partner in everything,
  174. my children, who grew up during the writing of this book, and the
  175. programming language students at Indiana University, whose
  176. thoughtful questions made this a better book.}
  177. %% \begin{epigraphpage}
  178. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  179. %% \textit{Book Name if any}}
  180. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  181. %% \end{epigraphpage}
  182. \tableofcontents
  183. %\listoffigures
  184. %\listoftables
  185. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  186. \chapter*{Preface}
  187. \addcontentsline{toc}{fmbm}{Preface}
  188. There is a magical moment when a programmer presses the \emph{run}
  189. button and the software begins to execute. Somehow a program written
  190. in a high-level language is running on a computer that is capable only
  191. of shuffling bits. Here we reveal the wizardry that makes that moment
  192. possible. Beginning with the groundbreaking work of Backus and
  193. colleagues in the 1950s, computer scientists developed techniques for
  194. constructing programs called \emph{compilers} that automatically
  195. translate high-level programs into machine code.
  196. We take you on a journey through constructing your own compiler for a
  197. small but powerful language. Along the way we explain the essential
  198. concepts, algorithms, and data structures that underlie compilers. We
  199. develop your understanding of how programs are mapped onto computer
  200. hardware, which is helpful in reasoning about properties at the
  201. junction of hardware and software, such as execution time, software
  202. errors, and security vulnerabilities. For those interested in
  203. pursuing compiler construction as a career, our goal is to provide a
  204. stepping-stone to advanced topics such as just-in-time compilation,
  205. program analysis, and program optimization. For those interested in
  206. designing and implementing programming languages, we connect language
  207. design choices to their impact on the compiler and the generated code.
  208. A compiler is typically organized as a sequence of stages that
  209. progressively translate a program to the code that runs on
  210. hardware. We take this approach to the extreme by partitioning our
  211. compiler into a large number of \emph{nanopasses}, each of which
  212. performs a single task. This enables the testing of each pass in
  213. isolation and focuses our attention, making the compiler far easier to
  214. understand.
  215. The most familiar approach to describing compilers is to dedicate each
  216. chapter to one pass. The problem with that approach is that it
  217. obfuscates how language features motivate design choices in a
  218. compiler. We instead take an \emph{incremental} approach in which we
  219. build a complete compiler in each chapter, starting with a small input
  220. language that includes only arithmetic and variables. We add new
  221. language features in subsequent chapters, extending the compiler as
  222. necessary.
  223. Our choice of language features is designed to elicit fundamental
  224. concepts and algorithms used in compilers.
  225. \begin{itemize}
  226. \item We begin with integer arithmetic and local variables in
  227. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  228. the fundamental tools of compiler construction: \emph{abstract
  229. syntax trees} and \emph{recursive functions}.
  230. {\if\edition\pythonEd\pythonColor
  231. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  232. parser framework to create a parser for the language of integer
  233. arithmetic and local variables. We learn about the parsing
  234. algorithms inside Lark, including Earley and LALR(1).
  235. %
  236. \fi}
  237. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  238. \emph{graph coloring} to assign variables to machine registers.
  239. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  240. motivates an elegant recursive algorithm for translating them into
  241. conditional \code{goto} statements.
  242. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  243. variables}. This elicits the need for \emph{dataflow
  244. analysis} in the register allocator.
  245. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  246. \emph{garbage collection}.
  247. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  248. without lexical scoping, similar to functions in the C programming
  249. language~\citep{Kernighan:1988nx}. The reader learns about the
  250. procedure call stack and \emph{calling conventions} and how they interact
  251. with register allocation and garbage collection. The chapter also
  252. describes how to generate efficient tail calls.
  253. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  254. scoping, that is, \emph{lambda} expressions. The reader learns about
  255. \emph{closure conversion}, in which lambdas are translated into a
  256. combination of functions and tuples.
  257. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  258. point the input languages are statically typed. The reader extends
  259. the statically typed language with an \code{Any} type that serves
  260. as a target for compiling the dynamically typed language.
  261. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  262. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  263. in which different regions of a program may be static or dynamically
  264. typed. The reader implements runtime support for \emph{proxies} that
  265. allow values to safely move between regions.
  266. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  267. leveraging the \code{Any} type and type casts developed in chapters
  268. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  269. \end{itemize}
  270. There are many language features that we do not include. Our choices
  271. balance the incidental complexity of a feature versus the fundamental
  272. concepts that it exposes. For example, we include tuples and not
  273. records because although they both elicit the study of heap allocation and
  274. garbage collection, records come with more incidental complexity.
  275. Since 2009, drafts of this book have served as the textbook for
  276. sixteen-week compiler courses for upper-level undergraduates and
  277. first-year graduate students at the University of Colorado and Indiana
  278. University.
  279. %
  280. Students come into the course having learned the basics of
  281. programming, data structures and algorithms, and discrete
  282. mathematics.
  283. %
  284. At the beginning of the course, students form groups of two to four
  285. people. The groups complete approximately one chapter every two
  286. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  287. according to the students interests while respecting the dependencies
  288. between chapters shown in
  289. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  290. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  291. implementation of efficient tail calls.
  292. %
  293. The last two weeks of the course involve a final project in which
  294. students design and implement a compiler extension of their choosing.
  295. The last few chapters can be used in support of these projects. Many
  296. chapters include a challenge problem that we assign to the graduate
  297. students.
  298. For compiler courses at universities on the quarter system
  299. (about ten weeks in length), we recommend completing the course
  300. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  301. some scaffolding code to the students for each compiler pass.
  302. %
  303. The course can be adapted to emphasize functional languages by
  304. skipping chapter~\ref{ch:Lwhile} (loops) and including
  305. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  306. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  307. This book has been used in compiler courses at California Polytechnic
  308. State University, Portland State University, Rose–Hulman Institute of
  309. Technology, University of Freiburg, University of Massachusetts
  310. Lowell, and the University of Vermont.
  311. \begin{figure}[tp]
  312. \begin{tcolorbox}[colback=white]
  313. {\if\edition\racketEd
  314. \begin{tikzpicture}[baseline=(current bounding box.center)]
  315. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  316. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  317. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  318. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  319. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  320. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  321. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  322. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  323. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  324. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  325. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  326. \path[->] (C1) edge [above] node {} (C2);
  327. \path[->] (C2) edge [above] node {} (C3);
  328. \path[->] (C3) edge [above] node {} (C4);
  329. \path[->] (C4) edge [above] node {} (C5);
  330. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  331. \path[->] (C5) edge [above] node {} (C7);
  332. \path[->] (C6) edge [above] node {} (C7);
  333. \path[->] (C4) edge [above] node {} (C8);
  334. \path[->] (C4) edge [above] node {} (C9);
  335. \path[->] (C7) edge [above] node {} (C10);
  336. \path[->] (C8) edge [above] node {} (C10);
  337. \path[->] (C10) edge [above] node {} (C11);
  338. \end{tikzpicture}
  339. \fi}
  340. {\if\edition\pythonEd\pythonColor
  341. \begin{tikzpicture}[baseline=(current bounding box.center)]
  342. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  343. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  344. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  345. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  346. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  347. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  348. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  349. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  350. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  351. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  352. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  353. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  354. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  355. \path[->] (Prelim) edge [above] node {} (Var);
  356. \path[->] (Var) edge [above] node {} (Reg);
  357. \path[->] (Var) edge [above] node {} (Parse);
  358. \path[->] (Reg) edge [above] node {} (Cond);
  359. \path[->] (Cond) edge [above] node {} (Tuple);
  360. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  361. \path[->] (Cond) edge [above] node {} (Fun);
  362. \path[->] (Tuple) edge [above] node {} (Lam);
  363. \path[->] (Fun) edge [above] node {} (Lam);
  364. \path[->] (Cond) edge [above] node {} (Dyn);
  365. \path[->] (Cond) edge [above] node {} (Loop);
  366. \path[->] (Lam) edge [above] node {} (Gradual);
  367. \path[->] (Dyn) edge [above] node {} (Gradual);
  368. % \path[->] (Dyn) edge [above] node {} (CO);
  369. \path[->] (Gradual) edge [above] node {} (Generic);
  370. \end{tikzpicture}
  371. \fi}
  372. \end{tcolorbox}
  373. \caption{Diagram of chapter dependencies.}
  374. \label{fig:chapter-dependences}
  375. \end{figure}
  376. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  377. the implementation of the compiler and for the input language, so the
  378. reader should be proficient with Racket or Scheme. There are many
  379. excellent resources for learning Scheme and
  380. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  381. %
  382. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  383. both for the implementation of the compiler and for the input language, so the
  384. reader should be proficient with Python. There are many
  385. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  386. %
  387. The support code for this book is in the GitHub repository at
  388. the following location:
  389. \begin{center}\small\texttt
  390. https://github.com/IUCompilerCourse/
  391. \end{center}
  392. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  393. is helpful but not necessary for the reader to have taken a computer
  394. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  395. assembly language that are needed in the compiler.
  396. %
  397. We follow the System V calling
  398. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  399. that we generate works with the runtime system (written in C) when it
  400. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  401. operating systems on Intel hardware.
  402. %
  403. On the Windows operating system, \code{gcc} uses the Microsoft x64
  404. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  405. assembly code that we generate does \emph{not} work with the runtime
  406. system on Windows. One workaround is to use a virtual machine with
  407. Linux as the guest operating system.
  408. \section*{Acknowledgments}
  409. The tradition of compiler construction at Indiana University goes back
  410. to research and courses on programming languages by Daniel Friedman in
  411. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  412. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  413. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  414. the compiler course and continued the development of Chez Scheme.
  415. %
  416. The compiler course evolved to incorporate novel pedagogical ideas
  417. while also including elements of real-world compilers. One of
  418. Friedman's ideas was to split the compiler into many small
  419. passes. Another idea, called ``the game,'' was to test the code
  420. generated by each pass using interpreters.
  421. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  422. developed infrastructure to support this approach and evolved the
  423. course to use even smaller
  424. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  425. design decisions in this book are inspired by the assignment
  426. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  427. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  428. organization of the course made it difficult for students to
  429. understand the rationale for the compiler design. Ghuloum proposed the
  430. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  431. based.
  432. I thank the many students who served as teaching assistants for the
  433. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  434. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  435. garbage collector and x86 interpreter, Michael Vollmer for work on
  436. efficient tail calls, and Michael Vitousek for help with the first
  437. offering of the incremental compiler course at IU.
  438. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  439. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  440. Michael Wollowski for teaching courses based on drafts of this book
  441. and for their feedback. I thank the National Science Foundation for
  442. the grants that helped to support this work: Grant Numbers 1518844,
  443. 1763922, and 1814460.
  444. I thank Ronald Garcia for helping me survive Dybvig's compiler
  445. course in the early 2000s and especially for finding the bug that
  446. sent our garbage collector on a wild goose chase!
  447. \mbox{}\\
  448. \noindent Jeremy G. Siek \\
  449. Bloomington, Indiana
  450. \mainmatter
  451. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  452. \chapter{Preliminaries}
  453. \label{ch:trees-recur}
  454. \setcounter{footnote}{0}
  455. In this chapter we introduce the basic tools needed to implement a
  456. compiler. Programs are typically input by a programmer as text, that
  457. is, a sequence of characters. The program-as-text representation is
  458. called \emph{concrete syntax}. We use concrete syntax to concisely
  459. write down and talk about programs. Inside the compiler, we use
  460. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  461. that efficiently supports the operations that the compiler needs to
  462. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  463. syntax}\index{subject}{abstract syntax
  464. tree}\index{subject}{AST}\index{subject}{program}
  465. The process of translating concrete syntax to abstract syntax is
  466. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  467. chapter~\ref{ch:parsing}}.
  468. \racket{This book does not cover the theory and implementation of parsing.
  469. We refer the readers interested in parsing to the thorough treatment
  470. of parsing by \citet{Aho:2006wb}. }%
  471. %
  472. \racket{A parser is provided in the support code for translating from
  473. concrete to abstract syntax.}%
  474. %
  475. \python{For now we use the \code{parse} function in Python's
  476. \code{ast} module to translate from concrete to abstract syntax.}
  477. ASTs can be represented inside the compiler in many different ways,
  478. depending on the programming language used to write the compiler.
  479. %
  480. \racket{We use Racket's
  481. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  482. feature to represent ASTs (section~\ref{sec:ast}).}
  483. %
  484. \python{We use Python classes and objects to represent ASTs, especially the
  485. classes defined in the standard \code{ast} module for the Python
  486. source language.}
  487. %
  488. We use grammars to define the abstract syntax of programming languages
  489. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  490. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  491. recursive functions to construct and deconstruct ASTs
  492. (section~\ref{sec:recursion}). This chapter provides a brief
  493. introduction to these components.
  494. \racket{\index{subject}{struct}}
  495. \python{\index{subject}{class}\index{subject}{object}}
  496. \section{Abstract Syntax Trees}
  497. \label{sec:ast}
  498. Compilers use abstract syntax trees to represent programs because they
  499. often need to ask questions such as, for a given part of a program,
  500. what kind of language feature is it? What are its subparts? Consider
  501. the program on the left and the diagram of its AST on the
  502. right~\eqref{eq:arith-prog}. This program is an addition operation
  503. that has two subparts, a \racket{read}\python{input} operation and a
  504. negation. The negation has another subpart, the integer constant
  505. \code{8}. By using a tree to represent the program, we can easily
  506. follow the links to go from one part of a program to its subparts.
  507. \begin{center}
  508. \begin{minipage}{0.4\textwidth}
  509. {\if\edition\racketEd
  510. \begin{lstlisting}
  511. (+ (read) (- 8))
  512. \end{lstlisting}
  513. \fi}
  514. {\if\edition\pythonEd\pythonColor
  515. \begin{lstlisting}
  516. input_int() + -8
  517. \end{lstlisting}
  518. \fi}
  519. \end{minipage}
  520. \begin{minipage}{0.4\textwidth}
  521. \begin{equation}
  522. \begin{tikzpicture}
  523. \node[draw] (plus) at (0 , 0) {\key{+}};
  524. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  525. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  526. \node[draw] (8) at (1 , -2) {\key{8}};
  527. \draw[->] (plus) to (read);
  528. \draw[->] (plus) to (minus);
  529. \draw[->] (minus) to (8);
  530. \end{tikzpicture}
  531. \label{eq:arith-prog}
  532. \end{equation}
  533. \end{minipage}
  534. \end{center}
  535. We use the standard terminology for trees to describe ASTs: each
  536. rectangle above is called a \emph{node}. The arrows connect a node to its
  537. \emph{children}, which are also nodes. The top-most node is the
  538. \emph{root}. Every node except for the root has a \emph{parent} (the
  539. node of which it is the child). If a node has no children, it is a
  540. \emph{leaf} node; otherwise it is an \emph{internal} node.
  541. \index{subject}{node}
  542. \index{subject}{children}
  543. \index{subject}{root}
  544. \index{subject}{parent}
  545. \index{subject}{leaf}
  546. \index{subject}{internal node}
  547. %% Recall that an \emph{symbolic expression} (S-expression) is either
  548. %% \begin{enumerate}
  549. %% \item an atom, or
  550. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  551. %% where $e_1$ and $e_2$ are each an S-expression.
  552. %% \end{enumerate}
  553. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  554. %% null value \code{'()}, etc. We can create an S-expression in Racket
  555. %% simply by writing a backquote (called a quasi-quote in Racket)
  556. %% followed by the textual representation of the S-expression. It is
  557. %% quite common to use S-expressions to represent a list, such as $a, b
  558. %% ,c$ in the following way:
  559. %% \begin{lstlisting}
  560. %% `(a . (b . (c . ())))
  561. %% \end{lstlisting}
  562. %% Each element of the list is in the first slot of a pair, and the
  563. %% second slot is either the rest of the list or the null value, to mark
  564. %% the end of the list. Such lists are so common that Racket provides
  565. %% special notation for them that removes the need for the periods
  566. %% and so many parenthesis:
  567. %% \begin{lstlisting}
  568. %% `(a b c)
  569. %% \end{lstlisting}
  570. %% The following expression creates an S-expression that represents AST
  571. %% \eqref{eq:arith-prog}.
  572. %% \begin{lstlisting}
  573. %% `(+ (read) (- 8))
  574. %% \end{lstlisting}
  575. %% When using S-expressions to represent ASTs, the convention is to
  576. %% represent each AST node as a list and to put the operation symbol at
  577. %% the front of the list. The rest of the list contains the children. So
  578. %% in the above case, the root AST node has operation \code{`+} and its
  579. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  580. %% diagram \eqref{eq:arith-prog}.
  581. %% To build larger S-expressions one often needs to splice together
  582. %% several smaller S-expressions. Racket provides the comma operator to
  583. %% splice an S-expression into a larger one. For example, instead of
  584. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  585. %% we could have first created an S-expression for AST
  586. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  587. %% S-expression.
  588. %% \begin{lstlisting}
  589. %% (define ast1.4 `(- 8))
  590. %% (define ast1_1 `(+ (read) ,ast1.4))
  591. %% \end{lstlisting}
  592. %% In general, the Racket expression that follows the comma (splice)
  593. %% can be any expression that produces an S-expression.
  594. {\if\edition\racketEd
  595. We define a Racket \code{struct} for each kind of node. For this
  596. chapter we require just two kinds of nodes: one for integer constants
  597. (aka literals\index{subject}{literals})
  598. and one for primitive operations. The following is the \code{struct}
  599. definition for integer constants.\footnote{All the AST structures are
  600. defined in the file \code{utilities.rkt} in the support code.}
  601. \begin{lstlisting}
  602. (struct Int (value))
  603. \end{lstlisting}
  604. An integer node contains just one thing: the integer value.
  605. We establish the convention that \code{struct} names, such
  606. as \code{Int}, are capitalized.
  607. To create an AST node for the integer $8$, we write \INT{8}.
  608. \begin{lstlisting}
  609. (define eight (Int 8))
  610. \end{lstlisting}
  611. We say that the value created by \INT{8} is an
  612. \emph{instance} of the
  613. \code{Int} structure.
  614. The following is the \code{struct} definition for primitive operations.
  615. \begin{lstlisting}
  616. (struct Prim (op args))
  617. \end{lstlisting}
  618. A primitive operation node includes an operator symbol \code{op} and a
  619. list of child arguments called \code{args}. For example, to create an
  620. AST that negates the number $8$, we write the following.
  621. \begin{lstlisting}
  622. (define neg-eight (Prim '- (list eight)))
  623. \end{lstlisting}
  624. Primitive operations may have zero or more children. The \code{read}
  625. operator has zero:
  626. \begin{lstlisting}
  627. (define rd (Prim 'read '()))
  628. \end{lstlisting}
  629. The addition operator has two children:
  630. \begin{lstlisting}
  631. (define ast1_1 (Prim '+ (list rd neg-eight)))
  632. \end{lstlisting}
  633. We have made a design choice regarding the \code{Prim} structure.
  634. Instead of using one structure for many different operations
  635. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  636. structure for each operation, as follows:
  637. \begin{lstlisting}
  638. (struct Read ())
  639. (struct Add (left right))
  640. (struct Neg (value))
  641. \end{lstlisting}
  642. The reason that we choose to use just one structure is that many parts
  643. of the compiler can use the same code for the different primitive
  644. operators, so we might as well just write that code once by using a
  645. single structure.
  646. %
  647. \fi}
  648. {\if\edition\pythonEd\pythonColor
  649. We use a Python \code{class} for each kind of node.
  650. The following is the class definition for
  651. constants (aka literals\index{subject}{literals})
  652. from the Python \code{ast} module.
  653. \begin{lstlisting}
  654. class Constant:
  655. def __init__(self, value):
  656. self.value = value
  657. \end{lstlisting}
  658. An integer constant node includes just one thing: the integer value.
  659. To create an AST node for the integer $8$, we write \INT{8}.
  660. \begin{lstlisting}
  661. eight = Constant(8)
  662. \end{lstlisting}
  663. We say that the value created by \INT{8} is an
  664. \emph{instance} of the \code{Constant} class.
  665. The following is the class definition for unary operators.
  666. \begin{lstlisting}
  667. class UnaryOp:
  668. def __init__(self, op, operand):
  669. self.op = op
  670. self.operand = operand
  671. \end{lstlisting}
  672. The specific operation is specified by the \code{op} parameter. For
  673. example, the class \code{USub} is for unary subtraction.
  674. (More unary operators are introduced in later chapters.) To create an AST that
  675. negates the number $8$, we write the following.
  676. \begin{lstlisting}
  677. neg_eight = UnaryOp(USub(), eight)
  678. \end{lstlisting}
  679. The call to the \code{input\_int} function is represented by the
  680. \code{Call} and \code{Name} classes.
  681. \begin{lstlisting}
  682. class Call:
  683. def __init__(self, func, args):
  684. self.func = func
  685. self.args = args
  686. class Name:
  687. def __init__(self, id):
  688. self.id = id
  689. \end{lstlisting}
  690. To create an AST node that calls \code{input\_int}, we write
  691. \begin{lstlisting}
  692. read = Call(Name('input_int'), [])
  693. \end{lstlisting}
  694. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  695. the \code{BinOp} class for binary operators.
  696. \begin{lstlisting}
  697. class BinOp:
  698. def __init__(self, left, op, right):
  699. self.op = op
  700. self.left = left
  701. self.right = right
  702. \end{lstlisting}
  703. Similar to \code{UnaryOp}, the specific operation is specified by the
  704. \code{op} parameter, which for now is just an instance of the
  705. \code{Add} class. So to create the AST
  706. node that adds negative eight to some user input, we write the following.
  707. \begin{lstlisting}
  708. ast1_1 = BinOp(read, Add(), neg_eight)
  709. \end{lstlisting}
  710. \fi}
  711. To compile a program such as \eqref{eq:arith-prog}, we need to know
  712. that the operation associated with the root node is addition and we
  713. need to be able to access its two
  714. children. \racket{Racket}\python{Python} provides pattern matching to
  715. support these kinds of queries, as we see in
  716. section~\ref{sec:pattern-matching}.
  717. We often write down the concrete syntax of a program even when we
  718. actually have in mind the AST, because the concrete syntax is more
  719. concise. We recommend that you always think of programs as abstract
  720. syntax trees.
  721. \section{Grammars}
  722. \label{sec:grammar}
  723. \index{subject}{integer}
  724. %\index{subject}{constant}
  725. A programming language can be thought of as a \emph{set} of programs.
  726. The set is infinite (that is, one can always create larger programs),
  727. so one cannot simply describe a language by listing all the
  728. programs in the language. Instead we write down a set of rules, a
  729. \emph{context-free grammar}, for building programs. Grammars are often used to
  730. define the concrete syntax of a language, but they can also be used to
  731. describe the abstract syntax. We write our rules in a variant of
  732. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  733. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  734. we describe a small language, named \LangInt{}, that consists of
  735. integers and arithmetic operations.\index{subject}{grammar}
  736. \index{subject}{context-free grammar}
  737. The first grammar rule for the abstract syntax of \LangInt{} says that an
  738. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  739. \begin{equation}
  740. \Exp ::= \INT{\Int} \label{eq:arith-int}
  741. \end{equation}
  742. %
  743. Each rule has a left-hand side and a right-hand side.
  744. If you have an AST node that matches the
  745. right-hand side, then you can categorize it according to the
  746. left-hand side.
  747. %
  748. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  749. are \emph{terminal} symbols and must literally appear in the program for the
  750. rule to be applicable.\index{subject}{terminal}
  751. %
  752. Our grammars do not mention \emph{white space}, that is, delimiter
  753. characters like spaces, tabs, and new lines. White space may be
  754. inserted between symbols for disambiguation and to improve
  755. readability. \index{subject}{white space}
  756. %
  757. A name such as $\Exp$ that is defined by the grammar rules is a
  758. \emph{nonterminal}. \index{subject}{nonterminal}
  759. %
  760. The name $\Int$ is also a nonterminal, but instead of defining it with
  761. a grammar rule, we define it with the following explanation. An
  762. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  763. $-$ (for negative integers), such that the sequence of decimals
  764. %
  765. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  766. enables the representation of integers using 63 bits, which simplifies
  767. several aspects of compilation.
  768. %
  769. Thus, these integers correspond to the Racket \texttt{fixnum}
  770. datatype on a 64-bit machine.}
  771. %
  772. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  773. enables the representation of integers using 64 bits, which simplifies
  774. several aspects of compilation. In contrast, integers in Python have
  775. unlimited precision, but the techniques needed to handle unlimited
  776. precision fall outside the scope of this book.}
  777. The second grammar rule is the \READOP{} operation, which receives an
  778. input integer from the user of the program.
  779. \begin{equation}
  780. \Exp ::= \READ{} \label{eq:arith-read}
  781. \end{equation}
  782. The third rule categorizes the negation of an $\Exp$ node as an
  783. $\Exp$.
  784. \begin{equation}
  785. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  786. \end{equation}
  787. We can apply these rules to categorize the ASTs that are in the
  788. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  789. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  790. following AST is an $\Exp$.
  791. \begin{center}
  792. \begin{minipage}{0.5\textwidth}
  793. \NEG{\INT{\code{8}}}
  794. \end{minipage}
  795. \begin{minipage}{0.25\textwidth}
  796. \begin{equation}
  797. \begin{tikzpicture}
  798. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  799. \node[draw, circle] (8) at (0, -1.2) {$8$};
  800. \draw[->] (minus) to (8);
  801. \end{tikzpicture}
  802. \label{eq:arith-neg8}
  803. \end{equation}
  804. \end{minipage}
  805. \end{center}
  806. The next two grammar rules are for addition and subtraction expressions:
  807. \begin{align}
  808. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  809. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  810. \end{align}
  811. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  812. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  813. \eqref{eq:arith-read}, and we have already categorized
  814. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  815. to show that
  816. \[
  817. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  818. \]
  819. is an $\Exp$ in the \LangInt{} language.
  820. If you have an AST for which these rules do not apply, then the
  821. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  822. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  823. because there is no rule for the \key{*} operator. Whenever we
  824. define a language with a grammar, the language includes only those
  825. programs that are justified by the grammar rules.
  826. {\if\edition\pythonEd\pythonColor
  827. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  828. There is a statement for printing the value of an expression
  829. \[
  830. \Stmt{} ::= \PRINT{\Exp}
  831. \]
  832. and a statement that evaluates an expression but ignores the result.
  833. \[
  834. \Stmt{} ::= \EXPR{\Exp}
  835. \]
  836. \fi}
  837. {\if\edition\racketEd
  838. The last grammar rule for \LangInt{} states that there is a
  839. \code{Program} node to mark the top of the whole program:
  840. \[
  841. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  842. \]
  843. The \code{Program} structure is defined as follows:
  844. \begin{lstlisting}
  845. (struct Program (info body))
  846. \end{lstlisting}
  847. where \code{body} is an expression. In further chapters, the \code{info}
  848. part is used to store auxiliary information, but for now it is
  849. just the empty list.
  850. \fi}
  851. {\if\edition\pythonEd\pythonColor
  852. The last grammar rule for \LangInt{} states that there is a
  853. \code{Module} node to mark the top of the whole program:
  854. \[
  855. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  856. \]
  857. The asterisk $*$ indicates a list of the preceding grammar item, in
  858. this case a list of statements.
  859. %
  860. The \code{Module} class is defined as follows:
  861. \begin{lstlisting}
  862. class Module:
  863. def __init__(self, body):
  864. self.body = body
  865. \end{lstlisting}
  866. where \code{body} is a list of statements.
  867. \fi}
  868. It is common to have many grammar rules with the same left-hand side
  869. but different right-hand sides, such as the rules for $\Exp$ in the
  870. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  871. combine several right-hand sides into a single rule.
  872. The concrete syntax for \LangInt{} is shown in
  873. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  874. \LangInt{} is shown in figure~\ref{fig:r0-syntax}. %
  875. %
  876. \racket{The \code{read-program} function provided in
  877. \code{utilities.rkt} of the support code reads a program from a file
  878. (the sequence of characters in the concrete syntax of Racket) and
  879. parses it into an abstract syntax tree. Refer to the description of
  880. \code{read-program} in appendix~\ref{appendix:utilities} for more
  881. details.}
  882. %
  883. \python{We recommend using the \code{parse} function in Python's
  884. \code{ast} module to convert the concrete syntax into an abstract
  885. syntax tree.}
  886. \newcommand{\LintGrammarRacket}{
  887. \begin{array}{rcl}
  888. \Type &::=& \key{Integer} \\
  889. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  890. \MID \CSUB{\Exp}{\Exp}
  891. \end{array}
  892. }
  893. \newcommand{\LintASTRacket}{
  894. \begin{array}{rcl}
  895. \Type &::=& \key{Integer} \\
  896. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  897. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  898. \end{array}
  899. }
  900. \newcommand{\LintGrammarPython}{
  901. \begin{array}{rcl}
  902. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  903. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  904. \end{array}
  905. }
  906. \newcommand{\LintASTPython}{
  907. \begin{array}{rcl}
  908. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  909. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  910. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  911. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  912. \end{array}
  913. }
  914. \begin{figure}[tp]
  915. \begin{tcolorbox}[colback=white]
  916. {\if\edition\racketEd
  917. \[
  918. \begin{array}{l}
  919. \LintGrammarRacket \\
  920. \begin{array}{rcl}
  921. \LangInt{} &::=& \Exp
  922. \end{array}
  923. \end{array}
  924. \]
  925. \fi}
  926. {\if\edition\pythonEd\pythonColor
  927. \[
  928. \begin{array}{l}
  929. \LintGrammarPython \\
  930. \begin{array}{rcl}
  931. \LangInt{} &::=& \Stmt^{*}
  932. \end{array}
  933. \end{array}
  934. \]
  935. \fi}
  936. \end{tcolorbox}
  937. \caption{The concrete syntax of \LangInt{}.}
  938. \label{fig:r0-concrete-syntax}
  939. \index{subject}{Lint@\LangInt{} concrete syntax}
  940. \end{figure}
  941. \begin{figure}[tp]
  942. \begin{tcolorbox}[colback=white]
  943. {\if\edition\racketEd
  944. \[
  945. \begin{array}{l}
  946. \LintASTRacket{} \\
  947. \begin{array}{rcl}
  948. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  949. \end{array}
  950. \end{array}
  951. \]
  952. \fi}
  953. {\if\edition\pythonEd\pythonColor
  954. \[
  955. \begin{array}{l}
  956. \LintASTPython\\
  957. \begin{array}{rcl}
  958. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  959. \end{array}
  960. \end{array}
  961. \]
  962. \fi}
  963. \end{tcolorbox}
  964. \python{
  965. \index{subject}{Constant@\texttt{Constant}}
  966. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  967. \index{subject}{USub@\texttt{USub}}
  968. \index{subject}{inputint@\texttt{input\_int}}
  969. \index{subject}{Call@\texttt{Call}}
  970. \index{subject}{Name@\texttt{Name}}
  971. \index{subject}{BinOp@\texttt{BinOp}}
  972. \index{subject}{Add@\texttt{Add}}
  973. \index{subject}{Sub@\texttt{Sub}}
  974. \index{subject}{print@\texttt{print}}
  975. \index{subject}{Expr@\texttt{Expr}}
  976. \index{subject}{Module@\texttt{Module}}
  977. }
  978. \caption{The abstract syntax of \LangInt{}.}
  979. \label{fig:r0-syntax}
  980. \index{subject}{Lint@\LangInt{} abstract syntax}
  981. \end{figure}
  982. \section{Pattern Matching}
  983. \label{sec:pattern-matching}
  984. As mentioned in section~\ref{sec:ast}, compilers often need to access
  985. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  986. provides the \texttt{match} feature to access the parts of a value.
  987. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  988. \begin{center}
  989. \begin{minipage}{1.0\textwidth}
  990. {\if\edition\racketEd
  991. \begin{lstlisting}
  992. (match ast1_1
  993. [(Prim op (list child1 child2))
  994. (print op)])
  995. \end{lstlisting}
  996. \fi}
  997. {\if\edition\pythonEd\pythonColor
  998. \begin{lstlisting}
  999. match ast1_1:
  1000. case BinOp(child1, op, child2):
  1001. print(op)
  1002. \end{lstlisting}
  1003. \fi}
  1004. \end{minipage}
  1005. \end{center}
  1006. {\if\edition\racketEd
  1007. %
  1008. In this example, the \texttt{match} form checks whether the AST
  1009. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1010. three pattern variables \texttt{op}, \texttt{child1}, and
  1011. \texttt{child2}. In general, a match clause consists of a
  1012. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1013. recursively defined to be a pattern variable, a structure name
  1014. followed by a pattern for each of the structure's arguments, or an
  1015. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1016. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1017. and chapter 9 of The Racket
  1018. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1019. for complete descriptions of \code{match}.)
  1020. %
  1021. The body of a match clause may contain arbitrary Racket code. The
  1022. pattern variables can be used in the scope of the body, such as
  1023. \code{op} in \code{(print op)}.
  1024. %
  1025. \fi}
  1026. %
  1027. %
  1028. {\if\edition\pythonEd\pythonColor
  1029. %
  1030. In the example above, the \texttt{match} form checks whether the AST
  1031. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1032. three pattern variables (\texttt{child1}, \texttt{op}, and
  1033. \texttt{child2}). In general, each \code{case} consists of a
  1034. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1035. recursively defined to be one of the following: a pattern variable, a
  1036. class name followed by a pattern for each of its constructor's
  1037. arguments, or other literals\index{subject}{literals} such as strings
  1038. or lists.
  1039. %
  1040. The body of each \code{case} may contain arbitrary Python code. The
  1041. pattern variables can be used in the body, such as \code{op} in
  1042. \code{print(op)}.
  1043. %
  1044. \fi}
  1045. A \code{match} form may contain several clauses, as in the following
  1046. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1047. the AST. The \code{match} proceeds through the clauses in order,
  1048. checking whether the pattern can match the input AST. The body of the
  1049. first clause that matches is executed. The output of \code{leaf} for
  1050. several ASTs is shown on the right side of the following:
  1051. \begin{center}
  1052. \begin{minipage}{0.6\textwidth}
  1053. {\if\edition\racketEd
  1054. \begin{lstlisting}
  1055. (define (leaf arith)
  1056. (match arith
  1057. [(Int n) #t]
  1058. [(Prim 'read '()) #t]
  1059. [(Prim '- (list e1)) #f]
  1060. [(Prim '+ (list e1 e2)) #f]
  1061. [(Prim '- (list e1 e2)) #f]))
  1062. (leaf (Prim 'read '()))
  1063. (leaf (Prim '- (list (Int 8))))
  1064. (leaf (Int 8))
  1065. \end{lstlisting}
  1066. \fi}
  1067. {\if\edition\pythonEd\pythonColor
  1068. \begin{lstlisting}
  1069. def leaf(arith):
  1070. match arith:
  1071. case Constant(n):
  1072. return True
  1073. case Call(Name('input_int'), []):
  1074. return True
  1075. case UnaryOp(USub(), e1):
  1076. return False
  1077. case BinOp(e1, Add(), e2):
  1078. return False
  1079. case BinOp(e1, Sub(), e2):
  1080. return False
  1081. print(leaf(Call(Name('input_int'), [])))
  1082. print(leaf(UnaryOp(USub(), eight)))
  1083. print(leaf(Constant(8)))
  1084. \end{lstlisting}
  1085. \fi}
  1086. \end{minipage}
  1087. \vrule
  1088. \begin{minipage}{0.25\textwidth}
  1089. {\if\edition\racketEd
  1090. \begin{lstlisting}
  1091. #t
  1092. #f
  1093. #t
  1094. \end{lstlisting}
  1095. \fi}
  1096. {\if\edition\pythonEd\pythonColor
  1097. \begin{lstlisting}
  1098. True
  1099. False
  1100. True
  1101. \end{lstlisting}
  1102. \fi}
  1103. \end{minipage}
  1104. \index{subject}{True@\TRUE{}}
  1105. \index{subject}{False@\FALSE{}}
  1106. \end{center}
  1107. When constructing a \code{match} expression, we refer to the grammar
  1108. definition to identify which nonterminal we are expecting to match
  1109. against, and then we make sure that (1) we have one
  1110. \racket{clause}\python{case} for each alternative of that nonterminal
  1111. and (2) the pattern in each \racket{clause}\python{case}
  1112. corresponds to the corresponding right-hand side of a grammar
  1113. rule. For the \code{match} in the \code{leaf} function, we refer to
  1114. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1115. nonterminal has five alternatives, so the \code{match} has five
  1116. \racket{clauses}\python{cases}. The pattern in each
  1117. \racket{clause}\python{case} corresponds to the right-hand side of a
  1118. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1119. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1120. translating from grammars to patterns, replace nonterminals such as
  1121. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1122. \code{e2}).
  1123. \section{Recursive Functions}
  1124. \label{sec:recursion}
  1125. \index{subject}{recursive function}
  1126. Programs are inherently recursive. For example, an expression is often
  1127. made of smaller expressions. Thus, the natural way to process an
  1128. entire program is to use a recursive function. As a first example of
  1129. such a recursive function, we define the function \code{is\_exp} as
  1130. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1131. value and determine whether or not it is an expression in \LangInt{}.
  1132. %
  1133. We say that a function is defined by \emph{structural recursion} if
  1134. it is defined using a sequence of match \racket{clauses}\python{cases}
  1135. that correspond to a grammar and the body of each
  1136. \racket{clause}\python{case} makes a recursive call on each child
  1137. node.\footnote{This principle of structuring code according to the
  1138. data definition is advocated in the book \emph{How to Design
  1139. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1140. second function, named \code{is\_stmt}, that recognizes whether a value
  1141. is a \LangInt{} statement.} \python{Finally, }
  1142. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1143. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1144. In general, we can write one recursive function to handle each
  1145. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1146. two examples at the bottom of the figure, the first is in
  1147. \LangInt{} and the second is not.
  1148. \begin{figure}[tp]
  1149. \begin{tcolorbox}[colback=white]
  1150. {\if\edition\racketEd
  1151. \begin{lstlisting}
  1152. (define (is_exp ast)
  1153. (match ast
  1154. [(Int n) #t]
  1155. [(Prim 'read '()) #t]
  1156. [(Prim '- (list e)) (is_exp e)]
  1157. [(Prim '+ (list e1 e2))
  1158. (and (is_exp e1) (is_exp e2))]
  1159. [(Prim '- (list e1 e2))
  1160. (and (is_exp e1) (is_exp e2))]
  1161. [else #f]))
  1162. (define (is_Lint ast)
  1163. (match ast
  1164. [(Program '() e) (is_exp e)]
  1165. [else #f]))
  1166. (is_Lint (Program '() ast1_1))
  1167. (is_Lint (Program '()
  1168. (Prim '* (list (Prim 'read '())
  1169. (Prim '+ (list (Int 8)))))))
  1170. \end{lstlisting}
  1171. \fi}
  1172. {\if\edition\pythonEd\pythonColor
  1173. \begin{lstlisting}
  1174. def is_exp(e):
  1175. match e:
  1176. case Constant(n):
  1177. return True
  1178. case Call(Name('input_int'), []):
  1179. return True
  1180. case UnaryOp(USub(), e1):
  1181. return is_exp(e1)
  1182. case BinOp(e1, Add(), e2):
  1183. return is_exp(e1) and is_exp(e2)
  1184. case BinOp(e1, Sub(), e2):
  1185. return is_exp(e1) and is_exp(e2)
  1186. case _:
  1187. return False
  1188. def is_stmt(s):
  1189. match s:
  1190. case Expr(Call(Name('print'), [e])):
  1191. return is_exp(e)
  1192. case Expr(e):
  1193. return is_exp(e)
  1194. case _:
  1195. return False
  1196. def is_Lint(p):
  1197. match p:
  1198. case Module(body):
  1199. return all([is_stmt(s) for s in body])
  1200. case _:
  1201. return False
  1202. print(is_Lint(Module([Expr(ast1_1)])))
  1203. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1204. UnaryOp(Add(), Constant(8))))])))
  1205. \end{lstlisting}
  1206. \fi}
  1207. \end{tcolorbox}
  1208. \caption{Example of recursive functions for \LangInt{}. These functions
  1209. recognize whether an AST is in \LangInt{}.}
  1210. \label{fig:exp-predicate}
  1211. \end{figure}
  1212. %% You may be tempted to merge the two functions into one, like this:
  1213. %% \begin{center}
  1214. %% \begin{minipage}{0.5\textwidth}
  1215. %% \begin{lstlisting}
  1216. %% (define (Lint ast)
  1217. %% (match ast
  1218. %% [(Int n) #t]
  1219. %% [(Prim 'read '()) #t]
  1220. %% [(Prim '- (list e)) (Lint e)]
  1221. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1222. %% [(Program '() e) (Lint e)]
  1223. %% [else #f]))
  1224. %% \end{lstlisting}
  1225. %% \end{minipage}
  1226. %% \end{center}
  1227. %% %
  1228. %% Sometimes such a trick will save a few lines of code, especially when
  1229. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1230. %% \emph{not} recommended because it can get you into trouble.
  1231. %% %
  1232. %% For example, the above function is subtly wrong:
  1233. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1234. %% returns true when it should return false.
  1235. \section{Interpreters}
  1236. \label{sec:interp_Lint}
  1237. \index{subject}{interpreter}
  1238. The behavior of a program is defined by the specification of the
  1239. programming language.
  1240. %
  1241. \racket{For example, the Scheme language is defined in the report by
  1242. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1243. reference manual~\citep{plt-tr}.}
  1244. %
  1245. \python{For example, the Python language is defined in the Python
  1246. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1247. %
  1248. In this book we use interpreters to specify each language that we
  1249. consider. An interpreter that is designated as the definition of a
  1250. language is called a \emph{definitional
  1251. interpreter}~\citep{reynolds72:_def_interp}.
  1252. \index{subject}{definitional interpreter} We warm up by creating a
  1253. definitional interpreter for the \LangInt{} language. This interpreter
  1254. serves as a second example of structural recursion. The definition of the
  1255. \code{interp\_Lint} function is shown in
  1256. figure~\ref{fig:interp_Lint}.
  1257. %
  1258. \racket{The body of the function is a match on the input program
  1259. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1260. which in turn has one match clause per grammar rule for \LangInt{}
  1261. expressions.}
  1262. %
  1263. \python{The body of the function matches on the \code{Module} AST node
  1264. and then invokes \code{interp\_stmt} on each statement in the
  1265. module. The \code{interp\_stmt} function includes a case for each
  1266. grammar rule of the \Stmt{} nonterminal, and it calls
  1267. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1268. function includes a case for each grammar rule of the \Exp{}
  1269. nonterminal. We use several auxiliary functions such as \code{add64}
  1270. and \code{input\_int} that are defined in the support code for this book.}
  1271. \begin{figure}[tp]
  1272. \begin{tcolorbox}[colback=white]
  1273. {\if\edition\racketEd
  1274. \begin{lstlisting}
  1275. (define (interp_exp e)
  1276. (match e
  1277. [(Int n) n]
  1278. [(Prim 'read '())
  1279. (define r (read))
  1280. (cond [(fixnum? r) r]
  1281. [else (error 'interp_exp "read expected an integer: ~v" r)])]
  1282. [(Prim '- (list e))
  1283. (define v (interp_exp e))
  1284. (fx- 0 v)]
  1285. [(Prim '+ (list e1 e2))
  1286. (define v1 (interp_exp e1))
  1287. (define v2 (interp_exp e2))
  1288. (fx+ v1 v2)]
  1289. [(Prim '- (list e1 e2))
  1290. (define v1 (interp_exp e1))
  1291. (define v2 (interp_exp e2))
  1292. (fx- v1 v2)]))
  1293. (define (interp_Lint p)
  1294. (match p
  1295. [(Program '() e) (interp_exp e)]))
  1296. \end{lstlisting}
  1297. \fi}
  1298. {\if\edition\pythonEd\pythonColor
  1299. \begin{lstlisting}
  1300. def interp_exp(e):
  1301. match e:
  1302. case BinOp(left, Add(), right):
  1303. l = interp_exp(left); r = interp_exp(right)
  1304. return add64(l, r)
  1305. case BinOp(left, Sub(), right):
  1306. l = interp_exp(left); r = interp_exp(right)
  1307. return sub64(l, r)
  1308. case UnaryOp(USub(), v):
  1309. return neg64(interp_exp(v))
  1310. case Constant(value):
  1311. return value
  1312. case Call(Name('input_int'), []):
  1313. return input_int()
  1314. def interp_stmt(s):
  1315. match s:
  1316. case Expr(Call(Name('print'), [arg])):
  1317. print(interp_exp(arg))
  1318. case Expr(value):
  1319. interp_exp(value)
  1320. def interp_Lint(p):
  1321. match p:
  1322. case Module(body):
  1323. for s in body:
  1324. interp_stmt(s)
  1325. \end{lstlisting}
  1326. \fi}
  1327. \end{tcolorbox}
  1328. \caption{Interpreter for the \LangInt{} language.}
  1329. \label{fig:interp_Lint}
  1330. \end{figure}
  1331. Let us consider the result of interpreting a few \LangInt{} programs. The
  1332. following program adds two integers:
  1333. {\if\edition\racketEd
  1334. \begin{lstlisting}
  1335. (+ 10 32)
  1336. \end{lstlisting}
  1337. \fi}
  1338. {\if\edition\pythonEd\pythonColor
  1339. \begin{lstlisting}
  1340. print(10 + 32)
  1341. \end{lstlisting}
  1342. \fi}
  1343. %
  1344. \noindent The result is \key{42}, the answer to life, the universe,
  1345. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1346. the Galaxy} by Douglas Adams.}
  1347. %
  1348. We wrote this program in concrete syntax, whereas the parsed
  1349. abstract syntax is
  1350. {\if\edition\racketEd
  1351. \begin{lstlisting}
  1352. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1353. \end{lstlisting}
  1354. \fi}
  1355. {\if\edition\pythonEd\pythonColor
  1356. \begin{lstlisting}
  1357. Module([Expr(Call(Name('print'),
  1358. [BinOp(Constant(10), Add(), Constant(32))]))])
  1359. \end{lstlisting}
  1360. \fi}
  1361. The following program demonstrates that expressions may be nested within
  1362. each other, in this case nesting several additions and negations.
  1363. {\if\edition\racketEd
  1364. \begin{lstlisting}
  1365. (+ 10 (- (+ 12 20)))
  1366. \end{lstlisting}
  1367. \fi}
  1368. {\if\edition\pythonEd\pythonColor
  1369. \begin{lstlisting}
  1370. print(10 + -(12 + 20))
  1371. \end{lstlisting}
  1372. \fi}
  1373. %
  1374. \noindent What is the result of this program?
  1375. {\if\edition\racketEd
  1376. As mentioned previously, the \LangInt{} language does not support
  1377. arbitrarily large integers but only $63$-bit integers, so we
  1378. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1379. in Racket.
  1380. Suppose that
  1381. \[
  1382. n = 999999999999999999
  1383. \]
  1384. which indeed fits in $63$ bits. What happens when we run the
  1385. following program in our interpreter?
  1386. \begin{lstlisting}
  1387. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1388. \end{lstlisting}
  1389. It produces the following error:
  1390. \begin{lstlisting}
  1391. fx+: result is not a fixnum
  1392. \end{lstlisting}
  1393. We establish the convention that if running the definitional
  1394. interpreter on a program produces an error, then the meaning of that
  1395. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1396. error is a \code{trapped-error}. A compiler for the language is under
  1397. no obligation regarding programs with unspecified behavior; it does
  1398. not have to produce an executable, and if it does, that executable can
  1399. do anything. On the other hand, if the error is a
  1400. \code{trapped-error}, then the compiler must produce an executable and
  1401. it is required to report that an error occurred. To signal an error,
  1402. exit with a return code of \code{255}. The interpreters in chapters
  1403. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1404. \code{trapped-error}.
  1405. \fi}
  1406. % TODO: how to deal with too-large integers in the Python interpreter?
  1407. %% This convention applies to the languages defined in this
  1408. %% book, as a way to simplify the student's task of implementing them,
  1409. %% but this convention is not applicable to all programming languages.
  1410. %%
  1411. The last feature of the \LangInt{} language, the \READOP{} operation,
  1412. prompts the user of the program for an integer. Recall that program
  1413. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1414. \code{8}. So, if we run {\if\edition\racketEd
  1415. \begin{lstlisting}
  1416. (interp_Lint (Program '() ast1_1))
  1417. \end{lstlisting}
  1418. \fi}
  1419. {\if\edition\pythonEd\pythonColor
  1420. \begin{lstlisting}
  1421. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1422. \end{lstlisting}
  1423. \fi}
  1424. \noindent and if the input is \code{50}, the result is \code{42}.
  1425. We include the \READOP{} operation in \LangInt{} so that a clever
  1426. student cannot implement a compiler for \LangInt{} that simply runs
  1427. the interpreter during compilation to obtain the output and then
  1428. generates the trivial code to produce the output.\footnote{Yes, a
  1429. clever student did this in the first instance of this course!}
  1430. The job of a compiler is to translate a program in one language into a
  1431. program in another language so that the output program behaves the
  1432. same way as the input program. This idea is depicted in the
  1433. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1434. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1435. Given a compiler that translates from language $\mathcal{L}_1$ to
  1436. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1437. compiler must translate it into some program $P_2$ such that
  1438. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1439. same input $i$ yields the same output $o$.
  1440. \begin{equation} \label{eq:compile-correct}
  1441. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1442. \node (p1) at (0, 0) {$P_1$};
  1443. \node (p2) at (3, 0) {$P_2$};
  1444. \node (o) at (3, -2.5) {$o$};
  1445. \path[->] (p1) edge [above] node {compile} (p2);
  1446. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1447. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1448. \end{tikzpicture}
  1449. \end{equation}
  1450. \python{We establish the convention that if running the definitional
  1451. interpreter on a program produces an error, then the meaning of that
  1452. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1453. unless the exception raised is a \code{TrappedError}. A compiler for
  1454. the language is under no obligation regarding programs with
  1455. unspecified behavior; it does not have to produce an executable, and
  1456. if it does, that executable can do anything. On the other hand, if
  1457. the error is a \code{TrappedError}, then the compiler must produce
  1458. an executable and it is required to report that an error
  1459. occurred. To signal an error, exit with a return code of \code{255}.
  1460. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1461. section \ref{sec:arrays} use \code{TrappedError}.}
  1462. In the next section we see our first example of a compiler.
  1463. \section{Example Compiler: A Partial Evaluator}
  1464. \label{sec:partial-evaluation}
  1465. In this section we consider a compiler that translates \LangInt{}
  1466. programs into \LangInt{} programs that may be more efficient. The
  1467. compiler eagerly computes the parts of the program that do not depend
  1468. on any inputs, a process known as \emph{partial
  1469. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1470. For example, given the following program
  1471. {\if\edition\racketEd
  1472. \begin{lstlisting}
  1473. (+ (read) (- (+ 5 3)))
  1474. \end{lstlisting}
  1475. \fi}
  1476. {\if\edition\pythonEd\pythonColor
  1477. \begin{lstlisting}
  1478. print(input_int() + -(5 + 3) )
  1479. \end{lstlisting}
  1480. \fi}
  1481. \noindent our compiler translates it into the program
  1482. {\if\edition\racketEd
  1483. \begin{lstlisting}
  1484. (+ (read) -8)
  1485. \end{lstlisting}
  1486. \fi}
  1487. {\if\edition\pythonEd\pythonColor
  1488. \begin{lstlisting}
  1489. print(input_int() + -8)
  1490. \end{lstlisting}
  1491. \fi}
  1492. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1493. evaluator for the \LangInt{} language. The output of the partial evaluator
  1494. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1495. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1496. whereas the code for partially evaluating the negation and addition
  1497. operations is factored into three auxiliary functions:
  1498. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1499. functions is the output of partially evaluating the children.
  1500. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1501. arguments are integers and if they are, perform the appropriate
  1502. arithmetic. Otherwise, they create an AST node for the arithmetic
  1503. operation.
  1504. \begin{figure}[tp]
  1505. \begin{tcolorbox}[colback=white]
  1506. {\if\edition\racketEd
  1507. \begin{lstlisting}
  1508. (define (pe_neg r)
  1509. (match r
  1510. [(Int n) (Int (fx- 0 n))]
  1511. [else (Prim '- (list r))]))
  1512. (define (pe_add r1 r2)
  1513. (match* (r1 r2)
  1514. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1515. [(_ _) (Prim '+ (list r1 r2))]))
  1516. (define (pe_sub r1 r2)
  1517. (match* (r1 r2)
  1518. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1519. [(_ _) (Prim '- (list r1 r2))]))
  1520. (define (pe_exp e)
  1521. (match e
  1522. [(Int n) (Int n)]
  1523. [(Prim 'read '()) (Prim 'read '())]
  1524. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1525. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1526. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1527. (define (pe_Lint p)
  1528. (match p
  1529. [(Program '() e) (Program '() (pe_exp e))]))
  1530. \end{lstlisting}
  1531. \fi}
  1532. {\if\edition\pythonEd\pythonColor
  1533. \begin{lstlisting}
  1534. def pe_neg(r):
  1535. match r:
  1536. case Constant(n):
  1537. return Constant(neg64(n))
  1538. case _:
  1539. return UnaryOp(USub(), r)
  1540. def pe_add(r1, r2):
  1541. match (r1, r2):
  1542. case (Constant(n1), Constant(n2)):
  1543. return Constant(add64(n1, n2))
  1544. case _:
  1545. return BinOp(r1, Add(), r2)
  1546. def pe_sub(r1, r2):
  1547. match (r1, r2):
  1548. case (Constant(n1), Constant(n2)):
  1549. return Constant(sub64(n1, n2))
  1550. case _:
  1551. return BinOp(r1, Sub(), r2)
  1552. def pe_exp(e):
  1553. match e:
  1554. case BinOp(left, Add(), right):
  1555. return pe_add(pe_exp(left), pe_exp(right))
  1556. case BinOp(left, Sub(), right):
  1557. return pe_sub(pe_exp(left), pe_exp(right))
  1558. case UnaryOp(USub(), v):
  1559. return pe_neg(pe_exp(v))
  1560. case Constant(value):
  1561. return e
  1562. case Call(Name('input_int'), []):
  1563. return e
  1564. def pe_stmt(s):
  1565. match s:
  1566. case Expr(Call(Name('print'), [arg])):
  1567. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1568. case Expr(value):
  1569. return Expr(pe_exp(value))
  1570. def pe_Lint(p):
  1571. match p:
  1572. case Module(body):
  1573. new_body = [pe_stmt(s) for s in body]
  1574. return Module(new_body)
  1575. \end{lstlisting}
  1576. \fi}
  1577. \end{tcolorbox}
  1578. \caption{A partial evaluator for \LangInt{}.}
  1579. \label{fig:pe-arith}
  1580. \end{figure}
  1581. To gain some confidence that the partial evaluator is correct, we can
  1582. test whether it produces programs that produce the same result as the
  1583. input programs. That is, we can test whether it satisfies the diagram
  1584. of \eqref{eq:compile-correct}.
  1585. %
  1586. {\if\edition\racketEd
  1587. The following code runs the partial evaluator on several examples and
  1588. tests the output program. The \texttt{parse-program} and
  1589. \texttt{assert} functions are defined in
  1590. appendix~\ref{appendix:utilities}.\\
  1591. \begin{minipage}{1.0\textwidth}
  1592. \begin{lstlisting}
  1593. (define (test_pe p)
  1594. (assert "testing pe_Lint"
  1595. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1596. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1597. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1598. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1599. \end{lstlisting}
  1600. \end{minipage}
  1601. \fi}
  1602. % TODO: python version of testing the PE
  1603. \begin{exercise}\normalfont\normalsize
  1604. Create three programs in the \LangInt{} language and test whether
  1605. partially evaluating them with \code{pe\_Lint} and then
  1606. interpreting them with \code{interp\_Lint} gives the same result
  1607. as directly interpreting them with \code{interp\_Lint}.
  1608. \end{exercise}
  1609. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1610. \chapter{Integers and Variables}
  1611. \label{ch:Lvar}
  1612. \setcounter{footnote}{0}
  1613. This chapter covers compiling a subset of
  1614. \racket{Racket}\python{Python} to x86-64 assembly
  1615. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1616. integer arithmetic and local variables. We often refer to x86-64
  1617. simply as x86. The chapter first describes the \LangVar{} language
  1618. (section~\ref{sec:s0}) and then introduces x86 assembly
  1619. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1620. discuss only the instructions needed for compiling \LangVar{}. We
  1621. introduce more x86 instructions in subsequent chapters. After
  1622. introducing \LangVar{} and x86, we reflect on their differences and
  1623. create a plan to break down the translation from \LangVar{} to x86
  1624. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1625. the chapter gives detailed hints regarding each step. We aim to give
  1626. enough hints that the well-prepared reader, together with a few
  1627. friends, can implement a compiler from \LangVar{} to x86 in a short
  1628. time. To suggest the scale of this first compiler, we note that the
  1629. instructor solution for the \LangVar{} compiler is approximately
  1630. \racket{500}\python{300} lines of code.
  1631. \section{The \LangVar{} Language}
  1632. \label{sec:s0}
  1633. \index{subject}{variable}
  1634. The \LangVar{} language extends the \LangInt{} language with
  1635. variables. The concrete syntax of the \LangVar{} language is defined
  1636. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1637. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1638. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1639. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1640. \key{-} is a unary operator, and \key{+} is a binary operator.
  1641. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1642. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1643. the top of the program.
  1644. %% The $\itm{info}$
  1645. %% field of the \key{Program} structure contains an \emph{association
  1646. %% list} (a list of key-value pairs) that is used to communicate
  1647. %% auxiliary data from one compiler pass the next.
  1648. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1649. exhibit several compilation techniques.
  1650. \newcommand{\LvarGrammarRacket}{
  1651. \begin{array}{rcl}
  1652. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1653. \end{array}
  1654. }
  1655. \newcommand{\LvarASTRacket}{
  1656. \begin{array}{rcl}
  1657. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1658. \end{array}
  1659. }
  1660. \newcommand{\LvarGrammarPython}{
  1661. \begin{array}{rcl}
  1662. \Exp &::=& \Var{} \\
  1663. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1664. \end{array}
  1665. }
  1666. \newcommand{\LvarASTPython}{
  1667. \begin{array}{rcl}
  1668. \Exp{} &::=& \VAR{\Var{}} \\
  1669. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1670. \end{array}
  1671. }
  1672. \begin{figure}[tp]
  1673. \centering
  1674. \begin{tcolorbox}[colback=white]
  1675. {\if\edition\racketEd
  1676. \[
  1677. \begin{array}{l}
  1678. \gray{\LintGrammarRacket{}} \\ \hline
  1679. \LvarGrammarRacket{} \\
  1680. \begin{array}{rcl}
  1681. \LangVarM{} &::=& \Exp
  1682. \end{array}
  1683. \end{array}
  1684. \]
  1685. \fi}
  1686. {\if\edition\pythonEd\pythonColor
  1687. \[
  1688. \begin{array}{l}
  1689. \gray{\LintGrammarPython} \\ \hline
  1690. \LvarGrammarPython \\
  1691. \begin{array}{rcl}
  1692. \LangVarM{} &::=& \Stmt^{*}
  1693. \end{array}
  1694. \end{array}
  1695. \]
  1696. \fi}
  1697. \end{tcolorbox}
  1698. \caption{The concrete syntax of \LangVar{}.}
  1699. \label{fig:Lvar-concrete-syntax}
  1700. \index{subject}{Lvar@\LangVar{} concrete syntax}
  1701. \end{figure}
  1702. \begin{figure}[tp]
  1703. \centering
  1704. \begin{tcolorbox}[colback=white]
  1705. {\if\edition\racketEd
  1706. \[
  1707. \begin{array}{l}
  1708. \gray{\LintASTRacket{}} \\ \hline
  1709. \LvarASTRacket \\
  1710. \begin{array}{rcl}
  1711. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1712. \end{array}
  1713. \end{array}
  1714. \]
  1715. \fi}
  1716. {\if\edition\pythonEd\pythonColor
  1717. \[
  1718. \begin{array}{l}
  1719. \gray{\LintASTPython}\\ \hline
  1720. \LvarASTPython \\
  1721. \begin{array}{rcl}
  1722. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1723. \end{array}
  1724. \end{array}
  1725. \]
  1726. \fi}
  1727. \end{tcolorbox}
  1728. \caption{The abstract syntax of \LangVar{}.}
  1729. \label{fig:Lvar-syntax}
  1730. \index{subject}{Lvar@\LangVar{} abstract syntax}
  1731. \end{figure}
  1732. {\if\edition\racketEd
  1733. Let us dive further into the syntax and semantics of the \LangVar{}
  1734. language. The \key{let} feature defines a variable for use within its
  1735. body and initializes the variable with the value of an expression.
  1736. The abstract syntax for \key{let} is shown in
  1737. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1738. \begin{lstlisting}
  1739. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1740. \end{lstlisting}
  1741. For example, the following program initializes \code{x} to $32$ and then
  1742. evaluates the body \code{(+ 10 x)}, producing $42$.
  1743. \begin{lstlisting}
  1744. (let ([x (+ 12 20)]) (+ 10 x))
  1745. \end{lstlisting}
  1746. \fi}
  1747. %
  1748. {\if\edition\pythonEd\pythonColor
  1749. %
  1750. The \LangVar{} language includes an assignment statement, which defines a
  1751. variable for use in later statements and initializes the variable with
  1752. the value of an expression. The abstract syntax for assignment is
  1753. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1754. assignment is \index{subject}{Assign@\texttt{Assign}}
  1755. \begin{lstlisting}
  1756. |$\itm{var}$| = |$\itm{exp}$|
  1757. \end{lstlisting}
  1758. For example, the following program initializes the variable \code{x}
  1759. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1760. \begin{lstlisting}
  1761. x = 12 + 20
  1762. print(10 + x)
  1763. \end{lstlisting}
  1764. \fi}
  1765. {\if\edition\racketEd
  1766. %
  1767. When there are multiple \key{let}s for the same variable, the closest
  1768. enclosing \key{let} is used. That is, variable definitions overshadow
  1769. prior definitions. Consider the following program with two \key{let}s
  1770. that define two variables named \code{x}. Can you figure out the
  1771. result?
  1772. \begin{lstlisting}
  1773. (let ([x 32]) (+ (let ([x 10]) x) x))
  1774. \end{lstlisting}
  1775. For the purposes of depicting which variable occurrences correspond to
  1776. which definitions, the following shows the \code{x}'s annotated with
  1777. subscripts to distinguish them. Double-check that your answer for the
  1778. previous program is the same as your answer for this annotated version
  1779. of the program.
  1780. \begin{lstlisting}
  1781. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1782. \end{lstlisting}
  1783. The initializing expression is always evaluated before the body of the
  1784. \key{let}, so in the following, the \key{read} for \code{x} is
  1785. performed before the \key{read} for \code{y}. Given the input
  1786. $52$ then $10$, the following produces $42$ (not $-42$).
  1787. \begin{lstlisting}
  1788. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1789. \end{lstlisting}
  1790. \fi}
  1791. \subsection{Extensible Interpreters via Method Overriding}
  1792. \label{sec:extensible-interp}
  1793. \index{subject}{method overriding}
  1794. To prepare for discussing the interpreter of \LangVar{}, we explain
  1795. why we implement it in an object-oriented style. Throughout this book
  1796. we define many interpreters, one for each language that we
  1797. study. Because each language builds on the prior one, there is a lot
  1798. of commonality between these interpreters. We want to write down the
  1799. common parts just once instead of many times. A naive interpreter for
  1800. \LangVar{} would handle the \racket{cases for variables and
  1801. \code{let}}\python{case for variables} but dispatch to an
  1802. interpreter for \LangInt{} in the rest of the cases. The following
  1803. code sketches this idea. (We explain the \code{env} parameter in
  1804. section~\ref{sec:interp-Lvar}.)
  1805. \begin{center}
  1806. {\if\edition\racketEd
  1807. \begin{minipage}{0.45\textwidth}
  1808. \begin{lstlisting}
  1809. (define ((interp_Lint env) e)
  1810. (match e
  1811. [(Prim '- (list e1))
  1812. (fx- 0 ((interp_Lint env) e1))]
  1813. ...))
  1814. \end{lstlisting}
  1815. \end{minipage}
  1816. \begin{minipage}{0.45\textwidth}
  1817. \begin{lstlisting}
  1818. (define ((interp_Lvar env) e)
  1819. (match e
  1820. [(Var x)
  1821. (dict-ref env x)]
  1822. [(Let x e body)
  1823. (define v ((interp_Lvar env) e))
  1824. (define env^ (dict-set env x v))
  1825. ((interp_Lvar env^) body)]
  1826. [else ((interp_Lint env) e)]))
  1827. \end{lstlisting}
  1828. \end{minipage}
  1829. \fi}
  1830. {\if\edition\pythonEd\pythonColor
  1831. \begin{minipage}{0.45\textwidth}
  1832. \begin{lstlisting}
  1833. def interp_Lint(e, env):
  1834. match e:
  1835. case UnaryOp(USub(), e1):
  1836. return - interp_Lint(e1, env)
  1837. ...
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. \begin{minipage}{0.45\textwidth}
  1841. \begin{lstlisting}
  1842. def interp_Lvar(e, env):
  1843. match e:
  1844. case Name(id):
  1845. return env[id]
  1846. case _:
  1847. return interp_Lint(e, env)
  1848. \end{lstlisting}
  1849. \end{minipage}
  1850. \fi}
  1851. \end{center}
  1852. The problem with this naive approach is that it does not handle
  1853. situations in which an \LangVar{} feature, such as a variable, is
  1854. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1855. in the following program.
  1856. {\if\edition\racketEd
  1857. \begin{lstlisting}
  1858. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1859. \end{lstlisting}
  1860. \fi}
  1861. {\if\edition\pythonEd\pythonColor
  1862. \begin{minipage}{1.0\textwidth}
  1863. \begin{lstlisting}
  1864. y = 10
  1865. print(-y)
  1866. \end{lstlisting}
  1867. \end{minipage}
  1868. \fi}
  1869. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1870. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1871. then it recursively calls \code{interp\_Lint} again on its argument.
  1872. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1873. \code{interp\_Lint}, we get an error!
  1874. To make our interpreters extensible we need something called
  1875. \emph{open recursion}\index{subject}{open recursion}, in which the
  1876. tying of the recursive knot is delayed until the functions are
  1877. composed. Object-oriented languages provide open recursion via method
  1878. overriding. The following code uses
  1879. method overriding to interpret \LangInt{} and \LangVar{} using
  1880. %
  1881. \racket{the
  1882. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1883. \index{subject}{class} feature of Racket.}%
  1884. %
  1885. \python{Python \code{class} definitions.}
  1886. %
  1887. We define one class for each language and define a method for
  1888. interpreting expressions inside each class. The class for \LangVar{}
  1889. inherits from the class for \LangInt{}, and the method
  1890. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1891. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1892. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1893. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1894. \code{interp\_exp} in \LangInt{}.
  1895. \begin{center}
  1896. \hspace{-20pt}
  1897. {\if\edition\racketEd
  1898. \begin{minipage}{0.45\textwidth}
  1899. \begin{lstlisting}
  1900. (define interp-Lint-class
  1901. (class object%
  1902. (define/public ((interp_exp env) e)
  1903. (match e
  1904. [(Prim '- (list e))
  1905. (fx- 0 ((interp_exp env) e))]
  1906. ...))
  1907. ...))
  1908. \end{lstlisting}
  1909. \end{minipage}
  1910. \begin{minipage}{0.45\textwidth}
  1911. \begin{lstlisting}
  1912. (define interp-Lvar-class
  1913. (class interp-Lint-class
  1914. (define/override ((interp_exp env) e)
  1915. (match e
  1916. [(Var x)
  1917. (dict-ref env x)]
  1918. [(Let x e body)
  1919. (define v ((interp_exp env) e))
  1920. (define env^ (dict-set env x v))
  1921. ((interp_exp env^) body)]
  1922. [else
  1923. ((super interp_exp env) e)]))
  1924. ...
  1925. ))
  1926. \end{lstlisting}
  1927. \end{minipage}
  1928. \fi}
  1929. {\if\edition\pythonEd\pythonColor
  1930. \begin{minipage}{0.45\textwidth}
  1931. \begin{lstlisting}
  1932. class InterpLint:
  1933. def interp_exp(e):
  1934. match e:
  1935. case UnaryOp(USub(), e1):
  1936. return neg64(self.interp_exp(e1))
  1937. ...
  1938. ...
  1939. \end{lstlisting}
  1940. \end{minipage}
  1941. \begin{minipage}{0.45\textwidth}
  1942. \begin{lstlisting}
  1943. class InterpLvar(InterpLint):
  1944. def interp_exp(e):
  1945. match e:
  1946. case Name(id):
  1947. return env[id]
  1948. case _:
  1949. return super().interp_exp(e)
  1950. ...
  1951. \end{lstlisting}
  1952. \end{minipage}
  1953. \fi}
  1954. \end{center}
  1955. We return to the troublesome example, repeated here:
  1956. {\if\edition\racketEd
  1957. \begin{lstlisting}
  1958. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1959. \end{lstlisting}
  1960. \fi}
  1961. {\if\edition\pythonEd\pythonColor
  1962. \begin{lstlisting}
  1963. y = 10
  1964. print(-y)
  1965. \end{lstlisting}
  1966. \fi}
  1967. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1968. \racket{on this expression,}%
  1969. \python{on the \code{-y} expression,}
  1970. %
  1971. which we call \code{e0}, by creating an object of the \LangVar{} class
  1972. and calling the \code{interp\_exp} method
  1973. {\if\edition\racketEd
  1974. \begin{lstlisting}
  1975. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1976. \end{lstlisting}
  1977. \fi}
  1978. {\if\edition\pythonEd\pythonColor
  1979. \begin{lstlisting}
  1980. InterpLvar().interp_exp(e0)
  1981. \end{lstlisting}
  1982. \fi}
  1983. \noindent To process the \code{-} operator, the default case of
  1984. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1985. method in \LangInt{}. But then for the recursive method call, it
  1986. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1987. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  1988. Thus, method overriding gives us the open recursion that we need to
  1989. implement our interpreters in an extensible way.
  1990. \subsection{Definitional Interpreter for \LangVar{}}
  1991. \label{sec:interp-Lvar}
  1992. Having justified the use of classes and methods to implement
  1993. interpreters, we revisit the definitional interpreter for \LangInt{}
  1994. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1995. create an interpreter for \LangVar{}, shown in
  1996. figure~\ref{fig:interp-Lvar}.
  1997. %
  1998. \python{We change the \code{interp\_stmt} method in the interpreter
  1999. for \LangInt{} to take two extra parameters named \code{env}, which
  2000. we discuss in the next paragraph, and \code{cont} for
  2001. \emph{continuation}, which is the technical name for what comes
  2002. after a particular point in a program. The \code{cont} parameter is
  2003. the list of statements that follow the current statement. Note
  2004. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  2005. statement and passes the rest of the statements as the argument for
  2006. \code{cont}. This organization enables each statement to decide what
  2007. if anything should be evaluated after it, for example, allowing a
  2008. \code{return} statement to exit early from a function (see
  2009. Chapter~\ref{ch:Lfun}).}
  2010. The interpreter for \LangVar{} adds two new cases for
  2011. variables and \racket{\key{let}}\python{assignment}. For
  2012. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2013. value bound to a variable to all the uses of the variable. To
  2014. accomplish this, we maintain a mapping from variables to values called
  2015. an \emph{environment}\index{subject}{environment}.
  2016. %
  2017. We use
  2018. %
  2019. \racket{an association list (alist) }%
  2020. %
  2021. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2022. %
  2023. to represent the environment.
  2024. %
  2025. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2026. and the \code{racket/dict} package.}
  2027. %
  2028. The \code{interp\_exp} function takes the current environment,
  2029. \code{env}, as an extra parameter. When the interpreter encounters a
  2030. variable, it looks up the corresponding value in the environment. If
  2031. the variable is not in the environment (because the variable was not
  2032. defined) then the lookup will fail and the interpreter will
  2033. halt with an error. Recall that the compiler is not obligated to
  2034. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2035. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2036. prohibit access to undefined variables.}
  2037. %
  2038. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2039. initializing expression, extends the environment with the result
  2040. value bound to the variable, using \code{dict-set}, then evaluates
  2041. the body of the \key{Let}.}
  2042. %
  2043. \python{When the interpreter encounters an assignment, it evaluates
  2044. the initializing expression and then associates the resulting value
  2045. with the variable in the environment.}
  2046. \begin{figure}[tp]
  2047. \begin{tcolorbox}[colback=white]
  2048. {\if\edition\racketEd
  2049. \begin{lstlisting}
  2050. (define interp-Lint-class
  2051. (class object%
  2052. (super-new)
  2053. (define/public ((interp_exp env) e)
  2054. (match e
  2055. [(Int n) n]
  2056. [(Prim 'read '())
  2057. (define r (read))
  2058. (cond [(fixnum? r) r]
  2059. [else (error 'interp_exp "expected an integer" r)])]
  2060. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2061. [(Prim '+ (list e1 e2))
  2062. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2063. [(Prim '- (list e1 e2))
  2064. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2065. (define/public (interp_program p)
  2066. (match p
  2067. [(Program '() e) ((interp_exp '()) e)]))
  2068. ))
  2069. \end{lstlisting}
  2070. \fi}
  2071. {\if\edition\pythonEd\pythonColor
  2072. \begin{lstlisting}
  2073. class InterpLint:
  2074. def interp_exp(self, e, env):
  2075. match e:
  2076. case BinOp(left, Add(), right):
  2077. l = self.interp_exp(left, env)
  2078. r = self.interp_exp(right, env)
  2079. return add64(l, r)
  2080. case BinOp(left, Sub(), right):
  2081. l = self.interp_exp(left, env)
  2082. r = self.interp_exp(right, env)
  2083. return sub64(l, r)
  2084. case UnaryOp(USub(), v):
  2085. return neg64(self.interp_exp(v, env))
  2086. case Constant(value):
  2087. return value
  2088. case Call(Name('input_int'), []):
  2089. return int(input())
  2090. def interp_stmt(self, s, env, cont):
  2091. match s:
  2092. case Expr(Call(Name('print'), [arg])):
  2093. val = self.interp_exp(arg, env)
  2094. print(val, end='')
  2095. return self.interp_stmts(cont, env)
  2096. case Expr(value):
  2097. self.interp_exp(value, env)
  2098. return self.interp_stmts(cont, env)
  2099. case _:
  2100. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2101. def interp_stmts(self, ss, env):
  2102. match ss:
  2103. case []:
  2104. return 0
  2105. case [s, *ss]:
  2106. return self.interp_stmt(s, env, ss)
  2107. def interp(self, p):
  2108. match p:
  2109. case Module(body):
  2110. self.interp_stmts(body, {})
  2111. def interp_Lint(p):
  2112. return InterpLint().interp(p)
  2113. \end{lstlisting}
  2114. \fi}
  2115. \end{tcolorbox}
  2116. \caption{Interpreter for \LangInt{} as a class.}
  2117. \label{fig:interp-Lint-class}
  2118. \end{figure}
  2119. \begin{figure}[tp]
  2120. \begin{tcolorbox}[colback=white]
  2121. {\if\edition\racketEd
  2122. \begin{lstlisting}
  2123. (define interp-Lvar-class
  2124. (class interp-Lint-class
  2125. (super-new)
  2126. (define/override ((interp_exp env) e)
  2127. (match e
  2128. [(Var x) (dict-ref env x)]
  2129. [(Let x e body)
  2130. (define new-env (dict-set env x ((interp_exp env) e)))
  2131. ((interp_exp new-env) body)]
  2132. [else ((super interp_exp env) e)]))
  2133. ))
  2134. (define (interp_Lvar p)
  2135. (send (new interp-Lvar-class) interp_program p))
  2136. \end{lstlisting}
  2137. \fi}
  2138. {\if\edition\pythonEd\pythonColor
  2139. \begin{lstlisting}
  2140. class InterpLvar(InterpLint):
  2141. def interp_exp(self, e, env):
  2142. match e:
  2143. case Name(id):
  2144. return env[id]
  2145. case _:
  2146. return super().interp_exp(e, env)
  2147. def interp_stmt(self, s, env, cont):
  2148. match s:
  2149. case Assign([Name(id)], value):
  2150. env[id] = self.interp_exp(value, env)
  2151. return self.interp_stmts(cont, env)
  2152. case _:
  2153. return super().interp_stmt(s, env, cont)
  2154. def interp_Lvar(p):
  2155. return InterpLvar().interp(p)
  2156. \end{lstlisting}
  2157. \fi}
  2158. \end{tcolorbox}
  2159. \caption{Interpreter for the \LangVar{} language.}
  2160. \label{fig:interp-Lvar}
  2161. \end{figure}
  2162. {\if\edition\racketEd
  2163. \begin{figure}[tp]
  2164. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2165. \small
  2166. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2167. An \emph{association list} (called an alist) is a list of key-value pairs.
  2168. For example, we can map people to their ages with an alist
  2169. \index{subject}{alist}\index{subject}{association list}
  2170. \begin{lstlisting}[basicstyle=\ttfamily]
  2171. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2172. \end{lstlisting}
  2173. The \emph{dictionary} interface is for mapping keys to values.
  2174. Every alist implements this interface. \index{subject}{dictionary}
  2175. The package
  2176. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2177. provides many functions for working with dictionaries, such as
  2178. \begin{description}
  2179. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2180. returns the value associated with the given $\itm{key}$.
  2181. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2182. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2183. and otherwise is the same as $\itm{dict}$.
  2184. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2185. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2186. of keys and values in $\itm{dict}$. For example, the following
  2187. creates a new alist in which the ages are incremented:
  2188. \end{description}
  2189. \vspace{-10pt}
  2190. \begin{lstlisting}[basicstyle=\ttfamily]
  2191. (for/list ([(k v) (in-dict ages)])
  2192. (cons k (add1 v)))
  2193. \end{lstlisting}
  2194. \end{tcolorbox}
  2195. %\end{wrapfigure}
  2196. \caption{Association lists implement the dictionary interface.}
  2197. \label{fig:alist}
  2198. \end{figure}
  2199. \fi}
  2200. The goal for this chapter is to implement a compiler that translates
  2201. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2202. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2203. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2204. That is, they output the same integer $n$. We depict this correctness
  2205. criteria in the following diagram:
  2206. \[
  2207. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2208. \node (p1) at (0, 0) {$P_1$};
  2209. \node (p2) at (4, 0) {$P_2$};
  2210. \node (o) at (4, -2) {$n$};
  2211. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2212. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2213. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2214. \end{tikzpicture}
  2215. \]
  2216. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2217. compiling \LangVar{}.
  2218. \section{The \LangXInt{} Assembly Language}
  2219. \label{sec:x86}
  2220. \index{subject}{x86}
  2221. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2222. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2223. assembler.
  2224. %
  2225. A program begins with a \code{main} label followed by a sequence of
  2226. instructions. The \key{globl} directive makes the \key{main} procedure
  2227. externally visible so that the operating system can call it.
  2228. %
  2229. An x86 program is stored in the computer's memory. For our purposes,
  2230. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2231. values. The computer has a \emph{program counter}
  2232. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2233. \code{rip} register that points to the address of the next instruction
  2234. to be executed. For most instructions, the program counter is
  2235. incremented after the instruction is executed so that it points to the
  2236. next instruction in memory. Most x86 instructions take two operands,
  2237. each of which is an integer constant (called an \emph{immediate
  2238. value}\index{subject}{immediate value}), a
  2239. \emph{register}\index{subject}{register}, or a memory location.
  2240. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2241. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2242. && \key{r8} \MID \key{r9} \MID \key{r10}
  2243. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2244. \MID \key{r14} \MID \key{r15}}
  2245. \newcommand{\GrammarXIntRacket}{
  2246. \begin{array}{rcl}
  2247. \Reg &::=& \allregisters{} \\
  2248. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2249. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2250. \key{subq} \; \Arg\key{,} \Arg \MID
  2251. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2252. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2253. \key{callq} \; \mathit{label} \MID
  2254. \key{retq} \MID
  2255. \key{jmp}\,\itm{label} \MID \\
  2256. && \itm{label}\key{:}\; \Instr
  2257. \end{array}
  2258. }
  2259. \newcommand{\GrammarXIntPython}{
  2260. % no jmp and label in the python version
  2261. \begin{array}{rcl}
  2262. \Reg &::=& \allregisters{} \\
  2263. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2264. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2265. \key{subq} \; \Arg\key{,} \Arg \MID
  2266. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2267. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2268. \key{callq} \; \mathit{label} \MID \key{retq}
  2269. \end{array}
  2270. }
  2271. \begin{figure}[tp]
  2272. \begin{tcolorbox}[colback=white]
  2273. {\if\edition\racketEd
  2274. \[
  2275. \begin{array}{l}
  2276. \GrammarXIntRacket \\
  2277. \begin{array}{lcl}
  2278. \LangXIntM{} &::= & \key{.globl main}\\
  2279. & & \key{main:} \; \Instr\ldots
  2280. \end{array}
  2281. \end{array}
  2282. \]
  2283. \fi}
  2284. {\if\edition\pythonEd\pythonColor
  2285. \[
  2286. \begin{array}{lcl}
  2287. \Reg &::=& \allregisters{} \\
  2288. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2289. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2290. \key{subq} \; \Arg\key{,} \Arg \MID
  2291. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2292. && \key{callq} \; \mathit{label} \MID
  2293. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2294. \LangXIntM{} &::= & \key{.globl main}\\
  2295. & & \key{main:} \; \Instr^{*}
  2296. \end{array}
  2297. \]
  2298. \fi}
  2299. \end{tcolorbox}
  2300. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2301. \label{fig:x86-int-concrete}
  2302. \index{subject}{x86int@\LangXInt{} concrete syntax}
  2303. \end{figure}
  2304. A register is a special kind of variable that holds a 64-bit
  2305. value. There are 16 general-purpose registers in the computer; their
  2306. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2307. written with a percent sign, \key{\%}, followed by its name,
  2308. for example, \key{\%rax}.
  2309. An immediate value is written using the notation \key{\$}$n$ where $n$
  2310. is an integer.
  2311. %
  2312. %
  2313. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2314. which obtains the address stored in register $r$ and then adds $n$
  2315. bytes to the address. The resulting address is used to load or to store
  2316. to memory depending on whether it occurs as a source or destination
  2317. argument of an instruction.
  2318. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2319. the source $s$ and destination $d$, applies the arithmetic operation,
  2320. and then writes the result to the destination $d$. \index{subject}{instruction}
  2321. %
  2322. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2323. stores the result in $d$.
  2324. %
  2325. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2326. specified by the label, and $\key{retq}$ returns from a procedure to
  2327. its caller.
  2328. %
  2329. We discuss procedure calls in more detail further in this chapter and
  2330. in chapter~\ref{ch:Lfun}.
  2331. %
  2332. The last letter \key{q} indicates that these instructions operate on
  2333. quadwords, which are 64-bit values.
  2334. %
  2335. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2336. counter to the address of the instruction immediately after the
  2337. specified label.}
  2338. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2339. all the x86 instructions used in this book.
  2340. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2341. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2342. \lstinline{movq $10, %rax}
  2343. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2344. adds $32$ to the $10$ in \key{rax} and
  2345. puts the result, $42$, into \key{rax}.
  2346. %
  2347. The last instruction \key{retq} finishes the \key{main} function by
  2348. returning the integer in \key{rax} to the operating system. The
  2349. operating system interprets this integer as the program's exit
  2350. code. By convention, an exit code of 0 indicates that a program has
  2351. completed successfully, and all other exit codes indicate various
  2352. errors.
  2353. %
  2354. \racket{However, in this book we return the result of the program
  2355. as the exit code.}
  2356. \begin{figure}[tbp]
  2357. \begin{minipage}{0.45\textwidth}
  2358. \begin{tcolorbox}[colback=white]
  2359. \begin{lstlisting}
  2360. .globl main
  2361. main:
  2362. movq $10, %rax
  2363. addq $32, %rax
  2364. retq
  2365. \end{lstlisting}
  2366. \end{tcolorbox}
  2367. \end{minipage}
  2368. \caption{An x86 program that computes
  2369. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2370. \label{fig:p0-x86}
  2371. \end{figure}
  2372. We exhibit the use of memory for storing intermediate results in the
  2373. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2374. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2375. uses a region of memory called the \emph{procedure call stack}
  2376. (\emph{stack} for
  2377. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2378. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2379. for each procedure call. The memory layout for an individual frame is
  2380. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2381. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2382. address of the item at the top of the stack. In general, we use the
  2383. term \emph{pointer}\index{subject}{pointer} for something that
  2384. contains an address. The stack grows downward in memory, so we
  2385. increase the size of the stack by subtracting from the stack pointer.
  2386. In the context of a procedure call, the \emph{return
  2387. address}\index{subject}{return address} is the location of the
  2388. instruction that immediately follows the call instruction on the
  2389. caller side. The function call instruction, \code{callq}, pushes the
  2390. return address onto the stack prior to jumping to the procedure. The
  2391. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2392. pointer} and is used to access variables that are stored in the
  2393. frame of the current procedure call. The base pointer of the caller
  2394. is stored immediately after the return address.
  2395. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2396. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2397. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2398. $-16\key{(\%rbp)}$, and so on.
  2399. \begin{figure}[tbp]
  2400. \begin{minipage}{0.66\textwidth}
  2401. \begin{tcolorbox}[colback=white]
  2402. {\if\edition\racketEd
  2403. \begin{lstlisting}
  2404. start:
  2405. movq $10, -8(%rbp)
  2406. negq -8(%rbp)
  2407. movq -8(%rbp), %rax
  2408. addq $52, %rax
  2409. jmp conclusion
  2410. .globl main
  2411. main:
  2412. pushq %rbp
  2413. movq %rsp, %rbp
  2414. subq $16, %rsp
  2415. jmp start
  2416. conclusion:
  2417. addq $16, %rsp
  2418. popq %rbp
  2419. retq
  2420. \end{lstlisting}
  2421. \fi}
  2422. {\if\edition\pythonEd\pythonColor
  2423. \begin{lstlisting}
  2424. .globl main
  2425. main:
  2426. pushq %rbp
  2427. movq %rsp, %rbp
  2428. subq $16, %rsp
  2429. movq $10, -8(%rbp)
  2430. negq -8(%rbp)
  2431. movq -8(%rbp), %rax
  2432. addq $52, %rax
  2433. addq $16, %rsp
  2434. popq %rbp
  2435. retq
  2436. \end{lstlisting}
  2437. \fi}
  2438. \end{tcolorbox}
  2439. \end{minipage}
  2440. \caption{An x86 program that computes
  2441. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2442. \label{fig:p1-x86}
  2443. \end{figure}
  2444. \begin{figure}[tbp]
  2445. \begin{minipage}{0.66\textwidth}
  2446. \begin{tcolorbox}[colback=white]
  2447. \centering
  2448. \begin{tabular}{|r|l|} \hline
  2449. Position & Contents \\ \hline
  2450. $8$(\key{\%rbp}) & return address \\
  2451. $0$(\key{\%rbp}) & old \key{rbp} \\
  2452. $-8$(\key{\%rbp}) & variable $1$ \\
  2453. $-16$(\key{\%rbp}) & variable $2$ \\
  2454. \ldots & \ldots \\
  2455. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2456. \end{tabular}
  2457. \end{tcolorbox}
  2458. \end{minipage}
  2459. \caption{Memory layout of a frame.}
  2460. \label{fig:frame}
  2461. \end{figure}
  2462. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2463. is transferred from the operating system to the \code{main} function.
  2464. The operating system issues a \code{callq main} instruction that
  2465. pushes its return address on the stack and then jumps to
  2466. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2467. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2468. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2469. out of alignment (because the \code{callq} pushed the return address).
  2470. The first three instructions are the typical
  2471. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2472. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2473. pointer \code{rsp} and then saves the base pointer of the caller at
  2474. address \code{rsp} on the stack. The next instruction \code{movq
  2475. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2476. which is pointing to the location of the old base pointer. The
  2477. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2478. make enough room for storing variables. This program needs one
  2479. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2480. 16-byte-aligned, and then we are ready to make calls to other functions.
  2481. \racket{The last instruction of the prelude is \code{jmp start}, which
  2482. transfers control to the instructions that were generated from the
  2483. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2484. \racket{The first instruction under the \code{start} label is}
  2485. %
  2486. \python{The first instruction after the prelude is}
  2487. %
  2488. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2489. %
  2490. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2491. $1$ to $-10$.
  2492. %
  2493. The next instruction moves the $-10$ from variable $1$ into the
  2494. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2495. the value in \code{rax}, updating its contents to $42$.
  2496. \racket{The three instructions under the label \code{conclusion} are the
  2497. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2498. %
  2499. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2500. \code{main} function consists of the last three instructions.}
  2501. %
  2502. The first two restore the \code{rsp} and \code{rbp} registers to their
  2503. states at the beginning of the procedure. In particular,
  2504. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2505. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2506. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2507. \key{retq}, jumps back to the procedure that called this one and adds
  2508. $8$ to the stack pointer.
  2509. Our compiler needs a convenient representation for manipulating x86
  2510. programs, so we define an abstract syntax for x86, shown in
  2511. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2512. \LangXInt{}.
  2513. %
  2514. {\if\edition\pythonEd\pythonColor%
  2515. The main difference between this and the concrete syntax of \LangXInt{}
  2516. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2517. names, and register names are explicitly represented by strings.
  2518. \fi} %
  2519. {\if\edition\racketEd
  2520. The main difference between this and the concrete syntax of \LangXInt{}
  2521. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2522. front of every instruction. Instead instructions are grouped into
  2523. \emph{basic blocks}\index{subject}{basic block} with a
  2524. label associated with every basic block; this is why the \key{X86Program}
  2525. struct includes an alist mapping labels to basic blocks. The reason for this
  2526. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2527. introduce conditional branching. The \code{Block} structure includes
  2528. an $\itm{info}$ field that is not needed in this chapter but becomes
  2529. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2530. $\itm{info}$ field should contain an empty list.
  2531. \fi}
  2532. %
  2533. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2534. node includes an integer for representing the arity of the function,
  2535. that is, the number of arguments, which is helpful to know during
  2536. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2537. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2538. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2539. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2540. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2541. \MID \skey{r14} \MID \skey{r15}}
  2542. \newcommand{\ASTXIntRacket}{
  2543. \begin{array}{lcl}
  2544. \Reg &::=& \allregisters{} \\
  2545. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2546. \MID \DEREF{\Reg}{\Int} \\
  2547. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2548. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2549. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2550. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2551. &\MID& \PUSHQ{\Arg}
  2552. \MID \POPQ{\Arg} \\
  2553. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2554. \MID \RETQ{}
  2555. \MID \JMP{\itm{label}} \\
  2556. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2557. \end{array}
  2558. }
  2559. \newcommand{\ASTXIntPython}{
  2560. \begin{array}{lcl}
  2561. \Reg &::=& \allregisters{} \\
  2562. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2563. \MID \DEREF{\Reg}{\Int} \\
  2564. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2565. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2566. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2567. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2568. &\MID& \PUSHQ{\Arg}
  2569. \MID \POPQ{\Arg} \\
  2570. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2571. \MID \RETQ{} \\
  2572. \Block &::= & \Instr^{+}
  2573. \end{array}
  2574. }
  2575. \begin{figure}[tp]
  2576. \begin{tcolorbox}[colback=white]
  2577. \small
  2578. {\if\edition\racketEd
  2579. \[\arraycolsep=3pt
  2580. \begin{array}{l}
  2581. \ASTXIntRacket \\
  2582. \begin{array}{lcl}
  2583. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2584. \end{array}
  2585. \end{array}
  2586. \]
  2587. \fi}
  2588. {\if\edition\pythonEd\pythonColor
  2589. \[
  2590. \begin{array}{l}
  2591. \ASTXIntPython \\
  2592. \begin{array}{lcl}
  2593. \LangXIntM{} &::= & \XPROGRAM{}{\Block}{}
  2594. \end{array}
  2595. \end{array}
  2596. \]
  2597. \fi}
  2598. \end{tcolorbox}
  2599. \caption{The abstract syntax of \LangXInt{} assembly.}
  2600. \label{fig:x86-int-ast}
  2601. \index{subject}{x86int@\LangXInt{} abstract syntax}
  2602. \end{figure}
  2603. \section{Planning the Trip to x86}
  2604. \label{sec:plan-s0-x86}
  2605. To compile one language to another, it helps to focus on the
  2606. differences between the two languages because the compiler will need
  2607. to bridge those differences. What are the differences between \LangVar{}
  2608. and x86 assembly? Here are some of the most important ones:
  2609. \begin{enumerate}
  2610. \item x86 arithmetic instructions typically have two arguments and
  2611. update the second argument in place. In contrast, \LangVar{}
  2612. arithmetic operations take two arguments and produce a new value.
  2613. An x86 instruction may have at most one memory-accessing argument.
  2614. Furthermore, some x86 instructions place special restrictions on
  2615. their arguments.
  2616. \item An argument of an \LangVar{} operator can be a deeply nested
  2617. expression, whereas x86 instructions restrict their arguments to be
  2618. integer constants, registers, and memory locations.
  2619. {\if\edition\racketEd
  2620. \item The order of execution in x86 is explicit in the syntax, which
  2621. is a sequence of instructions and jumps to labeled positions,
  2622. whereas in \LangVar{} the order of evaluation is a left-to-right
  2623. depth-first traversal of the abstract syntax tree. \fi}
  2624. \item A program in \LangVar{} can have any number of variables,
  2625. whereas x86 has 16 registers and the procedure call stack.
  2626. {\if\edition\racketEd
  2627. \item Variables in \LangVar{} can shadow other variables with the
  2628. same name. In x86, registers have unique names, and memory locations
  2629. have unique addresses.
  2630. \fi}
  2631. \end{enumerate}
  2632. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2633. down the problem into several steps, which deal with these differences
  2634. one at a time. Each of these steps is called a \emph{pass} of the
  2635. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2636. %
  2637. This term indicates that each step passes over, or traverses, the AST
  2638. of the program.
  2639. %
  2640. Furthermore, we follow the nanopass approach, which means that we
  2641. strive for each pass to accomplish one clear objective rather than two
  2642. or three at the same time.
  2643. %
  2644. We begin by sketching how we might implement each pass and give each
  2645. pass a name. We then figure out an ordering of the passes and the
  2646. input/output language for each pass. The very first pass has
  2647. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2648. its output language. In between these two passes, we can choose
  2649. whichever language is most convenient for expressing the output of
  2650. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2651. \emph{intermediate language} of our own design. Finally, to
  2652. implement each pass we write one recursive function per nonterminal in
  2653. the grammar of the input language of the pass.
  2654. \index{subject}{intermediate language}
  2655. Our compiler for \LangVar{} consists of the following passes:
  2656. %
  2657. \begin{description}
  2658. {\if\edition\racketEd
  2659. \item[\key{uniquify}] deals with the shadowing of variables by
  2660. renaming every variable to a unique name.
  2661. \fi}
  2662. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2663. of a primitive operation or function call is a variable or integer,
  2664. that is, an \emph{atomic} expression. We refer to nonatomic
  2665. expressions as \emph{complex}. This pass introduces temporary
  2666. variables to hold the results of complex
  2667. subexpressions.\index{subject}{atomic
  2668. expression}\index{subject}{complex expression}%
  2669. {\if\edition\racketEd
  2670. \item[\key{explicate\_control}] makes the execution order of the
  2671. program explicit. It converts the abstract syntax tree
  2672. representation into a graph in which each node is a labeled sequence
  2673. of statements and the edges are \code{goto} statements.
  2674. \fi}
  2675. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2676. handles the difference between
  2677. \LangVar{} operations and x86 instructions. This pass converts each
  2678. \LangVar{} operation to a short sequence of instructions that
  2679. accomplishes the same task.
  2680. \item[\key{assign\_homes}] replaces variables with registers or stack
  2681. locations.
  2682. \end{description}
  2683. %
  2684. {\if\edition\racketEd
  2685. %
  2686. Our treatment of \code{remove\_complex\_operands} and
  2687. \code{explicate\_control} as separate passes is an example of the
  2688. nanopass approach.\footnote{For analogous decompositions of the
  2689. translation into continuation passing style, see the work of
  2690. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2691. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2692. %
  2693. \fi}
  2694. The next question is, in what order should we apply these passes? This
  2695. question can be challenging because it is difficult to know ahead of
  2696. time which orderings will be better (that is, will be easier to
  2697. implement, produce more efficient code, and so on), and therefore
  2698. ordering often involves trial and error. Nevertheless, we can plan
  2699. ahead and make educated choices regarding the ordering.
  2700. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2701. \key{uniquify}? The \key{uniquify} pass should come first because
  2702. \key{explicate\_control} changes all the \key{let}-bound variables to
  2703. become local variables whose scope is the entire program, which would
  2704. confuse variables with the same name.}
  2705. %
  2706. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2707. because the latter removes the \key{let} form, but it is convenient to
  2708. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2709. %
  2710. \racket{The ordering of \key{uniquify} with respect to
  2711. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2712. \key{uniquify} to come first.}
  2713. The \key{select\_instructions} and \key{assign\_homes} passes are
  2714. intertwined.
  2715. %
  2716. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2717. passing arguments to functions and that it is preferable to assign
  2718. parameters to their corresponding registers. This suggests that it
  2719. would be better to start with the \key{select\_instructions} pass,
  2720. which generates the instructions for argument passing, before
  2721. performing register allocation.
  2722. %
  2723. On the other hand, by selecting instructions first we may run into a
  2724. dead end in \key{assign\_homes}. Recall that only one argument of an
  2725. x86 instruction may be a memory access, but \key{assign\_homes} might
  2726. be forced to assign both arguments to memory locations.
  2727. %
  2728. A sophisticated approach is to repeat the two passes until a solution
  2729. is found. However, to reduce implementation complexity we recommend
  2730. placing \key{select\_instructions} first, followed by the
  2731. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2732. that uses a reserved register to fix outstanding problems.
  2733. \begin{figure}[tbp]
  2734. \begin{tcolorbox}[colback=white]
  2735. {\if\edition\racketEd
  2736. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2737. \node (Lvar) at (0,2) {\large \LangVar{}};
  2738. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2739. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2740. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2741. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2742. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2743. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2744. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2745. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2746. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2747. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2748. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2749. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2750. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2751. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2752. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2753. \end{tikzpicture}
  2754. \fi}
  2755. {\if\edition\pythonEd\pythonColor
  2756. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2757. \node (Lvar) at (0,2) {\large \LangVar{}};
  2758. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2759. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2760. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2761. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2762. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2763. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2764. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2765. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2766. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2767. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2768. \end{tikzpicture}
  2769. \fi}
  2770. \end{tcolorbox}
  2771. \caption{Diagram of the passes for compiling \LangVar{}. }
  2772. \label{fig:Lvar-passes}
  2773. \end{figure}
  2774. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2775. passes and identifies the input and output language of each pass.
  2776. %
  2777. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2778. language, which extends \LangXInt{} with an unbounded number of
  2779. program-scope variables and removes the restrictions regarding
  2780. instruction arguments.
  2781. %
  2782. The last pass, \key{prelude\_and\_conclusion}, places the program
  2783. instructions inside a \code{main} function with instructions for the
  2784. prelude and conclusion.
  2785. %
  2786. \racket{In the next section we discuss the \LangCVar{} intermediate
  2787. language that serves as the output of \code{explicate\_control}.}
  2788. %
  2789. The remainder of this chapter provides guidance on the implementation
  2790. of each of the compiler passes represented in
  2791. figure~\ref{fig:Lvar-passes}.
  2792. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2793. %% are programs that are still in the \LangVar{} language, though the
  2794. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2795. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2796. %% %
  2797. %% The output of \code{explicate\_control} is in an intermediate language
  2798. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2799. %% syntax, which we introduce in the next section. The
  2800. %% \key{select-instruction} pass translates from \LangCVar{} to
  2801. %% \LangXVar{}. The \key{assign-homes} and
  2802. %% \key{patch-instructions}
  2803. %% passes input and output variants of x86 assembly.
  2804. \newcommand{\CvarGrammarRacket}{
  2805. \begin{array}{lcl}
  2806. \Atm &::=& \Int \MID \Var \\
  2807. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2808. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2809. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2810. \end{array}
  2811. }
  2812. \newcommand{\CvarASTRacket}{
  2813. \begin{array}{lcl}
  2814. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2815. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2816. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2817. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2818. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2819. \end{array}
  2820. }
  2821. {\if\edition\racketEd
  2822. \subsection{The \LangCVar{} Intermediate Language}
  2823. The output of \code{explicate\_control} is similar to the C
  2824. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2825. categories for expressions and statements, so we name it \LangCVar{}.
  2826. This style of intermediate language is also known as
  2827. \emph{three-address code}, to emphasize that the typical form of a
  2828. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2829. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2830. The concrete syntax for \LangCVar{} is shown in
  2831. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2832. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2833. %
  2834. The \LangCVar{} language supports the same operators as \LangVar{} but
  2835. the arguments of operators are restricted to atomic
  2836. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2837. assignment statements that can be executed in sequence using the
  2838. \key{Seq} form. A sequence of statements always ends with
  2839. \key{Return}, a guarantee that is baked into the grammar rules for
  2840. \itm{tail}. The naming of this nonterminal comes from the term
  2841. \emph{tail position}\index{subject}{tail position}, which refers to an
  2842. expression that is the last one to execute within a function or
  2843. program.
  2844. A \LangCVar{} program consists of an alist mapping labels to
  2845. tails. This is more general than necessary for the present chapter, as
  2846. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2847. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2848. there is just one label, \key{start}, and the whole program is
  2849. its tail.
  2850. %
  2851. The $\itm{info}$ field of the \key{CProgram} form, after the
  2852. \code{explicate\_control} pass, contains an alist that associates the
  2853. symbol \key{locals} with a list of all the variables used in the
  2854. program. At the start of the program, these variables are
  2855. uninitialized; they become initialized on their first assignment.
  2856. \begin{figure}[tbp]
  2857. \begin{tcolorbox}[colback=white]
  2858. \[
  2859. \begin{array}{l}
  2860. \CvarGrammarRacket \\
  2861. \begin{array}{lcl}
  2862. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2863. \end{array}
  2864. \end{array}
  2865. \]
  2866. \end{tcolorbox}
  2867. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2868. \label{fig:c0-concrete-syntax}
  2869. \index{subject}{Cvar@\LangCVar{} concrete syntax}
  2870. \end{figure}
  2871. \begin{figure}[tbp]
  2872. \begin{tcolorbox}[colback=white]
  2873. \[
  2874. \begin{array}{l}
  2875. \CvarASTRacket \\
  2876. \begin{array}{lcl}
  2877. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2878. \end{array}
  2879. \end{array}
  2880. \]
  2881. \end{tcolorbox}
  2882. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2883. \label{fig:c0-syntax}
  2884. \index{subject}{Cvar@\LangCVar{} abstract syntax}
  2885. \end{figure}
  2886. The definitional interpreter for \LangCVar{} is in the support code,
  2887. in the file \code{interp-Cvar.rkt}.
  2888. \fi}
  2889. {\if\edition\racketEd
  2890. \section{Uniquify Variables}
  2891. \label{sec:uniquify-Lvar}
  2892. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2893. with a unique name. Both the input and output of the \code{uniquify}
  2894. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2895. should translate the program on the left into the program on the
  2896. right.
  2897. \begin{transformation}
  2898. \begin{lstlisting}
  2899. (let ([x 32])
  2900. (+ (let ([x 10]) x) x))
  2901. \end{lstlisting}
  2902. \compilesto
  2903. \begin{lstlisting}
  2904. (let ([x.1 32])
  2905. (+ (let ([x.2 10]) x.2) x.1))
  2906. \end{lstlisting}
  2907. \end{transformation}
  2908. The following is another example translation, this time of a program
  2909. with a \key{let} nested inside the initializing expression of another
  2910. \key{let}.
  2911. \begin{transformation}
  2912. \begin{lstlisting}
  2913. (let ([x (let ([x 4])
  2914. (+ x 1))])
  2915. (+ x 2))
  2916. \end{lstlisting}
  2917. \compilesto
  2918. \begin{lstlisting}
  2919. (let ([x.2 (let ([x.1 4])
  2920. (+ x.1 1))])
  2921. (+ x.2 2))
  2922. \end{lstlisting}
  2923. \end{transformation}
  2924. We recommend implementing \code{uniquify} by creating a structurally
  2925. recursive function named \code{uniquify\_exp} that does little other
  2926. than copy an expression. However, when encountering a \key{let}, it
  2927. should generate a unique name for the variable and associate the old
  2928. name with the new name in an alist.\footnote{The Racket function
  2929. \code{gensym} is handy for generating unique variable names.} The
  2930. \code{uniquify\_exp} function needs to access this alist when it gets
  2931. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2932. for the alist.
  2933. The skeleton of the \code{uniquify\_exp} function is shown in
  2934. figure~\ref{fig:uniquify-Lvar}.
  2935. %% The function is curried so that it is
  2936. %% convenient to partially apply it to an alist and then apply it to
  2937. %% different expressions, as in the last case for primitive operations in
  2938. %% figure~\ref{fig:uniquify-Lvar}.
  2939. The
  2940. %
  2941. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2942. %
  2943. form of Racket is useful for transforming the element of a list to
  2944. produce a new list.\index{subject}{for/list}
  2945. \begin{figure}[tbp]
  2946. \begin{tcolorbox}[colback=white]
  2947. \begin{lstlisting}
  2948. (define (uniquify_exp env)
  2949. (lambda (e)
  2950. (match e
  2951. [(Var x) ___]
  2952. [(Int n) (Int n)]
  2953. [(Let x e body) ___]
  2954. [(Prim op es)
  2955. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2956. (define (uniquify p)
  2957. (match p
  2958. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2959. \end{lstlisting}
  2960. \end{tcolorbox}
  2961. \caption{Skeleton for the \key{uniquify} pass.}
  2962. \label{fig:uniquify-Lvar}
  2963. \end{figure}
  2964. \begin{exercise}
  2965. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2966. Complete the \code{uniquify} pass by filling in the blanks in
  2967. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2968. variables and for the \key{let} form in the file \code{compiler.rkt}
  2969. in the support code.
  2970. \end{exercise}
  2971. \begin{exercise}
  2972. \normalfont\normalsize
  2973. \label{ex:Lvar}
  2974. Create five \LangVar{} programs that exercise the most interesting
  2975. parts of the \key{uniquify} pass; that is, the programs should include
  2976. \key{let} forms, variables, and variables that shadow each other.
  2977. The five programs should be placed in the subdirectory named
  2978. \key{tests}, and the file names should start with \code{var\_test\_}
  2979. followed by a unique integer and end with the file extension
  2980. \key{.rkt}.
  2981. %
  2982. The \key{run-tests.rkt} script in the support code checks whether the
  2983. output programs produce the same result as the input programs. The
  2984. script uses the \key{interp-tests} function
  2985. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2986. your \key{uniquify} pass on the example programs. The \code{passes}
  2987. parameter of \key{interp-tests} is a list that should have one entry
  2988. for each pass in your compiler. For now, define \code{passes} to
  2989. contain just one entry for \code{uniquify} as follows:
  2990. \begin{lstlisting}
  2991. (define passes
  2992. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2993. \end{lstlisting}
  2994. Run the \key{run-tests.rkt} script in the support code to check
  2995. whether the output programs produce the same result as the input
  2996. programs.
  2997. \end{exercise}
  2998. \fi}
  2999. \section{Remove Complex Operands}
  3000. \label{sec:remove-complex-opera-Lvar}
  3001. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  3002. into a restricted form in which the arguments of operations are atomic
  3003. expressions. Put another way, this pass removes complex
  3004. operands\index{subject}{complex operand}, such as the expression
  3005. \racket{\code{(- 10)}}\python{\code{-10}}
  3006. in the following program. This is accomplished by introducing a new
  3007. temporary variable, assigning the complex operand to the new
  3008. variable, and then using the new variable in place of the complex
  3009. operand, as shown in the output of \code{remove\_complex\_operands} on the
  3010. right.
  3011. {\if\edition\racketEd
  3012. \begin{transformation}
  3013. % var_test_19.rkt
  3014. \begin{lstlisting}
  3015. (let ([x (+ 42 (- 10))])
  3016. (+ x 10))
  3017. \end{lstlisting}
  3018. \compilesto
  3019. \begin{lstlisting}
  3020. (let ([x (let ([tmp.1 (- 10)])
  3021. (+ 42 tmp.1))])
  3022. (+ x 10))
  3023. \end{lstlisting}
  3024. \end{transformation}
  3025. \fi}
  3026. {\if\edition\pythonEd\pythonColor
  3027. \begin{transformation}
  3028. \begin{lstlisting}
  3029. x = 42 + -10
  3030. print(x + 10)
  3031. \end{lstlisting}
  3032. \compilesto
  3033. \begin{lstlisting}
  3034. tmp_0 = -10
  3035. x = 42 + tmp_0
  3036. tmp_1 = x + 10
  3037. print(tmp_1)
  3038. \end{lstlisting}
  3039. \end{transformation}
  3040. \fi}
  3041. \newcommand{\LvarMonadASTRacket}{
  3042. \begin{array}{rcl}
  3043. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3044. \Exp &::=& \Atm \MID \READ{} \\
  3045. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3046. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3047. \end{array}
  3048. }
  3049. \newcommand{\LvarMonadASTPython}{
  3050. \begin{array}{rcl}
  3051. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3052. \Exp{} &::=& \Atm \MID \READ{} \\
  3053. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3054. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3055. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3056. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3057. \end{array}
  3058. }
  3059. \begin{figure}[tp]
  3060. \centering
  3061. \begin{tcolorbox}[colback=white]
  3062. {\if\edition\racketEd
  3063. \[
  3064. \begin{array}{l}
  3065. \LvarMonadASTRacket \\
  3066. \begin{array}{rcl}
  3067. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3068. \end{array}
  3069. \end{array}
  3070. \]
  3071. \fi}
  3072. {\if\edition\pythonEd\pythonColor
  3073. \[
  3074. \begin{array}{l}
  3075. \LvarMonadASTPython \\
  3076. \begin{array}{rcl}
  3077. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3078. \end{array}
  3079. \end{array}
  3080. \]
  3081. \fi}
  3082. \end{tcolorbox}
  3083. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3084. atomic expressions.}
  3085. \label{fig:Lvar-anf-syntax}
  3086. \index{subject}{Lvarmon@\LangVarANF{} abstract syntax}
  3087. \end{figure}
  3088. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3089. of this pass, the language \LangVarANF{}. The only difference is that
  3090. operator arguments are restricted to be atomic expressions that are
  3091. defined by the \Atm{} nonterminal. In particular, integer constants
  3092. and variables are atomic.
  3093. The atomic expressions are pure (they do not cause or depend on side
  3094. effects) whereas complex expressions may have side effects, such as
  3095. \READ{}. A language with this separation between pure expressions
  3096. versus expressions with side effects is said to be in monadic normal
  3097. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3098. in the name \LangVarANF{}. An important invariant of the
  3099. \code{remove\_complex\_operands} pass is that the relative ordering
  3100. among complex expressions is not changed, but the relative ordering
  3101. between atomic expressions and complex expressions can change and
  3102. often does. These changes are behavior preserving because
  3103. atomic expressions are pure.
  3104. {\if\edition\racketEd
  3105. Another well-known form for intermediate languages is the
  3106. \emph{administrative normal form}
  3107. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3108. \index{subject}{administrative normal form} \index{subject}{ANF}
  3109. %
  3110. The \LangVarANF{} language is not quite in ANF because it allows the
  3111. right-hand side of a \code{let} to be a complex expression, such as
  3112. another \code{let}. The flattening of nested \code{let} expressions is
  3113. instead one of the responsibilities of the \code{explicate\_control}
  3114. pass.
  3115. \fi}
  3116. {\if\edition\racketEd
  3117. We recommend implementing this pass with two mutually recursive
  3118. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3119. \code{rco\_atom} to subexpressions that need to become atomic and to
  3120. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3121. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3122. returns an expression. The \code{rco\_atom} function returns two
  3123. things: an atomic expression and an alist mapping temporary variables to
  3124. complex subexpressions. You can return multiple things from a function
  3125. using Racket's \key{values} form, and you can receive multiple things
  3126. from a function call using the \key{define-values} form.
  3127. \fi}
  3128. %
  3129. {\if\edition\pythonEd\pythonColor
  3130. %
  3131. We recommend implementing this pass with an auxiliary method named
  3132. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3133. Boolean that specifies whether the expression needs to become atomic
  3134. or not. The \code{rco\_exp} method should return a pair consisting of
  3135. the new expression and a list of pairs, associating new temporary
  3136. variables with their initializing expressions.
  3137. %
  3138. \fi}
  3139. {\if\edition\racketEd
  3140. %
  3141. In the example program with the expression \code{(+ 42 (-
  3142. 10))}, the subexpression \code{(- 10)} should be processed using the
  3143. \code{rco\_atom} function because it is an argument of the \code{+}
  3144. operator and therefore needs to become atomic. The output of
  3145. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3146. \begin{transformation}
  3147. \begin{lstlisting}
  3148. (- 10)
  3149. \end{lstlisting}
  3150. \compilesto
  3151. \begin{lstlisting}
  3152. tmp.1
  3153. ((tmp.1 . (- 10)))
  3154. \end{lstlisting}
  3155. \end{transformation}
  3156. \fi}
  3157. %
  3158. {\if\edition\pythonEd\pythonColor
  3159. %
  3160. Returning to the example program with the expression \code{42 + -10},
  3161. the subexpression \code{-10} should be processed using the
  3162. \code{rco\_exp} function with \code{True} as the second argument,
  3163. because \code{-10} is an argument of the \code{+} operator and
  3164. therefore needs to become atomic. The output of \code{rco\_exp}
  3165. applied to \code{-10} is as follows.
  3166. \begin{transformation}
  3167. \begin{lstlisting}
  3168. -10
  3169. \end{lstlisting}
  3170. \compilesto
  3171. \begin{lstlisting}
  3172. tmp_1
  3173. [(tmp_1, -10)]
  3174. \end{lstlisting}
  3175. \end{transformation}
  3176. %
  3177. \fi}
  3178. Take special care of programs, such as the following, that
  3179. %
  3180. \racket{bind a variable to an atomic expression.}
  3181. %
  3182. \python{assign an atomic expression to a variable.}
  3183. %
  3184. You should leave such \racket{variable bindings}\python{assignments}
  3185. unchanged, as shown in the program on the right:\\
  3186. %
  3187. {\if\edition\racketEd
  3188. \begin{transformation}
  3189. % var_test_20.rkt
  3190. \begin{lstlisting}
  3191. (let ([a 42])
  3192. (let ([b a])
  3193. b))
  3194. \end{lstlisting}
  3195. \compilesto
  3196. \begin{lstlisting}
  3197. (let ([a 42])
  3198. (let ([b a])
  3199. b))
  3200. \end{lstlisting}
  3201. \end{transformation}
  3202. \fi}
  3203. {\if\edition\pythonEd\pythonColor
  3204. \begin{transformation}
  3205. \begin{lstlisting}
  3206. a = 42
  3207. b = a
  3208. print(b)
  3209. \end{lstlisting}
  3210. \compilesto
  3211. \begin{lstlisting}
  3212. a = 42
  3213. b = a
  3214. print(b)
  3215. \end{lstlisting}
  3216. \end{transformation}
  3217. \fi}
  3218. %
  3219. \noindent A careless implementation might produce the following output with
  3220. unnecessary temporary variables.
  3221. \begin{center}
  3222. \begin{minipage}{0.4\textwidth}
  3223. {\if\edition\racketEd
  3224. \begin{lstlisting}
  3225. (let ([tmp.1 42])
  3226. (let ([a tmp.1])
  3227. (let ([tmp.2 a])
  3228. (let ([b tmp.2])
  3229. b))))
  3230. \end{lstlisting}
  3231. \fi}
  3232. {\if\edition\pythonEd\pythonColor
  3233. \begin{lstlisting}
  3234. tmp_1 = 42
  3235. a = tmp_1
  3236. tmp_2 = a
  3237. b = tmp_2
  3238. print(b)
  3239. \end{lstlisting}
  3240. \fi}
  3241. \end{minipage}
  3242. \end{center}
  3243. \begin{exercise}
  3244. \normalfont\normalsize
  3245. {\if\edition\racketEd
  3246. Implement the \code{remove\_complex\_operands} function in
  3247. \code{compiler.rkt}.
  3248. %
  3249. Create three new \LangVar{} programs that exercise the interesting
  3250. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3251. regarding file names described in exercise~\ref{ex:Lvar}.
  3252. %
  3253. In the \code{run-tests.rkt} script, add the following entry to the
  3254. list of \code{passes}, and then run the script to test your compiler.
  3255. \begin{lstlisting}
  3256. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3257. \end{lstlisting}
  3258. In debugging your compiler, it is often useful to see the intermediate
  3259. programs that are output from each pass. To print the intermediate
  3260. programs, place \lstinline{(debug-level 1)} before the call to
  3261. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3262. %
  3263. {\if\edition\pythonEd\pythonColor
  3264. Implement the \code{remove\_complex\_operands} pass in
  3265. \code{compiler.py}, creating auxiliary functions for each
  3266. nonterminal in the grammar, that is, \code{rco\_exp}
  3267. and \code{rco\_stmt}. We recommend that you use the function
  3268. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3269. \fi}
  3270. \end{exercise}
  3271. {\if\edition\pythonEd\pythonColor
  3272. \begin{exercise}
  3273. \normalfont\normalsize
  3274. \label{ex:Lvar}
  3275. Create five \LangVar{} programs that exercise the most interesting
  3276. parts of the \code{remove\_complex\_operands} pass. The five programs
  3277. should be placed in the subdirectory \key{tests/var}, and the file
  3278. names should end with the file extension \key{.py}. Run the
  3279. \key{run-tests.py} script in the support code to check whether the
  3280. output programs produce the same result as the input programs.
  3281. \end{exercise}
  3282. \fi}
  3283. {\if\edition\racketEd
  3284. \section{Explicate Control}
  3285. \label{sec:explicate-control-Lvar}
  3286. The \code{explicate\_control} pass compiles \LangVarANF{} programs into \LangCVar{}
  3287. programs that make the order of execution explicit in their
  3288. syntax. For now this amounts to flattening \key{let} constructs into a
  3289. sequence of assignment statements. For example, consider the following
  3290. \LangVar{} program:\\
  3291. % var_test_11.rkt
  3292. \begin{minipage}{0.96\textwidth}
  3293. \begin{lstlisting}
  3294. (let ([y (let ([x 20])
  3295. (+ x (let ([x 22]) x)))])
  3296. y)
  3297. \end{lstlisting}
  3298. \end{minipage}\\
  3299. %
  3300. The output of the previous pass is shown next, on the left, and the
  3301. output of \code{explicate\_control} is on the right. Recall that the
  3302. right-hand side of a \key{let} executes before its body, so that the order
  3303. of evaluation for this program is to assign \code{20} to \code{x.1},
  3304. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3305. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3306. this ordering explicit.
  3307. \begin{transformation}
  3308. \begin{lstlisting}
  3309. (let ([y (let ([x.1 20])
  3310. (let ([x.2 22])
  3311. (+ x.1 x.2)))])
  3312. y)
  3313. \end{lstlisting}
  3314. \compilesto
  3315. \begin{lstlisting}[language=C]
  3316. start:
  3317. x.1 = 20;
  3318. x.2 = 22;
  3319. y = (+ x.1 x.2);
  3320. return y;
  3321. \end{lstlisting}
  3322. \end{transformation}
  3323. \begin{figure}[tbp]
  3324. \begin{tcolorbox}[colback=white]
  3325. \begin{lstlisting}
  3326. (define (explicate_tail e)
  3327. (match e
  3328. [(Var x) ___]
  3329. [(Int n) (Return (Int n))]
  3330. [(Let x rhs body) ___]
  3331. [(Prim op es) ___]
  3332. [else (error "explicate_tail unhandled case" e)]))
  3333. (define (explicate_assign e x cont)
  3334. (match e
  3335. [(Var x) ___]
  3336. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3337. [(Let y rhs body) ___]
  3338. [(Prim op es) ___]
  3339. [else (error "explicate_assign unhandled case" e)]))
  3340. (define (explicate_control p)
  3341. (match p
  3342. [(Program info body) ___]))
  3343. \end{lstlisting}
  3344. \end{tcolorbox}
  3345. \caption{Skeleton for the \code{explicate\_control} pass.}
  3346. \label{fig:explicate-control-Lvar}
  3347. \end{figure}
  3348. The organization of this pass depends on the notion of tail position
  3349. to which we have alluded. Here is the definition.
  3350. \begin{definition}\normalfont
  3351. The following rules define when an expression is in \emph{tail
  3352. position}\index{subject}{tail position} for the language \LangVar{}.
  3353. \begin{enumerate}
  3354. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3355. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3356. \end{enumerate}
  3357. \end{definition}
  3358. We recommend implementing \code{explicate\_control} using two
  3359. recursive functions, \code{explicate\_tail} and
  3360. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3361. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3362. function should be applied to expressions in tail position, whereas the
  3363. \code{explicate\_assign} should be applied to expressions that occur on
  3364. the right-hand side of a \key{let}.
  3365. %
  3366. The \code{explicate\_tail} function takes an \Exp{} in \LangVarANF{} as
  3367. input and produces a \Tail{} in \LangCVar{} (see
  3368. figure~\ref{fig:c0-syntax}).
  3369. %
  3370. The \code{explicate\_assign} function takes an \Exp{} in \LangVarANF{},
  3371. the variable to which it is to be assigned, and a \Tail{} in
  3372. \LangCVar{} for the code that comes after the assignment. The
  3373. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3374. The \code{explicate\_assign} function is in accumulator-passing style:
  3375. the \code{cont} parameter is used for accumulating the output. This
  3376. accumulator-passing style plays an important role in the way that we
  3377. generate high-quality code for conditional expressions in
  3378. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3379. continuation because it contains the generated code that should come
  3380. after the current assignment. This code organization is also related
  3381. to continuation-passing style, except that \code{cont} is not what
  3382. happens next during compilation but is what happens next in the
  3383. generated code.
  3384. \begin{exercise}\normalfont\normalsize
  3385. %
  3386. Implement the \code{explicate\_control} function in
  3387. \code{compiler.rkt}. Create three new \LangVar{} programs that
  3388. exercise the code in \code{explicate\_control}.
  3389. %
  3390. In the \code{run-tests.rkt} script, add the following entry to the
  3391. list of \code{passes} and then run the script to test your compiler.
  3392. \begin{lstlisting}
  3393. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3394. \end{lstlisting}
  3395. \end{exercise}
  3396. \fi}
  3397. \section{Select Instructions}
  3398. \label{sec:select-Lvar}
  3399. \index{subject}{select instructions}
  3400. In the \code{select\_instructions} pass we begin the work of
  3401. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3402. language of this pass, \LangXVar{}, is a variant of x86 that still
  3403. uses variables, so we add an AST node of the form $\XVAR{\itm{var}}$
  3404. to the \Arg{} nonterminal of the \LangXInt{} abstract syntax
  3405. (figure~\ref{fig:x86-int-ast})\index{subject}{x86var@\LangXVar{}}.
  3406. \racket{We recommend implementing the \code{select\_instructions} with
  3407. three auxiliary functions, one for each of the nonterminals of
  3408. \LangCVar{}: $\Atm$, $\Stmt$, and $\Tail$.} \python{We recommend
  3409. implementing an auxiliary function named \code{select\_stmt} for the
  3410. $\Stmt$ nonterminal.}
  3411. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3412. same and integer constants change to immediates; that is, $\INT{n}$
  3413. changes to $\IMM{n}$.}
  3414. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3415. arithmetic operations. For example, consider the following addition
  3416. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3417. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3418. \key{addq} instruction in x86, but it performs an in-place update.
  3419. %
  3420. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3421. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3422. \begin{transformation}
  3423. {\if\edition\racketEd
  3424. \begin{lstlisting}
  3425. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3426. \end{lstlisting}
  3427. \fi}
  3428. {\if\edition\pythonEd\pythonColor
  3429. \begin{lstlisting}
  3430. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3431. \end{lstlisting}
  3432. \fi}
  3433. \compilesto
  3434. \begin{lstlisting}
  3435. movq |$\Arg_1$|, %rax
  3436. addq |$\Arg_2$|, %rax
  3437. movq %rax, |$\itm{var}$|
  3438. \end{lstlisting}
  3439. \end{transformation}
  3440. %
  3441. However, with some care we can generate shorter sequences of
  3442. instructions. Suppose that one or more of the arguments of the
  3443. addition is the same variable as the left-hand side of the assignment.
  3444. Then the assignment statement can be translated into a single
  3445. \key{addq} instruction, as follows.
  3446. \begin{transformation}
  3447. {\if\edition\racketEd
  3448. \begin{lstlisting}
  3449. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3450. \end{lstlisting}
  3451. \fi}
  3452. {\if\edition\pythonEd\pythonColor
  3453. \begin{lstlisting}
  3454. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3455. \end{lstlisting}
  3456. \fi}
  3457. \compilesto
  3458. \begin{lstlisting}
  3459. addq |$\Arg_1$|, |$\itm{var}$|
  3460. \end{lstlisting}
  3461. \end{transformation}
  3462. %
  3463. On the other hand, if $\Atm_2$ is not the same variable as the
  3464. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3465. and then add $\Arg_2$ to \itm{var}.
  3466. %
  3467. \begin{transformation}
  3468. {\if\edition\racketEd
  3469. \begin{lstlisting}
  3470. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3471. \end{lstlisting}
  3472. \fi}
  3473. {\if\edition\pythonEd\pythonColor
  3474. \begin{lstlisting}
  3475. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3476. \end{lstlisting}
  3477. \fi}
  3478. \compilesto
  3479. \begin{lstlisting}
  3480. movq |$\Arg_1$|, |$\itm{var}$|
  3481. addq |$\Arg_2$|, |$\itm{var}$|
  3482. \end{lstlisting}
  3483. \end{transformation}
  3484. The \READOP{} operation does not have a direct counterpart in x86
  3485. assembly, so we provide this functionality with the function
  3486. \code{read\_int} in the file \code{runtime.c}, written in
  3487. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3488. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3489. system}, or simply the \emph{runtime} for short. When compiling your
  3490. generated x86 assembly code, you need to compile \code{runtime.c} to
  3491. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3492. \code{-c}) and link it into the executable. For our purposes of code
  3493. generation, all you need to do is translate an assignment of
  3494. \READOP{} into a call to the \code{read\_int} function followed by a
  3495. move from \code{rax} to the left-hand side variable. (The
  3496. return value of a function is placed in \code{rax}.)
  3497. \begin{transformation}
  3498. {\if\edition\racketEd
  3499. \begin{lstlisting}
  3500. |$\itm{var}$| = (read);
  3501. \end{lstlisting}
  3502. \fi}
  3503. {\if\edition\pythonEd\pythonColor
  3504. \begin{lstlisting}
  3505. |$\itm{var}$| = input_int();
  3506. \end{lstlisting}
  3507. \fi}
  3508. \compilesto
  3509. \begin{lstlisting}
  3510. callq read_int
  3511. movq %rax, |$\itm{var}$|
  3512. \end{lstlisting}
  3513. \end{transformation}
  3514. {\if\edition\pythonEd\pythonColor
  3515. %
  3516. Similarly, we translate the \code{print} operation, shown below, into
  3517. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3518. In x86, the first six arguments to functions are passed in registers,
  3519. with the first argument passed in register \code{rdi}. So we move the
  3520. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3521. \code{callq} instruction.
  3522. \begin{transformation}
  3523. \begin{lstlisting}
  3524. print(|$\Atm$|)
  3525. \end{lstlisting}
  3526. \compilesto
  3527. \begin{lstlisting}
  3528. movq |$\Arg$|, %rdi
  3529. callq print_int
  3530. \end{lstlisting}
  3531. \end{transformation}
  3532. %
  3533. \fi}
  3534. {\if\edition\racketEd
  3535. %
  3536. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3537. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3538. assignment to the \key{rax} register followed by a jump to
  3539. the label \key{conclusion}. Later, in Section~\ref{sec:print-x86},
  3540. we discuss the generation of the \key{conclusion} block.
  3541. In the meantime, the interpreter for \LangXVar{} recognizes a jump
  3542. to \key{conclusion} as the end of the program.
  3543. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3544. recursively and then append the resulting instructions.
  3545. %
  3546. \fi}
  3547. {\if\edition\pythonEd\pythonColor
  3548. We recommend that you use the function \code{utils.label\_name} to
  3549. transform strings into labels, for example, in
  3550. the target of the \code{callq} instruction. This practice makes your
  3551. compiler portable across Linux and Mac OS X, which requires an underscore
  3552. prefixed to all labels.
  3553. \fi}
  3554. \begin{exercise}
  3555. \normalfont\normalsize
  3556. {\if\edition\racketEd
  3557. Implement the \code{select\_instructions} pass in
  3558. \code{compiler.rkt}. Create three new example programs that are
  3559. designed to exercise all the interesting cases in this pass.
  3560. %
  3561. In the \code{run-tests.rkt} script, add the following entry to the
  3562. list of \code{passes} and then run the script to test your compiler.
  3563. \begin{lstlisting}
  3564. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3565. \end{lstlisting}
  3566. \fi}
  3567. {\if\edition\pythonEd\pythonColor
  3568. Implement the \key{select\_instructions} pass in
  3569. \code{compiler.py}. Create three new example programs that are
  3570. designed to exercise all the interesting cases in this pass.
  3571. Run the \code{run-tests.py} script to check
  3572. whether the output programs produce the same result as the input
  3573. programs.
  3574. \fi}
  3575. \end{exercise}
  3576. \section{Assign Homes}
  3577. \label{sec:assign-Lvar}
  3578. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3579. \LangXVar{} programs that no longer use program variables. Thus, the
  3580. \code{assign\_homes} pass is responsible for placing all the program
  3581. variables in registers or on the stack. For runtime efficiency, it is
  3582. better to place variables in registers, but because there are only
  3583. sixteen registers, some programs must necessarily resort to placing
  3584. some variables on the stack. In this chapter we focus on the mechanics
  3585. of placing variables on the stack. We study an algorithm for placing
  3586. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3587. Consider again the following \LangVar{} program from
  3588. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3589. % var_test_20.rkt
  3590. \begin{minipage}{0.96\textwidth}
  3591. {\if\edition\racketEd
  3592. \begin{lstlisting}
  3593. (let ([a 42])
  3594. (let ([b a])
  3595. b))
  3596. \end{lstlisting}
  3597. \fi}
  3598. {\if\edition\pythonEd\pythonColor
  3599. \begin{lstlisting}
  3600. a = 42
  3601. b = a
  3602. print(b)
  3603. \end{lstlisting}
  3604. \fi}
  3605. \end{minipage}\\
  3606. %
  3607. The output of \code{select\_instructions} is shown next, on the left,
  3608. and the output of \code{assign\_homes} is on the right.
  3609. In this example, we assign variable \code{a} to stack location
  3610. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3611. {\if\edition\racketEd
  3612. \begin{transformation}
  3613. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3614. movq $42, a
  3615. movq a, b
  3616. movq b, %rax
  3617. \end{lstlisting}
  3618. \compilesto
  3619. %stack-space: 16
  3620. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3621. movq $42, -8(%rbp)
  3622. movq -8(%rbp), -16(%rbp)
  3623. movq -16(%rbp), %rax
  3624. \end{lstlisting}
  3625. \end{transformation}
  3626. \fi}
  3627. {\if\edition\pythonEd
  3628. \begin{transformation}
  3629. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3630. movq $42, a
  3631. movq a, b
  3632. movq b, %rdi
  3633. callq print_int
  3634. \end{lstlisting}
  3635. \compilesto
  3636. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3637. movq $42, -8(%rbp)
  3638. movq -8(%rbp), -16(%rbp)
  3639. movq -16(%rbp), %rdi
  3640. callq print_int
  3641. \end{lstlisting}
  3642. \end{transformation}
  3643. \fi}
  3644. \racket{
  3645. The \code{assign\_homes} pass should replace all variables
  3646. with stack locations.
  3647. The list of variables can be obtained from
  3648. the \code{locals-types} entry in the $\itm{info}$ of the
  3649. \code{X86Program} node. The \code{locals-types} entry is an alist
  3650. mapping all the variables in the program to their types
  3651. (for now, just \code{Integer}).
  3652. As an aside, the \code{locals-types} entry is
  3653. computed by \code{type-check-Cvar} in the support code, which
  3654. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3655. which you should propagate to the \code{X86Program} node.}
  3656. %
  3657. \python{The \code{assign\_homes} pass should replace all uses of
  3658. variables with stack locations.}
  3659. %
  3660. In the process of assigning variables to stack locations, it is
  3661. convenient for you to compute and store the size of the frame (in
  3662. bytes) in
  3663. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3664. %
  3665. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3666. %
  3667. which is needed later to generate the conclusion of the \code{main}
  3668. procedure. The x86-64 standard requires the frame size to be a
  3669. multiple of 16 bytes.\index{subject}{frame}
  3670. % TODO: store the number of variables instead? -Jeremy
  3671. \begin{exercise}\normalfont\normalsize
  3672. Implement the \code{assign\_homes} pass in
  3673. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3674. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3675. grammar. We recommend that the auxiliary functions take an extra
  3676. parameter that maps variable names to homes (stack locations for now).
  3677. %
  3678. {\if\edition\racketEd
  3679. In the \code{run-tests.rkt} script, add the following entry to the
  3680. list of \code{passes} and then run the script to test your compiler.
  3681. \begin{lstlisting}
  3682. (list "assign homes" assign-homes interp_x86-0)
  3683. \end{lstlisting}
  3684. \fi}
  3685. {\if\edition\pythonEd\pythonColor
  3686. Run the \code{run-tests.py} script to check
  3687. whether the output programs produce the same result as the input
  3688. programs.
  3689. \fi}
  3690. \end{exercise}
  3691. \section{Patch Instructions}
  3692. \label{sec:patch-s0}
  3693. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3694. \LangXInt{} by making sure that each instruction adheres to the
  3695. restriction that at most one argument of an instruction may be a
  3696. memory reference.
  3697. We return to the following example.\\
  3698. \begin{minipage}{0.5\textwidth}
  3699. % var_test_20.rkt
  3700. {\if\edition\racketEd
  3701. \begin{lstlisting}
  3702. (let ([a 42])
  3703. (let ([b a])
  3704. b))
  3705. \end{lstlisting}
  3706. \fi}
  3707. {\if\edition\pythonEd\pythonColor
  3708. \begin{lstlisting}
  3709. a = 42
  3710. b = a
  3711. print(b)
  3712. \end{lstlisting}
  3713. \fi}
  3714. \end{minipage}\\
  3715. The \code{assign\_homes} pass produces the following translation. \\
  3716. \begin{minipage}{0.5\textwidth}
  3717. {\if\edition\racketEd
  3718. \begin{lstlisting}
  3719. movq $42, -8(%rbp)
  3720. movq -8(%rbp), -16(%rbp)
  3721. movq -16(%rbp), %rax
  3722. \end{lstlisting}
  3723. \fi}
  3724. {\if\edition\pythonEd\pythonColor
  3725. \begin{lstlisting}
  3726. movq $42, -8(%rbp)
  3727. movq -8(%rbp), -16(%rbp)
  3728. movq -16(%rbp), %rdi
  3729. callq print_int
  3730. \end{lstlisting}
  3731. \fi}
  3732. \end{minipage}\\
  3733. The second \key{movq} instruction is problematic because both
  3734. arguments are stack locations. We suggest fixing this problem by
  3735. moving from the source location to the register \key{rax} and then
  3736. from \key{rax} to the destination location, as follows.
  3737. \begin{lstlisting}
  3738. movq -8(%rbp), %rax
  3739. movq %rax, -16(%rbp)
  3740. \end{lstlisting}
  3741. There is a similar corner case that also needs to be dealt with. If
  3742. one argument is an immediate integer larger than $32$ bits (either
  3743. greater or equal to $2^{31}$ or less than $-2^{31}$) and the
  3744. other is a memory reference, then the instruction is invalid. One can
  3745. fix this, for example, by first moving the immediate integer into
  3746. \key{rax} and then using \key{rax} in place of the integer.
  3747. \begin{exercise}
  3748. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3749. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3750. Create three new example programs that are
  3751. designed to exercise all the interesting cases in this pass.
  3752. %
  3753. {\if\edition\racketEd
  3754. In the \code{run-tests.rkt} script, add the following entry to the
  3755. list of \code{passes} and then run the script to test your compiler.
  3756. \begin{lstlisting}
  3757. (list "patch instructions" patch_instructions interp_x86-0)
  3758. \end{lstlisting}
  3759. \fi}
  3760. {\if\edition\pythonEd\pythonColor
  3761. Run the \code{run-tests.py} script to check
  3762. whether the output programs produce the same result as the input
  3763. programs.
  3764. \fi}
  3765. \end{exercise}
  3766. \section{Generate Prelude and Conclusion}
  3767. \label{sec:print-x86}
  3768. \index{subject}{prelude}\index{subject}{conclusion}
  3769. The last step of the compiler from \LangVar{} to x86 is to generate
  3770. the \code{main} function with a prelude and conclusion wrapped around
  3771. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3772. discussed in section~\ref{sec:x86}.
  3773. When running on Mac OS X, your compiler should prefix an underscore to
  3774. all labels (for example, changing \key{main} to \key{\_main}).
  3775. %
  3776. \racket{The Racket call \code{(system-type 'os)} is useful for
  3777. determining which operating system the compiler is running on. It
  3778. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3779. %
  3780. \python{The Python \code{platform.system}
  3781. function returns \code{\textquotesingle Linux\textquotesingle},
  3782. \code{\textquotesingle Windows\textquotesingle}, or
  3783. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3784. \begin{exercise}\normalfont\normalsize
  3785. %
  3786. Implement the \key{prelude\_and\_conclusion} pass in
  3787. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3788. %
  3789. {\if\edition\racketEd
  3790. In the \code{run-tests.rkt} script, add the following entry to the
  3791. list of \code{passes} and then run the script to test your compiler.
  3792. \begin{lstlisting}
  3793. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3794. \end{lstlisting}
  3795. %
  3796. Uncomment the call to the \key{compiler-tests} function
  3797. (appendix~\ref{appendix:utilities}), which tests your complete
  3798. compiler by executing the generated x86 code. It translates the x86
  3799. AST that you produce into a string by invoking the \code{print-x86}
  3800. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3801. the provided \key{runtime.c} file to \key{runtime.o} using
  3802. \key{gcc}. Run the script to test your compiler.
  3803. %
  3804. \fi}
  3805. {\if\edition\pythonEd\pythonColor
  3806. %
  3807. Run the \code{run-tests.py} script to check whether the output
  3808. programs produce the same result as the input programs. That script
  3809. translates the x86 AST that you produce into a string by invoking the
  3810. \code{repr} method that is implemented by the x86 AST classes in
  3811. \code{x86\_ast.py}.
  3812. %
  3813. \fi}
  3814. \end{exercise}
  3815. \section{Challenge: Partial Evaluator for \LangVar{}}
  3816. \label{sec:pe-Lvar}
  3817. \index{subject}{partialevaluation@partial evaluation}
  3818. This section describes two optional challenge exercises that involve
  3819. adapting and improving the partial evaluator for \LangInt{} that was
  3820. introduced in section~\ref{sec:partial-evaluation}.
  3821. \begin{exercise}\label{ex:pe-Lvar}
  3822. \normalfont\normalsize
  3823. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3824. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3825. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3826. %
  3827. \racket{\key{let} binding}\python{assignment}
  3828. %
  3829. to the \LangInt{} language, so you will need to add cases for them in
  3830. the \code{pe\_exp}
  3831. %
  3832. \racket{function.}
  3833. %
  3834. \python{and \code{pe\_stmt} functions.}
  3835. %
  3836. Once complete, add the partial evaluation pass to the front of your
  3837. compiler.
  3838. \python{In particular, add a method named \code{partial\_eval} to
  3839. the \code{Compiler} class in \code{compiler.py}.}
  3840. Check that your compiler still passes all the
  3841. tests.
  3842. \end{exercise}
  3843. \begin{exercise}
  3844. \normalfont\normalsize
  3845. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3846. \code{pe\_add} auxiliary functions with functions that know more about
  3847. arithmetic. For example, your partial evaluator should translate
  3848. {\if\edition\racketEd
  3849. \[
  3850. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3851. \code{(+ 2 (read))}
  3852. \]
  3853. \fi}
  3854. {\if\edition\pythonEd\pythonColor
  3855. \[
  3856. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3857. \code{2 + input\_int()}
  3858. \]
  3859. \fi}
  3860. %
  3861. To accomplish this, the \code{pe\_exp} function should produce output
  3862. in the form of the $\itm{residual}$ nonterminal of the following
  3863. grammar. The idea is that when processing an addition expression, we
  3864. can always produce one of the following: (1) an integer constant, (2)
  3865. an addition expression with an integer constant on the left-hand side
  3866. but not the right-hand side, or (3) an addition expression in which
  3867. neither subexpression is a constant.
  3868. %
  3869. {\if\edition\racketEd
  3870. \[
  3871. \begin{array}{lcl}
  3872. \itm{inert} &::=& \Var
  3873. \MID \LP\key{read}\RP
  3874. \MID \LP\key{-} ~\Var\RP
  3875. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3876. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3877. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3878. \itm{residual} &::=& \Int
  3879. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3880. \MID \itm{inert}
  3881. \end{array}
  3882. \]
  3883. \fi}
  3884. {\if\edition\pythonEd\pythonColor
  3885. \[
  3886. \begin{array}{lcl}
  3887. \itm{inert} &::=& \Var
  3888. \MID \key{input\_int}\LP\RP
  3889. \MID \key{-} \Var
  3890. \MID \key{-} \key{input\_int}\LP\RP
  3891. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3892. \itm{residual} &::=& \Int
  3893. \MID \Int ~ \key{+} ~ \itm{inert}
  3894. \MID \itm{inert}
  3895. \end{array}
  3896. \]
  3897. \fi}
  3898. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3899. inputs are $\itm{residual}$ expressions and they should return
  3900. $\itm{residual}$ expressions. Once the improvements are complete,
  3901. make sure that your compiler still passes all the tests. After
  3902. all, fast code is useless if it produces incorrect results!
  3903. \end{exercise}
  3904. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3905. {\if\edition\pythonEd\pythonColor
  3906. \chapter{Parsing}
  3907. \label{ch:parsing}
  3908. \setcounter{footnote}{0}
  3909. \index{subject}{parsing}
  3910. In this chapter we learn how to use the Lark parser
  3911. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3912. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3913. You are then asked to create a parser for \LangVar{} using Lark.
  3914. We also describe the parsing algorithms used inside Lark, studying the
  3915. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3916. A parser framework such as Lark takes in a specification of the
  3917. concrete syntax and an input program and produces a parse tree. Even
  3918. though a parser framework does most of the work for us, using one
  3919. properly requires some knowledge. In particular, we must learn about
  3920. its specification languages and we must learn how to deal with
  3921. ambiguity in our language specifications. Also, some algorithms, such
  3922. as LALR(1), place restrictions on the grammars they can handle, in
  3923. which case knowing the algorithm helps with trying to decipher the
  3924. error messages.
  3925. The process of parsing is traditionally subdivided into two phases:
  3926. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3927. analysis} (also called parsing). The lexical analysis phase
  3928. translates the sequence of characters into a sequence of
  3929. \emph{tokens}, that is, words consisting of several characters. The
  3930. parsing phase organizes the tokens into a \emph{parse tree} that
  3931. captures how the tokens were matched by rules in the grammar of the
  3932. language. The reason for the subdivision into two phases is to enable
  3933. the use of a faster but less powerful algorithm for lexical analysis
  3934. and the use of a slower but more powerful algorithm for parsing.
  3935. %
  3936. %% Likewise, parser generators typical come in pairs, with separate
  3937. %% generators for the lexical analyzer (or lexer for short) and for the
  3938. %% parser. A particularly influential pair of generators were
  3939. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3940. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3941. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3942. %% Compiler Compiler.
  3943. %
  3944. The Lark parser framework that we use in this chapter includes both
  3945. lexical analyzers and parsers. The next section discusses lexical
  3946. analysis, and the remainder of the chapter discusses parsing.
  3947. \section{Lexical Analysis and Regular Expressions}
  3948. \label{sec:lex}
  3949. The lexical analyzers produced by Lark turn a sequence of characters
  3950. (a string) into a sequence of token objects. For example, a Lark
  3951. generated lexer for \LangInt{} converts the string
  3952. \begin{lstlisting}
  3953. 'print(1 + 3)'
  3954. \end{lstlisting}
  3955. \noindent into the following sequence of token objects:
  3956. \begin{center}
  3957. \begin{minipage}{0.95\textwidth}
  3958. \begin{lstlisting}
  3959. Token('PRINT', 'print')
  3960. Token('LPAR', '(')
  3961. Token('INT', '1')
  3962. Token('PLUS', '+')
  3963. Token('INT', '3')
  3964. Token('RPAR', ')')
  3965. Token('NEWLINE', '\n')
  3966. \end{lstlisting}
  3967. \end{minipage}
  3968. \end{center}
  3969. Each token includes a field for its \code{type}, such as \skey{INT},
  3970. and a field for its \code{value}, such as \skey{1}.
  3971. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3972. specification language for Lark's lexer is one regular expression for
  3973. each type of token. The term \emph{regular} comes from the term
  3974. \emph{regular languages}, which are the languages that can be
  3975. recognized by a finite state machine. A \emph{regular expression} is a
  3976. pattern formed of the following core elements:\index{subject}{regular
  3977. expression}\footnote{Regular expressions traditionally include the
  3978. empty regular expression that matches any zero-length part of a
  3979. string, but Lark does not support the empty regular expression.}
  3980. \begin{itemize}
  3981. \item A single character $c$ is a regular expression, and it matches
  3982. only itself. For example, the regular expression \code{a} matches
  3983. only the string \skey{a}.
  3984. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3985. R_2$ form a regular expression that matches any string that matches
  3986. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3987. matches the string \skey{a} and the string \skey{c}.
  3988. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3989. expression that matches any string that can be formed by
  3990. concatenating two strings, where the first string matches $R_1$ and
  3991. the second string matches $R_2$. For example, the regular expression
  3992. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3993. (Parentheses can be used to control the grouping of operators within
  3994. a regular expression.)
  3995. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3996. Kleene closure) is a regular expression that matches any string that
  3997. can be formed by concatenating zero or more strings that each match
  3998. the regular expression $R$. For example, the regular expression
  3999. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  4000. \skey{abc}.
  4001. \end{itemize}
  4002. For our convenience, Lark also accepts the following extended set of
  4003. regular expressions that are automatically translated into the core
  4004. regular expressions.
  4005. \begin{itemize}
  4006. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  4007. c_n]$ is a regular expression that matches any one of the
  4008. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  4009. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  4010. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  4011. a regular expression that matches any character between $c_1$ and
  4012. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  4013. letter in the alphabet.
  4014. \item A regular expression followed by the plus symbol $R\ttm{+}$
  4015. is a regular expression that matches any string that can
  4016. be formed by concatenating one or more strings that each match $R$.
  4017. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  4018. matches \skey{b} and \skey{bzca}.
  4019. \item A regular expression followed by a question mark $R\ttm{?}$
  4020. is a regular expression that matches any string that either
  4021. matches $R$ or is the empty string.
  4022. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  4023. \end{itemize}
  4024. In a Lark grammar file, each kind of token is specified by a
  4025. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  4026. that consists of the name of the terminal followed by a colon followed
  4027. by a sequence of literals. The literals include strings such as
  4028. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  4029. terminal names, and literals composed using the regular expression
  4030. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  4031. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  4032. \begin{center}
  4033. \begin{minipage}{0.95\textwidth}
  4034. \begin{lstlisting}
  4035. DIGIT: /[0-9]/
  4036. INT: "-"? DIGIT+
  4037. NEWLINE: (/\r/? /\n/)+
  4038. \end{lstlisting}
  4039. \end{minipage}
  4040. \end{center}
  4041. \section{Grammars and Parse Trees}
  4042. \label{sec:CFG}
  4043. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4044. specify the abstract syntax of a language. We now take a closer look
  4045. at using grammar rules to specify the concrete syntax. Recall that
  4046. each rule has a left-hand side and a right-hand side, where the
  4047. left-hand side is a nonterminal and the right-hand side is a pattern
  4048. that defines what can be parsed as that nonterminal. For concrete
  4049. syntax, each right-hand side expresses a pattern for a string instead
  4050. of a pattern for an abstract syntax tree. In particular, each
  4051. right-hand side is a sequence of
  4052. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4053. terminal or a nonterminal. The nonterminals play the same role as in
  4054. the abstract syntax, defining categories of syntax. The nonterminals
  4055. of a grammar include the tokens defined in the lexer and all the
  4056. nonterminals defined by the grammar rules.
  4057. As an example, let us take a closer look at the concrete syntax of the
  4058. \LangInt{} language, repeated here.
  4059. \[
  4060. \begin{array}{l}
  4061. \LintGrammarPython \\
  4062. \begin{array}{rcl}
  4063. \LangInt{} &::=& \Stmt^{*}
  4064. \end{array}
  4065. \end{array}
  4066. \]
  4067. The Lark syntax for grammar rules differs slightly from the variant of
  4068. BNF that we use in this book. In particular, the notation $::=$ is
  4069. replaced by a single colon, and the use of typewriter font for string
  4070. literals is replaced by quotation marks. The following grammar serves
  4071. as a first draft of a Lark grammar for \LangInt{}.
  4072. \begin{center}
  4073. \begin{minipage}{0.95\textwidth}
  4074. \begin{lstlisting}[escapechar=$]
  4075. exp: INT
  4076. | "input_int" "(" ")"
  4077. | "-" exp
  4078. | exp "+" exp
  4079. | exp "-" exp
  4080. | "(" exp ")"
  4081. stmt_list:
  4082. | stmt NEWLINE stmt_list
  4083. lang_int: stmt_list
  4084. \end{lstlisting}
  4085. \end{minipage}
  4086. \end{center}
  4087. Let us begin by discussing the rule \code{exp: INT}, which says that
  4088. if the lexer matches a string to \code{INT}, then the parser also
  4089. categorizes the string as an \code{exp}. Recall that in
  4090. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4091. nonterminal with a sentence in English. Here we specify \code{INT}
  4092. more formally using a type of token \code{INT} and its regular
  4093. expression \code{"-"? DIGIT+}.
  4094. The rule \code{exp: exp "+" exp} says that any string that matches
  4095. \code{exp}, followed by the \code{+} character, followed by another
  4096. string that matches \code{exp}, is itself an \code{exp}. For example,
  4097. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4098. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4099. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4100. \code{exp}. We can visualize the application of grammar rules to parse
  4101. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4102. internal node in the tree is an application of a grammar rule and is
  4103. labeled with its left-hand side nonterminal. Each leaf node is a
  4104. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4105. shown in figure~\ref{fig:simple-parse-tree}.
  4106. \begin{figure}[tbp]
  4107. \begin{tcolorbox}[colback=white]
  4108. \centering
  4109. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4110. \end{tcolorbox}
  4111. \caption{The parse tree for \lstinline{'1+3'}.}
  4112. \label{fig:simple-parse-tree}
  4113. \end{figure}
  4114. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4115. following parse tree as represented by \code{Tree} and \code{Token}
  4116. objects.
  4117. \begin{lstlisting}
  4118. Tree('lang_int',
  4119. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4120. Tree('exp', [Token('INT', '3')])])]),
  4121. Token('NEWLINE', '\n')])
  4122. \end{lstlisting}
  4123. The nodes that come from the lexer are \code{Token} objects, whereas
  4124. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4125. object has a \code{data} field containing the name of the nonterminal
  4126. for the grammar rule that was applied. Each \code{Tree} object also
  4127. has a \code{children} field that is a list containing trees and/or
  4128. tokens. Note that Lark does not produce nodes for string literals in
  4129. the grammar. For example, the \code{Tree} node for the addition
  4130. expression has only two children for the two integers but is missing
  4131. its middle child for the \code{"+"} terminal. This would be
  4132. problematic except that Lark provides a mechanism for customizing the
  4133. \code{data} field of each \code{Tree} node on the basis of which rule was
  4134. applied. Next to each alternative in a grammar rule, write \code{->}
  4135. followed by a string that you want to appear in the \code{data}
  4136. field. The following is a second draft of a Lark grammar for
  4137. \LangInt{}, this time with more specific labels on the \code{Tree}
  4138. nodes.
  4139. \begin{center}
  4140. \begin{minipage}{0.95\textwidth}
  4141. \begin{lstlisting}[escapechar=$]
  4142. exp: INT -> int
  4143. | "input_int" "(" ")" -> input_int
  4144. | "-" exp -> usub
  4145. | exp "+" exp -> add
  4146. | exp "-" exp -> sub
  4147. | "(" exp ")" -> paren
  4148. stmt: "print" "(" exp ")" -> print
  4149. | exp -> expr
  4150. stmt_list: -> empty_stmt
  4151. | stmt NEWLINE stmt_list -> add_stmt
  4152. lang_int: stmt_list -> module
  4153. \end{lstlisting}
  4154. \end{minipage}
  4155. \end{center}
  4156. Here is the resulting parse tree.
  4157. \begin{lstlisting}
  4158. Tree('module',
  4159. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4160. Tree('int', [Token('INT', '3')])])]),
  4161. Token('NEWLINE', '\n')])
  4162. \end{lstlisting}
  4163. \section{Ambiguous Grammars}
  4164. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4165. can be parsed in more than one way. For example, consider the string
  4166. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4167. our draft grammar, resulting in the two parse trees shown in
  4168. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4169. interpreting the second parse tree would yield \code{-4} even through
  4170. the correct answer is \code{2}.
  4171. \begin{figure}[tbp]
  4172. \begin{tcolorbox}[colback=white]
  4173. \centering
  4174. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4175. \end{tcolorbox}
  4176. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4177. \label{fig:ambig-parse-tree}
  4178. \end{figure}
  4179. To deal with this problem we can change the grammar by categorizing
  4180. the syntax in a more fine-grained fashion. In this case we want to
  4181. disallow the application of the rule \code{exp: exp "-" exp} when the
  4182. child on the right is an addition. To do this we can replace the
  4183. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4184. the expressions except for addition, as in the following.
  4185. \begin{center}
  4186. \begin{minipage}{0.95\textwidth}
  4187. \begin{lstlisting}[escapechar=$]
  4188. exp: exp "-" exp_no_add -> sub
  4189. | exp "+" exp -> add
  4190. | exp_no_add
  4191. exp_no_add: INT -> int
  4192. | "input_int" "(" ")" -> input_int
  4193. | "-" exp -> usub
  4194. | exp "-" exp_no_add -> sub
  4195. | "(" exp ")" -> paren
  4196. \end{lstlisting}
  4197. \end{minipage}
  4198. \end{center}
  4199. However, there remains some ambiguity in the grammar. For example, the
  4200. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4201. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4202. (incorrect). That is, subtraction is left associative. Likewise,
  4203. addition in Python is left associative. We also need to consider the
  4204. interaction of unary subtraction with both addition and
  4205. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4206. has higher \emph{precedence}\index{subject}{precedence} than addition
  4207. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4208. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4209. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4210. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4211. all the other expressions, and it uses \code{exp\_hi} for the second
  4212. child in the rules for addition and subtraction. Furthermore, unary
  4213. subtraction uses \code{exp\_hi} for its child.
  4214. For languages with more operators and more precedence levels, one must
  4215. refine the \code{exp} nonterminal into several nonterminals, one for
  4216. each precedence level.
  4217. \begin{figure}[tbp]
  4218. \begin{tcolorbox}[colback=white]
  4219. \centering
  4220. \begin{lstlisting}[escapechar=$]
  4221. exp: exp "+" exp_hi -> add
  4222. | exp "-" exp_hi -> sub
  4223. | exp_hi
  4224. exp_hi: INT -> int
  4225. | "input_int" "(" ")" -> input_int
  4226. | "-" exp_hi -> usub
  4227. | "(" exp ")" -> paren
  4228. stmt: "print" "(" exp ")" -> print
  4229. | exp -> expr
  4230. stmt_list: -> empty_stmt
  4231. | stmt NEWLINE stmt_list -> add_stmt
  4232. lang_int: stmt_list -> module
  4233. \end{lstlisting}
  4234. \end{tcolorbox}
  4235. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4236. \label{fig:Lint-lark-grammar}
  4237. \end{figure}
  4238. \section{From Parse Trees to Abstract Syntax Trees}
  4239. As we have seen, the output of a Lark parser is a parse tree, that is,
  4240. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4241. step is to convert the parse tree to an abstract syntax tree. This can
  4242. be accomplished with a recursive function that inspects the
  4243. \code{data} field of each node and then constructs the corresponding
  4244. AST node, using recursion to handle its children. The following is an
  4245. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4246. \begin{center}
  4247. \begin{minipage}{0.95\textwidth}
  4248. \begin{lstlisting}
  4249. def parse_tree_to_ast(e):
  4250. if e.data == 'int':
  4251. return Constant(int(e.children[0].value))
  4252. elif e.data == 'input_int':
  4253. return Call(Name('input_int'), [])
  4254. elif e.data == 'add':
  4255. e1, e2 = e.children
  4256. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4257. ...
  4258. else:
  4259. raise Exception('unhandled parse tree', e)
  4260. \end{lstlisting}
  4261. \end{minipage}
  4262. \end{center}
  4263. \begin{exercise}
  4264. \normalfont\normalsize
  4265. %
  4266. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4267. default parsing algorithm (Earley) with the \code{ambiguity} option
  4268. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4269. output will include multiple parse trees that will indicate to you
  4270. that there is a problem with your grammar. Your parser should ignore
  4271. white space, so we recommend using Lark's \code{\%ignore} directive
  4272. as follows.
  4273. \begin{lstlisting}
  4274. %import common.WS_INLINE
  4275. %ignore WS_INLINE
  4276. \end{lstlisting}
  4277. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4278. Lark parser instead of using the \code{parse} function from
  4279. the \code{ast} module. Test your compiler on all the \LangVar{}
  4280. programs that you have created, and create four additional programs
  4281. that test for ambiguities in your grammar.
  4282. \end{exercise}
  4283. \section{Earley's Algorithm}
  4284. \label{sec:earley}
  4285. In this section we discuss the parsing algorithm of
  4286. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4287. algorithm is powerful in that it can handle any context-free grammar,
  4288. which makes it easy to use, but it is not a particularly
  4289. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4290. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4291. the number of tokens in the input
  4292. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4293. learn about the LALR(1) algorithm, which is more efficient but cannot
  4294. handle all context-free grammars.
  4295. Earley's algorithm can be viewed as an interpreter; it treats the
  4296. grammar as the program being interpreted, and it treats the concrete
  4297. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4298. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4299. keep track of its progress and to store its results. The chart is an
  4300. array with one slot for each position in the input string, where
  4301. position $0$ is before the first character and position $n$ is
  4302. immediately after the last character. So, the array has length $n+1$
  4303. for an input string of length $n$. Each slot in the chart contains a
  4304. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4305. with a period indicating how much of its right-hand side has already
  4306. been parsed. For example, the dotted rule
  4307. \begin{lstlisting}
  4308. exp: exp "+" . exp_hi
  4309. \end{lstlisting}
  4310. represents a partial parse that has matched an \code{exp} followed by
  4311. \code{+} but has not yet parsed an \code{exp} to the right of
  4312. \code{+}.
  4313. %
  4314. Earley's algorithm starts with an initialization phase and then
  4315. repeats three actions---prediction, scanning, and completion---for as
  4316. long as opportunities arise. We demonstrate Earley's algorithm on a
  4317. running example, parsing the following program:
  4318. \begin{lstlisting}
  4319. print(1 + 3)
  4320. \end{lstlisting}
  4321. The algorithm's initialization phase creates dotted rules for all the
  4322. grammar rules whose left-hand side is the start symbol and places them
  4323. in slot $0$ of the chart. We also record the starting position of the
  4324. dotted rule in parentheses on the right. For example, given the
  4325. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4326. \begin{lstlisting}
  4327. lang_int: . stmt_list (0)
  4328. \end{lstlisting}
  4329. in slot $0$ of the chart. The algorithm then proceeds with
  4330. \emph{prediction} actions in which it adds more dotted rules to the
  4331. chart based on the nonterminals that come immediately after a period. In
  4332. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4333. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4334. period at the beginning of their right-hand sides, as follows:
  4335. \begin{lstlisting}
  4336. stmt_list: . (0)
  4337. stmt_list: . stmt NEWLINE stmt_list (0)
  4338. \end{lstlisting}
  4339. We continue to perform prediction actions as more opportunities
  4340. arise. For example, the \code{stmt} nonterminal now appears after a
  4341. period, so we add all the rules for \code{stmt}.
  4342. \begin{lstlisting}
  4343. stmt: . "print" "(" exp ")" (0)
  4344. stmt: . exp (0)
  4345. \end{lstlisting}
  4346. This reveals yet more opportunities for prediction, so we add the grammar
  4347. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4348. \begin{lstlisting}[escapechar=$]
  4349. exp: . exp "+" exp_hi (0)
  4350. exp: . exp "-" exp_hi (0)
  4351. exp: . exp_hi (0)
  4352. exp_hi: . INT (0)
  4353. exp_hi: . "input_int" "(" ")" (0)
  4354. exp_hi: . "-" exp_hi (0)
  4355. exp_hi: . "(" exp ")" (0)
  4356. \end{lstlisting}
  4357. We have exhausted the opportunities for prediction, so the algorithm
  4358. proceeds to \emph{scanning}, in which we inspect the next input token
  4359. and look for a dotted rule at the current position that has a matching
  4360. terminal immediately following the period. In our running example, the
  4361. first input token is \code{"print"}, so we identify the rule in slot
  4362. $0$ of the chart where \code{"print"} follows the period:
  4363. \begin{lstlisting}
  4364. stmt: . "print" "(" exp ")" (0)
  4365. \end{lstlisting}
  4366. We advance the period past \code{"print"} and add the resulting rule
  4367. to slot $1$:
  4368. \begin{lstlisting}
  4369. stmt: "print" . "(" exp ")" (0)
  4370. \end{lstlisting}
  4371. If the new dotted rule had a nonterminal after the period, we would
  4372. need to carry out a prediction action, adding more dotted rules to
  4373. slot $1$. That is not the case, so we continue scanning. The next
  4374. input token is \code{"("}, so we add the following to slot $2$ of the
  4375. chart.
  4376. \begin{lstlisting}
  4377. stmt: "print" "(" . exp ")" (0)
  4378. \end{lstlisting}
  4379. Now we have a nonterminal after the period, so we carry out several
  4380. prediction actions, adding dotted rules for \code{exp} and
  4381. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4382. starting position $2$.
  4383. \begin{lstlisting}[escapechar=$]
  4384. exp: . exp "+" exp_hi (2)
  4385. exp: . exp "-" exp_hi (2)
  4386. exp: . exp_hi (2)
  4387. exp_hi: . INT (2)
  4388. exp_hi: . "input_int" "(" ")" (2)
  4389. exp_hi: . "-" exp_hi (2)
  4390. exp_hi: . "(" exp ")" (2)
  4391. \end{lstlisting}
  4392. With this prediction complete, we return to scanning, noting that the
  4393. next input token is \code{"1"}, which the lexer parses as an
  4394. \code{INT}. There is a matching rule in slot $2$:
  4395. \begin{lstlisting}
  4396. exp_hi: . INT (2)
  4397. \end{lstlisting}
  4398. so we advance the period and put the following rule into slot $3$.
  4399. \begin{lstlisting}
  4400. exp_hi: INT . (2)
  4401. \end{lstlisting}
  4402. This brings us to \emph{completion} actions. When the period reaches
  4403. the end of a dotted rule, we recognize that the substring
  4404. has matched the nonterminal on the left-hand side of the rule, in this case
  4405. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4406. rules into slot $2$ (the starting position for the finished rule) if
  4407. the period is immediately followed by \code{exp\_hi}. So we identify
  4408. \begin{lstlisting}
  4409. exp: . exp_hi (2)
  4410. \end{lstlisting}
  4411. and add the following dotted rule to slot $3$
  4412. \begin{lstlisting}
  4413. exp: exp_hi . (2)
  4414. \end{lstlisting}
  4415. This triggers another completion step for the nonterminal \code{exp},
  4416. adding two more dotted rules to slot $3$.
  4417. \begin{lstlisting}[escapechar=$]
  4418. exp: exp . "+" exp_hi (2)
  4419. exp: exp . "-" exp_hi (2)
  4420. \end{lstlisting}
  4421. Returning to scanning, the next input token is \code{"+"}, so
  4422. we add the following to slot $4$.
  4423. \begin{lstlisting}[escapechar=$]
  4424. exp: exp "+" . exp_hi (2)
  4425. \end{lstlisting}
  4426. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4427. the following dotted rules to slot $4$ of the chart.
  4428. \begin{lstlisting}[escapechar=$]
  4429. exp_hi: . INT (4)
  4430. exp_hi: . "input_int" "(" ")" (4)
  4431. exp_hi: . "-" exp_hi (4)
  4432. exp_hi: . "(" exp ")" (4)
  4433. \end{lstlisting}
  4434. The next input token is \code{"3"} which the lexer categorized as an
  4435. \code{INT}, so we advance the period past \code{INT} for the rules in
  4436. slot $4$, of which there is just one, and put the following into slot $5$.
  4437. \begin{lstlisting}[escapechar=$]
  4438. exp_hi: INT . (4)
  4439. \end{lstlisting}
  4440. The period at the end of the rule triggers a completion action for the
  4441. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4442. So we advance the period and put the following into slot $5$.
  4443. \begin{lstlisting}[escapechar=$]
  4444. exp: exp "+" exp_hi . (2)
  4445. \end{lstlisting}
  4446. This triggers another completion action for the rules in slot $2$ that
  4447. have a period before \code{exp}.
  4448. \begin{lstlisting}[escapechar=$]
  4449. stmt: "print" "(" exp . ")" (0)
  4450. exp: exp . "+" exp_hi (2)
  4451. exp: exp . "-" exp_hi (2)
  4452. \end{lstlisting}
  4453. We scan the next input token \code{")"}, placing the following dotted
  4454. rule into slot $6$.
  4455. \begin{lstlisting}[escapechar=$]
  4456. stmt: "print" "(" exp ")" . (0)
  4457. \end{lstlisting}
  4458. This triggers the completion of \code{stmt} in slot $0$
  4459. \begin{lstlisting}
  4460. stmt_list: stmt . NEWLINE stmt_list (0)
  4461. \end{lstlisting}
  4462. The last input token is a \code{NEWLINE}, so we advance the period
  4463. and place the new dotted rule into slot $7$.
  4464. \begin{lstlisting}
  4465. stmt_list: stmt NEWLINE . stmt_list (0)
  4466. \end{lstlisting}
  4467. We are close to the end of parsing the input!
  4468. The period is before the \code{stmt\_list} nonterminal, so we
  4469. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4470. \begin{lstlisting}
  4471. stmt_list: . (7)
  4472. stmt_list: . stmt NEWLINE stmt_list (7)
  4473. stmt: . "print" "(" exp ")" (7)
  4474. stmt: . exp (7)
  4475. \end{lstlisting}
  4476. There is immediately an opportunity for completion of \code{stmt\_list},
  4477. so we add the following to slot $7$.
  4478. \begin{lstlisting}
  4479. stmt_list: stmt NEWLINE stmt_list . (0)
  4480. \end{lstlisting}
  4481. This triggers another completion action for \code{stmt\_list} in slot $0$
  4482. \begin{lstlisting}
  4483. lang_int: stmt_list . (0)
  4484. \end{lstlisting}
  4485. which in turn completes \code{lang\_int}, the start symbol of the
  4486. grammar, so the parsing of the input is complete.
  4487. For reference, we give a general description of Earley's
  4488. algorithm.
  4489. \begin{enumerate}
  4490. \item The algorithm begins by initializing slot $0$ of the chart with the
  4491. grammar rule for the start symbol, placing a period at the beginning
  4492. of the right-hand side, and recording its starting position as $0$.
  4493. \item The algorithm repeatedly applies the following three kinds of
  4494. actions for as long as there are opportunities to do so.
  4495. \begin{itemize}
  4496. \item Prediction: If there is a rule in slot $k$ whose period comes
  4497. before a nonterminal, add the rules for that nonterminal into slot
  4498. $k$, placing a period at the beginning of their right-hand sides
  4499. and recording their starting position as $k$.
  4500. \item Scanning: If the token at position $k$ of the input string
  4501. matches the symbol after the period in a dotted rule in slot $k$
  4502. of the chart, advance the period in the dotted rule, adding
  4503. the result to slot $k+1$.
  4504. \item Completion: If a dotted rule in slot $k$ has a period at the
  4505. end, inspect the rules in the slot corresponding to the starting
  4506. position of the completed rule. If any of those rules have a
  4507. nonterminal following their period that matches the left-hand side
  4508. of the completed rule, then advance their period, placing the new
  4509. dotted rule in slot $k$.
  4510. \end{itemize}
  4511. While repeating these three actions, take care never to add
  4512. duplicate dotted rules to the chart.
  4513. \end{enumerate}
  4514. We have described how Earley's algorithm recognizes that an input
  4515. string matches a grammar, but we have not described how it builds a
  4516. parse tree. The basic idea is simple, but building parse trees in an
  4517. efficient way is more complex, requiring a data structure called a
  4518. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4519. to attach a partial parse tree to every dotted rule in the chart.
  4520. Initially, the node associated with a dotted rule has no
  4521. children. As the period moves to the right, the nodes from the
  4522. subparses are added as children to the node.
  4523. As mentioned at the beginning of this section, Earley's algorithm is
  4524. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4525. files that contain thousands of tokens in a reasonable amount of time,
  4526. but not millions.
  4527. %
  4528. In the next section we discuss the LALR(1) parsing algorithm, which is
  4529. efficient enough to use with even the largest of input files.
  4530. \section{The LALR(1) Algorithm}
  4531. \label{sec:lalr}
  4532. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4533. two-phase approach in which it first compiles the grammar into a state
  4534. machine and then runs the state machine to parse an input string. The
  4535. second phase has time complexity $O(n)$ where $n$ is the number of
  4536. tokens in the input, so LALR(1) is the best one could hope for with
  4537. respect to efficiency.
  4538. %
  4539. A particularly influential implementation of LALR(1) is the
  4540. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4541. \texttt{yacc} stands for ``yet another compiler compiler.''
  4542. %
  4543. The LALR(1) state machine uses a stack to record its progress in
  4544. parsing the input string. Each element of the stack is a pair: a
  4545. state number and a grammar symbol (a terminal or a nonterminal). The
  4546. symbol characterizes the input that has been parsed so far, and the
  4547. state number is used to remember how to proceed once the next
  4548. symbol's worth of input has been parsed. Each state in the machine
  4549. represents where the parser stands in the parsing process with respect
  4550. to certain grammar rules. In particular, each state is associated with
  4551. a set of dotted rules.
  4552. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4553. (also called parse table) for the following simple but ambiguous
  4554. grammar:
  4555. \begin{lstlisting}[escapechar=$]
  4556. exp: INT
  4557. | exp "+" exp
  4558. stmt: "print" exp
  4559. start: stmt
  4560. \end{lstlisting}
  4561. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4562. read in a \lstinline{"print"} token, so the top of the stack is
  4563. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4564. the input according to grammar rule 1, which is signified by showing
  4565. rule 1 with a period after the \code{"print"} token and before the
  4566. \code{exp} nonterminal. There are two rules that could apply next,
  4567. rules 2 and 3, so state 1 also shows those rules with a period at
  4568. the beginning of their right-hand sides. The edges between states
  4569. indicate which transitions the machine should make depending on the
  4570. next input token. So, for example, if the next input token is
  4571. \code{INT} then the parser will push \code{INT} and the target state 4
  4572. on the stack and transition to state 4. Suppose that we are now at the end
  4573. of the input. State 4 says that we should reduce by rule 3, so we pop
  4574. from the stack the same number of items as the number of symbols in
  4575. the right-hand side of the rule, in this case just one. We then
  4576. momentarily jump to the state at the top of the stack (state 1) and
  4577. then follow the goto edge that corresponds to the left-hand side of
  4578. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4579. state 3. (A slightly longer example parse is shown in
  4580. figure~\ref{fig:shift-reduce}.)
  4581. \begin{figure}[tbp]
  4582. \centering
  4583. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4584. \caption{An LALR(1) parse table and a trace of an example run.}
  4585. \label{fig:shift-reduce}
  4586. \end{figure}
  4587. In general, the algorithm works as follows. First, set the current state to
  4588. state $0$. Then repeat the following, looking at the next input token.
  4589. \begin{itemize}
  4590. \item If there there is a shift edge for the input token in the
  4591. current state, push the edge's target state and the input token onto
  4592. the stack and proceed to the edge's target state.
  4593. \item If there is a reduce action for the input token in the current
  4594. state, pop $k$ elements from the stack, where $k$ is the number of
  4595. symbols in the right-hand side of the rule being reduced. Jump to
  4596. the state at the top of the stack and then follow the goto edge for
  4597. the nonterminal that matches the left-hand side of the rule that we
  4598. are reducing by. Push the edge's target state and the nonterminal on the
  4599. stack.
  4600. \end{itemize}
  4601. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4602. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4603. algorithm does not know which action to take in this case. When a
  4604. state has both a shift and a reduce action for the same token, we say
  4605. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4606. will arise, for example, in trying to parse the input
  4607. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4608. the parser will be in state 6 and will not know whether to
  4609. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4610. to proceed by shifting the next \lstinline{+} from the input.
  4611. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4612. arises when there are two reduce actions in a state for the same
  4613. token. To understand which grammars give rise to shift/reduce and
  4614. reduce/reduce conflicts, it helps to know how the parse table is
  4615. generated from the grammar, which we discuss next.
  4616. The parse table is generated one state at a time. State 0 represents
  4617. the start of the parser. We add the grammar rule for the start symbol
  4618. to this state with a period at the beginning of the right-hand side,
  4619. similarly to the initialization phase of the Earley parser. If the
  4620. period appears immediately before another nonterminal, we add all the
  4621. rules with that nonterminal on the left-hand side. Again, we place a
  4622. period at the beginning of the right-hand side of each new
  4623. rule. This process, called \emph{state closure}, is continued
  4624. until there are no more rules to add (similarly to the prediction
  4625. actions of an Earley parser). We then examine each dotted rule in the
  4626. current state $I$. Suppose that a dotted rule has the form $A ::=
  4627. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4628. are sequences of symbols. We create a new state and call it $J$. If $X$
  4629. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4630. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4631. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4632. state $J$. We start by adding all dotted rules from state $I$ that
  4633. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4634. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4635. the period moved past the $X$. (This is analogous to completion in
  4636. Earley's algorithm.) We then perform state closure on $J$. This
  4637. process repeats until there are no more states or edges to add.
  4638. We then mark states as accepting states if they have a dotted rule
  4639. that is the start rule with a period at the end. Also, to add
  4640. the reduce actions, we look for any state containing a dotted rule
  4641. with a period at the end. Let $n$ be the rule number for this dotted
  4642. rule. We then put a reduce $n$ action into that state for every token
  4643. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4644. dotted rule with a period at the end. We therefore put a reduce by
  4645. rule 3 action into state 4 for every
  4646. token.
  4647. When inserting reduce actions, take care to spot any shift/reduce or
  4648. reduce/reduce conflicts. If there are any, abort the construction of
  4649. the parse table.
  4650. \begin{exercise}
  4651. \normalfont\normalsize
  4652. %
  4653. Working on paper, walk through the parse table generation process for
  4654. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4655. your results against the parse table shown in
  4656. figure~\ref{fig:shift-reduce}.
  4657. \end{exercise}
  4658. \begin{exercise}
  4659. \normalfont\normalsize
  4660. %
  4661. Change the parser in your compiler for \LangVar{} to set the
  4662. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4663. all the \LangVar{} programs that you have created. In doing so, Lark
  4664. may signal an error due to shift/reduce or reduce/reduce conflicts
  4665. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4666. remove those conflicts.
  4667. \end{exercise}
  4668. \section{Further Reading}
  4669. In this chapter we have just scratched the surface of the field of
  4670. parsing, with the study of a very general but less efficient algorithm
  4671. (Earley) and with a more limited but highly efficient algorithm
  4672. (LALR). There are many more algorithms and classes of grammars that
  4673. fall between these two ends of the spectrum. We recommend to the reader
  4674. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4675. Regarding lexical analysis, we have described the specification
  4676. language, which are the regular expressions, but not the algorithms
  4677. for recognizing them. In short, regular expressions can be translated
  4678. to nondeterministic finite automata, which in turn are translated to
  4679. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4680. all the details on lexical analysis.
  4681. \fi}
  4682. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4683. \chapter{Register Allocation}
  4684. \label{ch:register-allocation-Lvar}
  4685. \setcounter{footnote}{0}
  4686. \index{subject}{register allocation}
  4687. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4688. storing variables on the procedure call stack. The CPU may require tens
  4689. to hundreds of cycles to access a location on the stack, whereas
  4690. accessing a register takes only a single cycle. In this chapter we
  4691. improve the efficiency of our generated code by storing some variables
  4692. in registers. The goal of register allocation is to fit as many
  4693. variables into registers as possible. Some programs have more
  4694. variables than registers, so we cannot always map each variable to a
  4695. different register. Fortunately, it is common for different variables
  4696. to be in use during different periods of time during program
  4697. execution, and in those cases we can map multiple variables to the
  4698. same register.
  4699. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4700. example. The source program is on the left and the output of
  4701. instruction selection\index{subject}{instruction selection}
  4702. is on the right. The program is almost
  4703. completely in the x86 assembly language, but it still uses variables.
  4704. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4705. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4706. the other hand, is used only after this point, so \code{x} and
  4707. \code{z} could share the same register.
  4708. \begin{figure}
  4709. \begin{tcolorbox}[colback=white]
  4710. \begin{minipage}{0.45\textwidth}
  4711. Example \LangVar{} program:
  4712. % var_test_28.rkt
  4713. {\if\edition\racketEd
  4714. \begin{lstlisting}
  4715. (let ([v 1])
  4716. (let ([w 42])
  4717. (let ([x (+ v 7)])
  4718. (let ([y x])
  4719. (let ([z (+ x w)])
  4720. (+ z (- y)))))))
  4721. \end{lstlisting}
  4722. \fi}
  4723. {\if\edition\pythonEd\pythonColor
  4724. \begin{lstlisting}
  4725. v = 1
  4726. w = 42
  4727. x = v + 7
  4728. y = x
  4729. z = x + w
  4730. print(z + (- y))
  4731. \end{lstlisting}
  4732. \fi}
  4733. \end{minipage}
  4734. \begin{minipage}{0.45\textwidth}
  4735. After instruction selection:
  4736. {\if\edition\racketEd
  4737. \begin{lstlisting}
  4738. locals-types:
  4739. x : Integer, y : Integer,
  4740. z : Integer, t : Integer,
  4741. v : Integer, w : Integer
  4742. start:
  4743. movq $1, v
  4744. movq $42, w
  4745. movq v, x
  4746. addq $7, x
  4747. movq x, y
  4748. movq x, z
  4749. addq w, z
  4750. movq y, t
  4751. negq t
  4752. movq z, %rax
  4753. addq t, %rax
  4754. jmp conclusion
  4755. \end{lstlisting}
  4756. \fi}
  4757. {\if\edition\pythonEd\pythonColor
  4758. \begin{lstlisting}
  4759. movq $1, v
  4760. movq $42, w
  4761. movq v, x
  4762. addq $7, x
  4763. movq x, y
  4764. movq x, z
  4765. addq w, z
  4766. movq y, tmp_0
  4767. negq tmp_0
  4768. movq z, tmp_1
  4769. addq tmp_0, tmp_1
  4770. movq tmp_1, %rdi
  4771. callq print_int
  4772. \end{lstlisting}
  4773. \fi}
  4774. \end{minipage}
  4775. \end{tcolorbox}
  4776. \caption{A running example for register allocation.}
  4777. \label{fig:reg-eg}
  4778. \end{figure}
  4779. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4780. compute where a variable is in use. Once we have that information, we
  4781. compute which variables are in use at the same time, that is, which ones
  4782. \emph{interfere}\index{subject}{interfere} with each other, and
  4783. represent this relation as an undirected graph whose vertices are
  4784. variables and edges indicate when two variables interfere
  4785. (section~\ref{sec:build-interference}). We then model register
  4786. allocation as a graph coloring problem
  4787. (section~\ref{sec:graph-coloring}).
  4788. If we run out of registers despite these efforts, we place the
  4789. remaining variables on the stack, similarly to how we handled
  4790. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4791. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4792. location. The decision to spill a variable is handled as part of the
  4793. graph coloring process.
  4794. We make the simplifying assumption that each variable is assigned to
  4795. one location (a register or stack address). A more sophisticated
  4796. approach is to assign a variable to one or more locations in different
  4797. regions of the program. For example, if a variable is used many times
  4798. in short sequence and then used again only after many other
  4799. instructions, it could be more efficient to assign the variable to a
  4800. register during the initial sequence and then move it to the stack for
  4801. the rest of its lifetime. We refer the interested reader to
  4802. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4803. approach.
  4804. % discuss prioritizing variables based on how much they are used.
  4805. \section{Registers and Calling Conventions}
  4806. \label{sec:calling-conventions}
  4807. \index{subject}{calling conventions}
  4808. As we perform register allocation, we must be aware of the
  4809. \emph{calling conventions} \index{subject}{calling conventions} that
  4810. govern how function calls are performed in x86.
  4811. %
  4812. Even though \LangVar{} does not include programmer-defined functions,
  4813. our generated code includes a \code{main} function that is called by
  4814. the operating system and our generated code contains calls to the
  4815. \code{read\_int} function.
  4816. Function calls require coordination between two pieces of code that
  4817. may be written by different programmers or generated by different
  4818. compilers. Here we follow the System V calling conventions that are
  4819. used by the GNU C compiler on Linux and
  4820. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4821. %
  4822. The calling conventions include rules about how functions share the
  4823. use of registers. In particular, the caller is responsible for freeing
  4824. some registers prior to the function call for use by the callee.
  4825. These are called the \emph{caller-saved registers}
  4826. \index{subject}{caller-saved registers}
  4827. and they are
  4828. \begin{lstlisting}
  4829. rax rcx rdx rsi rdi r8 r9 r10 r11
  4830. \end{lstlisting}
  4831. On the other hand, the callee is responsible for preserving the values
  4832. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4833. which are
  4834. \begin{lstlisting}
  4835. rsp rbp rbx r12 r13 r14 r15
  4836. \end{lstlisting}
  4837. We can think about this caller/callee convention from two points of
  4838. view, the caller view and the callee view, as follows:
  4839. \begin{itemize}
  4840. \item The caller should assume that all the caller-saved registers get
  4841. overwritten with arbitrary values by the callee. On the other hand,
  4842. the caller can safely assume that all the callee-saved registers
  4843. retain their original values.
  4844. \item The callee can freely use any of the caller-saved registers.
  4845. However, if the callee wants to use a callee-saved register, the
  4846. callee must arrange to put the original value back in the register
  4847. prior to returning to the caller. This can be accomplished by saving
  4848. the value to the stack in the prelude of the function and restoring
  4849. the value in the conclusion of the function.
  4850. \end{itemize}
  4851. In x86, registers are also used for passing arguments to a function
  4852. and for the return value. In particular, the first six arguments of a
  4853. function are passed in the following six registers, in this order.
  4854. \begin{lstlisting}
  4855. rdi rsi rdx rcx r8 r9
  4856. \end{lstlisting}
  4857. We refer to these six registers are the argument-passing registers
  4858. \index{subject}{argument-passing registers}.
  4859. If there are more than six arguments, the convention is to use space
  4860. on the frame of the caller for the rest of the arguments. In
  4861. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4862. argument and the rest of the arguments, which simplifies the treatment
  4863. of efficient tail calls.
  4864. %
  4865. \racket{For now, the only function we care about is \code{read\_int},
  4866. which takes zero arguments.}
  4867. %
  4868. \python{For now, the only functions we care about are \code{read\_int}
  4869. and \code{print\_int}, which take zero and one argument, respectively.}
  4870. %
  4871. The register \code{rax} is used for the return value of a function.
  4872. The next question is how these calling conventions impact register
  4873. allocation. Consider the \LangVar{} program presented in
  4874. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4875. example from the caller point of view and then from the callee point
  4876. of view. We refer to a variable that is in use during a function call
  4877. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4878. The program makes two calls to \READOP{}. The variable \code{x} is
  4879. call-live because it is in use during the second call to \READOP{}; we
  4880. must ensure that the value in \code{x} does not get overwritten during
  4881. the call to \READOP{}. One obvious approach is to save all the values
  4882. that reside in caller-saved registers to the stack prior to each
  4883. function call and to restore them after each call. That way, if the
  4884. register allocator chooses to assign \code{x} to a caller-saved
  4885. register, its value will be preserved across the call to \READOP{}.
  4886. However, saving and restoring to the stack is relatively slow. If
  4887. \code{x} is not used many times, it may be better to assign \code{x}
  4888. to a stack location in the first place. Or better yet, if we can
  4889. arrange for \code{x} to be placed in a callee-saved register, then it
  4890. won't need to be saved and restored during function calls.
  4891. We recommend an approach that captures these issues in the
  4892. interference graph, without complicating the graph coloring algorithm.
  4893. During liveness analysis we know which variables are call-live because
  4894. we compute which variables are in use at every instruction
  4895. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4896. interference graph (section~\ref{sec:build-interference}), we can
  4897. place an edge in the interference graph between each call-live
  4898. variable and the caller-saved registers. This will prevent the graph
  4899. coloring algorithm from assigning call-live variables to caller-saved
  4900. registers.
  4901. On the other hand, for variables that are not call-live, we prefer
  4902. placing them in caller-saved registers to leave more room for
  4903. call-live variables in the callee-saved registers. This can also be
  4904. implemented without complicating the graph coloring algorithm. We
  4905. recommend that the graph coloring algorithm assign variables to
  4906. natural numbers, choosing the lowest number for which there is no
  4907. interference. After the coloring is complete, we map the numbers to
  4908. registers and stack locations: mapping the lowest numbers to
  4909. caller-saved registers, the next lowest to callee-saved registers, and
  4910. the largest numbers to stack locations. This ordering gives preference
  4911. to registers over stack locations and to caller-saved registers over
  4912. callee-saved registers.
  4913. Returning to the example in
  4914. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4915. generated x86 code on the right-hand side. Variable \code{x} is
  4916. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4917. in a safe place during the second call to \code{read\_int}. Next,
  4918. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4919. because \code{y} is not a call-live variable.
  4920. We have completed the analysis from the caller point of view, so now
  4921. we switch to the callee point of view, focusing on the prelude and
  4922. conclusion of the \code{main} function. As usual, the prelude begins
  4923. with saving the \code{rbp} register to the stack and setting the
  4924. \code{rbp} to the current stack pointer. We now know why it is
  4925. necessary to save the \code{rbp}: it is a callee-saved register. The
  4926. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4927. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4928. (\code{x}). The other callee-saved registers are not saved in the
  4929. prelude because they are not used. The prelude subtracts 8 bytes from
  4930. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4931. conclusion, we see that \code{rbx} is restored from the stack with a
  4932. \code{popq} instruction.
  4933. \index{subject}{prelude}\index{subject}{conclusion}
  4934. \begin{figure}[tp]
  4935. \begin{tcolorbox}[colback=white]
  4936. \begin{minipage}{0.45\textwidth}
  4937. Example \LangVar{} program:
  4938. %var_test_14.rkt
  4939. {\if\edition\racketEd
  4940. \begin{lstlisting}
  4941. (let ([x (read)])
  4942. (let ([y (read)])
  4943. (+ (+ x y) 42)))
  4944. \end{lstlisting}
  4945. \fi}
  4946. {\if\edition\pythonEd\pythonColor
  4947. \begin{lstlisting}
  4948. x = input_int()
  4949. y = input_int()
  4950. print((x + y) + 42)
  4951. \end{lstlisting}
  4952. \fi}
  4953. \end{minipage}
  4954. \begin{minipage}{0.45\textwidth}
  4955. Generated x86 assembly:
  4956. {\if\edition\racketEd
  4957. \begin{lstlisting}
  4958. start:
  4959. callq read_int
  4960. movq %rax, %rbx
  4961. callq read_int
  4962. movq %rax, %rcx
  4963. addq %rcx, %rbx
  4964. movq %rbx, %rax
  4965. addq $42, %rax
  4966. jmp conclusion
  4967. .globl main
  4968. main:
  4969. pushq %rbp
  4970. movq %rsp, %rbp
  4971. pushq %rbx
  4972. subq $8, %rsp
  4973. jmp start
  4974. conclusion:
  4975. addq $8, %rsp
  4976. popq %rbx
  4977. popq %rbp
  4978. retq
  4979. \end{lstlisting}
  4980. \fi}
  4981. {\if\edition\pythonEd\pythonColor
  4982. \begin{lstlisting}
  4983. .globl main
  4984. main:
  4985. pushq %rbp
  4986. movq %rsp, %rbp
  4987. pushq %rbx
  4988. subq $8, %rsp
  4989. callq read_int
  4990. movq %rax, %rbx
  4991. callq read_int
  4992. movq %rax, %rcx
  4993. movq %rbx, %rdx
  4994. addq %rcx, %rdx
  4995. movq %rdx, %rcx
  4996. addq $42, %rcx
  4997. movq %rcx, %rdi
  4998. callq print_int
  4999. addq $8, %rsp
  5000. popq %rbx
  5001. popq %rbp
  5002. retq
  5003. \end{lstlisting}
  5004. \fi}
  5005. \end{minipage}
  5006. \end{tcolorbox}
  5007. \caption{An example with function calls.}
  5008. \label{fig:example-calling-conventions}
  5009. \end{figure}
  5010. %\clearpage
  5011. \section{Liveness Analysis}
  5012. \label{sec:liveness-analysis-Lvar}
  5013. \index{subject}{liveness analysis}
  5014. The \code{uncover\_live} \racket{pass}\python{function} performs
  5015. \emph{liveness analysis}; that is, it discovers which variables are
  5016. in use in different regions of a program.
  5017. %
  5018. A variable or register is \emph{live} at a program point if its
  5019. current value is used at some later point in the program. We refer to
  5020. variables, stack locations, and registers collectively as
  5021. \emph{locations}.
  5022. %
  5023. Consider the following code fragment in which there are two writes to
  5024. \code{b}. Are variables \code{a} and \code{b} both live at the same
  5025. time?
  5026. \begin{center}
  5027. \begin{minipage}{0.85\textwidth}
  5028. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5029. movq $5, a
  5030. movq $30, b
  5031. movq a, c
  5032. movq $10, b
  5033. addq b, c
  5034. \end{lstlisting}
  5035. \end{minipage}
  5036. \end{center}
  5037. The answer is no, because \code{a} is live from line 1 to 3 and
  5038. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  5039. line 2 is never used because it is overwritten (line 4) before the
  5040. next read (line 5).
  5041. The live locations for each instruction can be computed by traversing
  5042. the instruction sequence back to front (i.e., backward in execution
  5043. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5044. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5045. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5046. locations before instruction $I_k$. \racket{We recommend representing
  5047. these sets with the Racket \code{set} data structure described in
  5048. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5049. with the Python
  5050. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5051. data structure.}
  5052. {\if\edition\racketEd
  5053. \begin{figure}[tp]
  5054. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5055. \small
  5056. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5057. A \emph{set} is an unordered collection of elements without duplicates.
  5058. Here are some of the operations defined on sets.
  5059. \index{subject}{set}
  5060. \begin{description}
  5061. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5062. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5063. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5064. difference of the two sets.
  5065. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5066. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5067. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5068. \end{description}
  5069. \end{tcolorbox}
  5070. %\end{wrapfigure}
  5071. \caption{The \code{set} data structure.}
  5072. \label{fig:set}
  5073. \end{figure}
  5074. \fi}
  5075. % TODO: add a python version of the reference box for sets. -Jeremy
  5076. The locations that are live after an instruction are its
  5077. \emph{live-after}\index{subject}{live-after} set, and the locations
  5078. that are live before an instruction are its
  5079. \emph{live-before}\index{subject}{live-before} set. The live-after
  5080. set of an instruction is always the same as the live-before set of the
  5081. next instruction.
  5082. \begin{equation} \label{eq:live-after-before-next}
  5083. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5084. \end{equation}
  5085. To start things off, there are no live locations after the last
  5086. instruction, so
  5087. \begin{equation}\label{eq:live-last-empty}
  5088. L_{\mathsf{after}}(n) = \emptyset
  5089. \end{equation}
  5090. We then apply the following rule repeatedly, traversing the
  5091. instruction sequence back to front.
  5092. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5093. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5094. \end{equation}
  5095. where $W(k)$ are the locations written to by instruction $I_k$, and
  5096. $R(k)$ are the locations read by instruction $I_k$.
  5097. {\if\edition\racketEd
  5098. %
  5099. There is a special case for \code{jmp} instructions. The locations
  5100. that are live before a \code{jmp} should be the locations in
  5101. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5102. maintaining an alist named \code{label->live} that maps each label to
  5103. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5104. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5105. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5106. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5107. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5108. %
  5109. \fi}
  5110. Let us walk through the previous example, applying these formulas
  5111. starting with the instruction on line 5 of the code fragment. We
  5112. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5113. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5114. $\emptyset$ because it is the last instruction
  5115. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5116. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5117. variables \code{b} and \code{c}
  5118. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5119. \[
  5120. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5121. \]
  5122. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5123. the live-before set from line 5 to be the live-after set for this
  5124. instruction (formula~\eqref{eq:live-after-before-next}).
  5125. \[
  5126. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5127. \]
  5128. This move instruction writes to \code{b} and does not read from any
  5129. variables, so we have the following live-before set
  5130. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5131. \[
  5132. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5133. \]
  5134. The live-before for instruction \code{movq a, c}
  5135. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5136. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5137. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5138. variable that is not live and does not read from a variable.
  5139. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5140. because it writes to variable \code{a}.
  5141. \begin{figure}[tbp]
  5142. \centering
  5143. \begin{tcolorbox}[colback=white]
  5144. \hspace{10pt}
  5145. \begin{minipage}{0.4\textwidth}
  5146. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5147. movq $5, a
  5148. movq $30, b
  5149. movq a, c
  5150. movq $10, b
  5151. addq b, c
  5152. \end{lstlisting}
  5153. \end{minipage}
  5154. \vrule\hspace{10pt}
  5155. \begin{minipage}{0.45\textwidth}
  5156. \begin{align*}
  5157. L_{\mathsf{before}}(1)= \emptyset,
  5158. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5159. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5160. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5161. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5162. L_{\mathsf{after}}(3)= \{\ttm{c}\}\\
  5163. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5164. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5165. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5166. L_{\mathsf{after}}(5)= \emptyset
  5167. \end{align*}
  5168. \end{minipage}
  5169. \end{tcolorbox}
  5170. \caption{Example output of liveness analysis on a short example.}
  5171. \label{fig:liveness-example-0}
  5172. \end{figure}
  5173. \begin{exercise}\normalfont\normalsize
  5174. Perform liveness analysis by hand on the running example in
  5175. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5176. sets for each instruction. Compare your answers to the solution
  5177. shown in figure~\ref{fig:live-eg}.
  5178. \end{exercise}
  5179. \begin{figure}[tp]
  5180. \hspace{20pt}
  5181. \begin{minipage}{0.55\textwidth}
  5182. \begin{tcolorbox}[colback=white]
  5183. {\if\edition\racketEd
  5184. \begin{lstlisting}
  5185. |$\{\ttm{rsp}\}$|
  5186. movq $1, v
  5187. |$\{\ttm{v},\ttm{rsp}\}$|
  5188. movq $42, w
  5189. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5190. movq v, x
  5191. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5192. addq $7, x
  5193. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5194. movq x, y
  5195. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5196. movq x, z
  5197. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5198. addq w, z
  5199. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5200. movq y, t
  5201. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5202. negq t
  5203. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5204. movq z, %rax
  5205. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5206. addq t, %rax
  5207. |$\{\ttm{rax},\ttm{rsp}\}$|
  5208. jmp conclusion
  5209. \end{lstlisting}
  5210. \fi}
  5211. {\if\edition\pythonEd\pythonColor
  5212. \begin{lstlisting}
  5213. movq $1, v
  5214. |$\{\ttm{v}\}$|
  5215. movq $42, w
  5216. |$\{\ttm{w}, \ttm{v}\}$|
  5217. movq v, x
  5218. |$\{\ttm{w}, \ttm{x}\}$|
  5219. addq $7, x
  5220. |$\{\ttm{w}, \ttm{x}\}$|
  5221. movq x, y
  5222. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5223. movq x, z
  5224. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5225. addq w, z
  5226. |$\{\ttm{y}, \ttm{z}\}$|
  5227. movq y, tmp_0
  5228. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5229. negq tmp_0
  5230. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5231. movq z, tmp_1
  5232. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5233. addq tmp_0, tmp_1
  5234. |$\{\ttm{tmp\_1}\}$|
  5235. movq tmp_1, %rdi
  5236. |$\{\ttm{rdi}\}$|
  5237. callq print_int
  5238. |$\{\}$|
  5239. \end{lstlisting}
  5240. \fi}
  5241. \end{tcolorbox}
  5242. \end{minipage}
  5243. \caption{The running example annotated with live-after sets.}
  5244. \label{fig:live-eg}
  5245. \end{figure}
  5246. \begin{exercise}\normalfont\normalsize
  5247. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5248. %
  5249. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5250. field of the \code{Block} structure.}
  5251. %
  5252. \python{Return a dictionary that maps each instruction to its
  5253. live-after set.}
  5254. %
  5255. \racket{We recommend creating an auxiliary function that takes a list
  5256. of instructions and an initial live-after set (typically empty) and
  5257. returns the list of live-after sets.}
  5258. %
  5259. We recommend creating auxiliary functions to (1) compute the set
  5260. of locations that appear in an \Arg{}, (2) compute the locations read
  5261. by an instruction (the $R$ function), and (3) the locations written by
  5262. an instruction (the $W$ function). The \code{callq} instruction should
  5263. include all the caller-saved registers in its write set $W$ because
  5264. the calling convention says that those registers may be written to
  5265. during the function call. Likewise, the \code{callq} instruction
  5266. should include the appropriate argument-passing registers in its
  5267. read set $R$, depending on the arity of the function being
  5268. called. (This is why the abstract syntax for \code{callq} includes the
  5269. arity.)
  5270. \end{exercise}
  5271. %\clearpage
  5272. \section{Build the Interference Graph}
  5273. \label{sec:build-interference}
  5274. {\if\edition\racketEd
  5275. \begin{figure}[tp]
  5276. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5277. \small
  5278. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5279. A \emph{graph} is a collection of vertices and edges where each
  5280. edge connects two vertices. A graph is \emph{directed} if each
  5281. edge points from a source to a target. Otherwise the graph is
  5282. \emph{undirected}.
  5283. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5284. \begin{description}
  5285. %% We currently don't use directed graphs. We instead use
  5286. %% directed multi-graphs. -Jeremy
  5287. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5288. directed graph from a list of edges. Each edge is a list
  5289. containing the source and target vertex.
  5290. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5291. undirected graph from a list of edges. Each edge is represented by
  5292. a list containing two vertices.
  5293. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5294. inserts a vertex into the graph.
  5295. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5296. inserts an edge between the two vertices.
  5297. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5298. returns a sequence of vertices adjacent to the vertex.
  5299. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5300. returns a sequence of all vertices in the graph.
  5301. \end{description}
  5302. \end{tcolorbox}
  5303. %\end{wrapfigure}
  5304. \caption{The Racket \code{graph} package.}
  5305. \label{fig:graph}
  5306. \end{figure}
  5307. \fi}
  5308. On the basis of the liveness analysis, we know where each location is
  5309. live. However, during register allocation, we need to answer
  5310. questions of the specific form: are locations $u$ and $v$ live at the
  5311. same time? (If so, they cannot be assigned to the same register.) To
  5312. make this question more efficient to answer, we create an explicit
  5313. data structure, an \emph{interference
  5314. graph}\index{subject}{interference graph}. An interference graph is
  5315. an undirected graph that has a node for every variable and register
  5316. and has an edge between two nodes if they are
  5317. live at the same time, that is, if they interfere with each other.
  5318. %
  5319. \racket{We recommend using the Racket \code{graph} package
  5320. (figure~\ref{fig:graph}) to represent the interference graph.}
  5321. %
  5322. \python{We provide implementations of directed and undirected graph
  5323. data structures in the file \code{graph.py} of the support code.}
  5324. A straightforward way to compute the interference graph is to look at
  5325. the set of live locations between each instruction and add an edge to
  5326. the graph for every pair of variables in the same set. This approach
  5327. is less than ideal for two reasons. First, it can be expensive because
  5328. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5329. locations. Second, in the special case in which two locations hold the
  5330. same value (because one was assigned to the other), they can be live
  5331. at the same time without interfering with each other.
  5332. A better way to compute the interference graph is to focus on
  5333. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5334. must not overwrite something in a live location. So for each
  5335. instruction, we create an edge between the locations being written to
  5336. and the live locations. (However, a location never interferes with
  5337. itself.) For the \key{callq} instruction, we consider all the
  5338. caller-saved registers to have been written to, so an edge is added
  5339. between every live variable and every caller-saved register. Also, for
  5340. \key{movq} there is the special case of two variables holding the same
  5341. value. If a live variable $v$ is the same as the source of the
  5342. \key{movq}, then there is no need to add an edge between $v$ and the
  5343. destination, because they both hold the same value.
  5344. %
  5345. Hence we have the following two rules:
  5346. \begin{enumerate}
  5347. \item If instruction $I_k$ is a move instruction of the form
  5348. \key{movq} $s$\key{,} $d$, then for every $v \in
  5349. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5350. $(d,v)$.
  5351. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5352. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5353. $(d,v)$.
  5354. \end{enumerate}
  5355. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5356. these rules to each instruction. We highlight a few of the
  5357. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5358. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5359. so \code{v} interferes with \code{rsp}.}
  5360. %
  5361. \python{The first instruction is \lstinline{movq $1, v}, and the
  5362. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5363. no interference because $\ttm{v}$ is the destination of the move.}
  5364. %
  5365. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5366. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5367. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5368. %
  5369. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5370. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5371. $\ttm{x}$ interferes with \ttm{w}.}
  5372. %
  5373. \racket{The next instruction is \lstinline{movq x, y}, and the
  5374. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5375. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5376. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5377. \ttm{x} and \ttm{y} hold the same value.}
  5378. %
  5379. \python{The next instruction is \lstinline{movq x, y}, and the
  5380. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5381. applies, so \ttm{y} interferes with \ttm{w} but not
  5382. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5383. \ttm{x} and \ttm{y} hold the same value.}
  5384. %
  5385. Figure~\ref{fig:interference-results} lists the interference results
  5386. for all the instructions, and the resulting interference graph is
  5387. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5388. the interference graph in figure~\ref{fig:interfere} because there
  5389. were no interference edges involving registers and we did not wish to
  5390. clutter the graph, but in general one needs to include all the
  5391. registers in the interference graph.
  5392. \begin{figure}[tbp]
  5393. \begin{tcolorbox}[colback=white]
  5394. \begin{quote}
  5395. {\if\edition\racketEd
  5396. \begin{tabular}{ll}
  5397. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5398. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5399. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5400. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5401. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5402. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5403. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5404. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5405. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5406. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5407. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5408. \lstinline!jmp conclusion!& no interference.
  5409. \end{tabular}
  5410. \fi}
  5411. {\if\edition\pythonEd\pythonColor
  5412. \begin{tabular}{ll}
  5413. \lstinline!movq $1, v!& no interference\\
  5414. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5415. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5416. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5417. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5418. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5419. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5420. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5421. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5422. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5423. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5424. \lstinline!movq tmp_1, %rdi! & no interference \\
  5425. \lstinline!callq print_int!& no interference.
  5426. \end{tabular}
  5427. \fi}
  5428. \end{quote}
  5429. \end{tcolorbox}
  5430. \caption{Interference results for the running example.}
  5431. \label{fig:interference-results}
  5432. \end{figure}
  5433. \begin{figure}[tbp]
  5434. \begin{tcolorbox}[colback=white]
  5435. \large
  5436. {\if\edition\racketEd
  5437. \[
  5438. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5439. \node (rax) at (0,0) {$\ttm{rax}$};
  5440. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5441. \node (t1) at (0,2) {$\ttm{t}$};
  5442. \node (z) at (3,2) {$\ttm{z}$};
  5443. \node (x) at (6,2) {$\ttm{x}$};
  5444. \node (y) at (3,0) {$\ttm{y}$};
  5445. \node (w) at (6,0) {$\ttm{w}$};
  5446. \node (v) at (9,0) {$\ttm{v}$};
  5447. \draw (t1) to (rax);
  5448. \draw (t1) to (z);
  5449. \draw (z) to (y);
  5450. \draw (z) to (w);
  5451. \draw (x) to (w);
  5452. \draw (y) to (w);
  5453. \draw (v) to (w);
  5454. \draw (v) to (rsp);
  5455. \draw (w) to (rsp);
  5456. \draw (x) to (rsp);
  5457. \draw (y) to (rsp);
  5458. \path[-.,bend left=15] (z) edge node {} (rsp);
  5459. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5460. \draw (rax) to (rsp);
  5461. \end{tikzpicture}
  5462. \]
  5463. \fi}
  5464. {\if\edition\pythonEd\pythonColor
  5465. \[
  5466. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5467. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5468. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5469. \node (z) at (3,2) {$\ttm{z}$};
  5470. \node (x) at (6,2) {$\ttm{x}$};
  5471. \node (y) at (3,0) {$\ttm{y}$};
  5472. \node (w) at (6,0) {$\ttm{w}$};
  5473. \node (v) at (9,0) {$\ttm{v}$};
  5474. \draw (t0) to (t1);
  5475. \draw (t0) to (z);
  5476. \draw (z) to (y);
  5477. \draw (z) to (w);
  5478. \draw (x) to (w);
  5479. \draw (y) to (w);
  5480. \draw (v) to (w);
  5481. \end{tikzpicture}
  5482. \]
  5483. \fi}
  5484. \end{tcolorbox}
  5485. \caption{The interference graph of the example program.}
  5486. \label{fig:interfere}
  5487. \end{figure}
  5488. \begin{exercise}\normalfont\normalsize
  5489. \racket{Implement the compiler pass named \code{build\_interference} according
  5490. to the algorithm suggested here. We recommend using the Racket
  5491. \code{graph} package to create and inspect the interference graph.
  5492. The output graph of this pass should be stored in the $\itm{info}$ field of
  5493. the program, under the key \code{conflicts}.}
  5494. %
  5495. \python{Implement a function named \code{build\_interference}
  5496. according to the algorithm suggested above that
  5497. returns the interference graph.}
  5498. \end{exercise}
  5499. \section{Graph Coloring via Sudoku}
  5500. \label{sec:graph-coloring}
  5501. \index{subject}{graph coloring}
  5502. \index{subject}{sudoku}
  5503. \index{subject}{color}
  5504. We come to the main event discussed in this chapter, mapping variables
  5505. to registers and stack locations. Variables that interfere with each
  5506. other must be mapped to different locations. In terms of the
  5507. interference graph, this means that adjacent vertices must be mapped
  5508. to different locations. If we think of locations as colors, the
  5509. register allocation problem becomes the graph coloring
  5510. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5511. The reader may be more familiar with the graph coloring problem than he
  5512. or she realizes; the popular game of sudoku is an instance of the
  5513. graph coloring problem. The following describes how to build a graph
  5514. out of an initial sudoku board.
  5515. \begin{itemize}
  5516. \item There is one vertex in the graph for each sudoku square.
  5517. \item There is an edge between two vertices if the corresponding squares
  5518. are in the same row, in the same column, or in the same $3\times 3$ region.
  5519. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5520. \item On the basis of the initial assignment of numbers to squares on the
  5521. sudoku board, assign the corresponding colors to the corresponding
  5522. vertices in the graph.
  5523. \end{itemize}
  5524. If you can color the remaining vertices in the graph with the nine
  5525. colors, then you have also solved the corresponding game of sudoku.
  5526. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5527. the corresponding graph with colored vertices. Here we use a
  5528. monochrome representation of colors, mapping the sudoku number 1 to
  5529. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5530. of the vertices (the colored ones) because showing edges for all the
  5531. vertices would make the graph unreadable.
  5532. \begin{figure}[tbp]
  5533. \begin{tcolorbox}[colback=white]
  5534. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5535. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5536. \end{tcolorbox}
  5537. \caption{A sudoku game board and the corresponding colored graph.}
  5538. \label{fig:sudoku-graph}
  5539. \end{figure}
  5540. Some techniques for playing sudoku correspond to heuristics used in
  5541. graph coloring algorithms. For example, one of the basic techniques
  5542. for sudoku is called Pencil Marks. The idea is to use a process of
  5543. elimination to determine what numbers are no longer available for a
  5544. square and to write those numbers in the square (writing very
  5545. small). For example, if the number $1$ is assigned to a square, then
  5546. write the pencil mark $1$ in all the squares in the same row, column,
  5547. and region to indicate that $1$ is no longer an option for those other
  5548. squares.
  5549. %
  5550. The Pencil Marks technique corresponds to the notion of
  5551. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5552. saturation of a vertex, in sudoku terms, is the set of numbers that
  5553. are no longer available. In graph terminology, we have the following
  5554. definition:
  5555. \begin{equation*}
  5556. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5557. \text{ and } \mathrm{color}(v) = c \}
  5558. \end{equation*}
  5559. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5560. edge with $u$.
  5561. The Pencil Marks technique leads to a simple strategy for filling in
  5562. numbers: if there is a square with only one possible number left, then
  5563. choose that number! But what if there are no squares with only one
  5564. possibility left? One brute-force approach is to try them all: choose
  5565. the first one, and if that ultimately leads to a solution, great. If
  5566. not, backtrack and choose the next possibility. One good thing about
  5567. Pencil Marks is that it reduces the degree of branching in the search
  5568. tree. Nevertheless, backtracking can be terribly time consuming. One
  5569. way to reduce the amount of backtracking is to use the
  5570. most-constrained-first heuristic (aka minimum remaining
  5571. values)~\citep{Russell2003}. That is, in choosing a square, always
  5572. choose one with the fewest possibilities left (the vertex with the
  5573. highest saturation). The idea is that choosing highly constrained
  5574. squares earlier rather than later is better, because later on there may
  5575. not be any possibilities left in the highly saturated squares.
  5576. However, register allocation is easier than sudoku, because the
  5577. register allocator can fall back to assigning variables to stack
  5578. locations when the registers run out. Thus, it makes sense to replace
  5579. backtracking with greedy search: make the best choice at the time and
  5580. keep going. We still wish to minimize the number of colors needed, so
  5581. we use the most-constrained-first heuristic in the greedy search.
  5582. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5583. algorithm for register allocation based on saturation and the
  5584. most-constrained-first heuristic. It is roughly equivalent to the
  5585. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5586. sudoku, the algorithm represents colors with integers. The integers
  5587. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5588. register allocation. In particular, we recommend the following
  5589. correspondence, with $k=11$.
  5590. \begin{lstlisting}
  5591. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5592. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5593. \end{lstlisting}
  5594. The integers $k$ and larger correspond to stack locations. The
  5595. registers that are not used for register allocation, such as
  5596. \code{rax}, are assigned to negative integers. In particular, we
  5597. recommend the following correspondence.
  5598. \begin{lstlisting}
  5599. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5600. \end{lstlisting}
  5601. \begin{figure}[btp]
  5602. \begin{tcolorbox}[colback=white]
  5603. \centering
  5604. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5605. Algorithm: DSATUR
  5606. Input: A graph |$G$|
  5607. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5608. |$W \gets \mathrm{vertices}(G)$|
  5609. while |$W \neq \emptyset$| do
  5610. pick a vertex |$u$| from |$W$| with the highest saturation,
  5611. breaking ties randomly
  5612. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5613. |$\mathrm{color}[u] \gets c$|
  5614. |$W \gets W - \{u\}$|
  5615. \end{lstlisting}
  5616. \end{tcolorbox}
  5617. \caption{The saturation-based greedy graph coloring algorithm.}
  5618. \label{fig:satur-algo}
  5619. \end{figure}
  5620. {\if\edition\racketEd
  5621. With the DSATUR algorithm in hand, let us return to the running
  5622. example and consider how to color the interference graph shown in
  5623. figure~\ref{fig:interfere}.
  5624. %
  5625. We start by assigning each register node to its own color. For
  5626. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5627. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5628. (To reduce clutter in the interference graph, we elide nodes
  5629. that do not have interference edges, such as \code{rcx}.)
  5630. The variables are not yet colored, so they are annotated with a dash. We
  5631. then update the saturation for vertices that are adjacent to a
  5632. register, obtaining the following annotated graph. For example, the
  5633. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5634. \code{rax} and \code{rsp}.
  5635. \[
  5636. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5637. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5638. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5639. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5640. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5641. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5642. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5643. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5644. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5645. \draw (t1) to (rax);
  5646. \draw (t1) to (z);
  5647. \draw (z) to (y);
  5648. \draw (z) to (w);
  5649. \draw (x) to (w);
  5650. \draw (y) to (w);
  5651. \draw (v) to (w);
  5652. \draw (v) to (rsp);
  5653. \draw (w) to (rsp);
  5654. \draw (x) to (rsp);
  5655. \draw (y) to (rsp);
  5656. \path[-.,bend left=15] (z) edge node {} (rsp);
  5657. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5658. \draw (rax) to (rsp);
  5659. \end{tikzpicture}
  5660. \]
  5661. The algorithm says to select a maximally saturated vertex. So, we pick
  5662. $\ttm{t}$ and color it with the first available integer, which is
  5663. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5664. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5665. \[
  5666. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5667. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5668. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5669. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5670. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5671. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5672. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5673. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5674. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5675. \draw (t1) to (rax);
  5676. \draw (t1) to (z);
  5677. \draw (z) to (y);
  5678. \draw (z) to (w);
  5679. \draw (x) to (w);
  5680. \draw (y) to (w);
  5681. \draw (v) to (w);
  5682. \draw (v) to (rsp);
  5683. \draw (w) to (rsp);
  5684. \draw (x) to (rsp);
  5685. \draw (y) to (rsp);
  5686. \path[-.,bend left=15] (z) edge node {} (rsp);
  5687. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5688. \draw (rax) to (rsp);
  5689. \end{tikzpicture}
  5690. \]
  5691. We repeat the process, selecting a maximally saturated vertex,
  5692. choosing \code{z}, and coloring it with the first available number, which
  5693. is $1$. We add $1$ to the saturation for the neighboring vertices
  5694. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5695. \[
  5696. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5697. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5698. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5699. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5700. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5701. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5702. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5703. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5704. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5705. \draw (t1) to (rax);
  5706. \draw (t1) to (z);
  5707. \draw (z) to (y);
  5708. \draw (z) to (w);
  5709. \draw (x) to (w);
  5710. \draw (y) to (w);
  5711. \draw (v) to (w);
  5712. \draw (v) to (rsp);
  5713. \draw (w) to (rsp);
  5714. \draw (x) to (rsp);
  5715. \draw (y) to (rsp);
  5716. \path[-.,bend left=15] (z) edge node {} (rsp);
  5717. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5718. \draw (rax) to (rsp);
  5719. \end{tikzpicture}
  5720. \]
  5721. The most saturated vertices are now \code{w} and \code{y}. We color
  5722. \code{w} with the first available color, which is $0$.
  5723. \[
  5724. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5725. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5726. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5727. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5728. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5729. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5730. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5731. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5732. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5733. \draw (t1) to (rax);
  5734. \draw (t1) to (z);
  5735. \draw (z) to (y);
  5736. \draw (z) to (w);
  5737. \draw (x) to (w);
  5738. \draw (y) to (w);
  5739. \draw (v) to (w);
  5740. \draw (v) to (rsp);
  5741. \draw (w) to (rsp);
  5742. \draw (x) to (rsp);
  5743. \draw (y) to (rsp);
  5744. \path[-.,bend left=15] (z) edge node {} (rsp);
  5745. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5746. \draw (rax) to (rsp);
  5747. \end{tikzpicture}
  5748. \]
  5749. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5750. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5751. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5752. and \code{z}, whose colors are $0$ and $1$ respectively.
  5753. \[
  5754. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5755. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5756. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5757. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5758. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5759. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5760. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5761. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5762. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5763. \draw (t1) to (rax);
  5764. \draw (t1) to (z);
  5765. \draw (z) to (y);
  5766. \draw (z) to (w);
  5767. \draw (x) to (w);
  5768. \draw (y) to (w);
  5769. \draw (v) to (w);
  5770. \draw (v) to (rsp);
  5771. \draw (w) to (rsp);
  5772. \draw (x) to (rsp);
  5773. \draw (y) to (rsp);
  5774. \path[-.,bend left=15] (z) edge node {} (rsp);
  5775. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5776. \draw (rax) to (rsp);
  5777. \end{tikzpicture}
  5778. \]
  5779. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5780. \[
  5781. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5782. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5783. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5784. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5785. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5786. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5787. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5788. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5789. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5790. \draw (t1) to (rax);
  5791. \draw (t1) to (z);
  5792. \draw (z) to (y);
  5793. \draw (z) to (w);
  5794. \draw (x) to (w);
  5795. \draw (y) to (w);
  5796. \draw (v) to (w);
  5797. \draw (v) to (rsp);
  5798. \draw (w) to (rsp);
  5799. \draw (x) to (rsp);
  5800. \draw (y) to (rsp);
  5801. \path[-.,bend left=15] (z) edge node {} (rsp);
  5802. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5803. \draw (rax) to (rsp);
  5804. \end{tikzpicture}
  5805. \]
  5806. In the last step of the algorithm, we color \code{x} with $1$.
  5807. \[
  5808. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5809. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5810. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5811. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5812. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5813. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5814. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5815. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5816. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5817. \draw (t1) to (rax);
  5818. \draw (t1) to (z);
  5819. \draw (z) to (y);
  5820. \draw (z) to (w);
  5821. \draw (x) to (w);
  5822. \draw (y) to (w);
  5823. \draw (v) to (w);
  5824. \draw (v) to (rsp);
  5825. \draw (w) to (rsp);
  5826. \draw (x) to (rsp);
  5827. \draw (y) to (rsp);
  5828. \path[-.,bend left=15] (z) edge node {} (rsp);
  5829. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5830. \draw (rax) to (rsp);
  5831. \end{tikzpicture}
  5832. \]
  5833. So, we obtain the following coloring:
  5834. \[
  5835. \{
  5836. \ttm{rax} \mapsto -1,
  5837. \ttm{rsp} \mapsto -2,
  5838. \ttm{t} \mapsto 0,
  5839. \ttm{z} \mapsto 1,
  5840. \ttm{x} \mapsto 1,
  5841. \ttm{y} \mapsto 2,
  5842. \ttm{w} \mapsto 0,
  5843. \ttm{v} \mapsto 1
  5844. \}
  5845. \]
  5846. \fi}
  5847. %
  5848. {\if\edition\pythonEd\pythonColor
  5849. %
  5850. With the DSATUR algorithm in hand, let us return to the running
  5851. example and consider how to color the interference graph shown in
  5852. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5853. to indicate that it has not yet been assigned a color. Each register
  5854. node (not shown) should be assigned the number that the register
  5855. corresponds to, for example, color \code{rcx} with the number \code{0}
  5856. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5857. each node; all of them start as the empty set.
  5858. %
  5859. \[
  5860. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5861. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5862. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5863. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5864. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5865. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5866. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5867. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5868. \draw (t0) to (t1);
  5869. \draw (t0) to (z);
  5870. \draw (z) to (y);
  5871. \draw (z) to (w);
  5872. \draw (x) to (w);
  5873. \draw (y) to (w);
  5874. \draw (v) to (w);
  5875. \end{tikzpicture}
  5876. \]
  5877. The algorithm says to select a maximally saturated vertex, but they
  5878. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5879. and then we color it with the first available integer, which is $0$. We mark
  5880. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5881. they interfere with $\ttm{tmp\_0}$.
  5882. \[
  5883. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5884. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5885. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5886. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5887. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5888. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5889. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5890. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5891. \draw (t0) to (t1);
  5892. \draw (t0) to (z);
  5893. \draw (z) to (y);
  5894. \draw (z) to (w);
  5895. \draw (x) to (w);
  5896. \draw (y) to (w);
  5897. \draw (v) to (w);
  5898. \end{tikzpicture}
  5899. \]
  5900. We repeat the process. The most saturated vertices are \code{z} and
  5901. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5902. available number, which is $1$. We add $1$ to the saturation for the
  5903. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5904. \[
  5905. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5906. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5907. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5908. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5909. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5910. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5911. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5912. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5913. \draw (t0) to (t1);
  5914. \draw (t0) to (z);
  5915. \draw (z) to (y);
  5916. \draw (z) to (w);
  5917. \draw (x) to (w);
  5918. \draw (y) to (w);
  5919. \draw (v) to (w);
  5920. \end{tikzpicture}
  5921. \]
  5922. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5923. \code{y}. We color \code{w} with the first available color, which
  5924. is $0$.
  5925. \[
  5926. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5927. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5928. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5929. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5930. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5931. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5932. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5933. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5934. \draw (t0) to (t1);
  5935. \draw (t0) to (z);
  5936. \draw (z) to (y);
  5937. \draw (z) to (w);
  5938. \draw (x) to (w);
  5939. \draw (y) to (w);
  5940. \draw (v) to (w);
  5941. \end{tikzpicture}
  5942. \]
  5943. Now \code{y} is the most saturated, so we color it with $2$.
  5944. \[
  5945. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5946. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5947. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5948. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5949. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5950. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5951. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5952. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5953. \draw (t0) to (t1);
  5954. \draw (t0) to (z);
  5955. \draw (z) to (y);
  5956. \draw (z) to (w);
  5957. \draw (x) to (w);
  5958. \draw (y) to (w);
  5959. \draw (v) to (w);
  5960. \end{tikzpicture}
  5961. \]
  5962. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5963. We choose to color \code{v} with $1$.
  5964. \[
  5965. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5966. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5967. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5968. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5969. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5970. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5971. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5972. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5973. \draw (t0) to (t1);
  5974. \draw (t0) to (z);
  5975. \draw (z) to (y);
  5976. \draw (z) to (w);
  5977. \draw (x) to (w);
  5978. \draw (y) to (w);
  5979. \draw (v) to (w);
  5980. \end{tikzpicture}
  5981. \]
  5982. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5983. \[
  5984. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5985. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5986. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5987. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5988. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5989. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5990. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5991. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5992. \draw (t0) to (t1);
  5993. \draw (t0) to (z);
  5994. \draw (z) to (y);
  5995. \draw (z) to (w);
  5996. \draw (x) to (w);
  5997. \draw (y) to (w);
  5998. \draw (v) to (w);
  5999. \end{tikzpicture}
  6000. \]
  6001. So, we obtain the following coloring:
  6002. \[
  6003. \{ \ttm{tmp\_0} \mapsto 0,
  6004. \ttm{tmp\_1} \mapsto 1,
  6005. \ttm{z} \mapsto 1,
  6006. \ttm{x} \mapsto 1,
  6007. \ttm{y} \mapsto 2,
  6008. \ttm{w} \mapsto 0,
  6009. \ttm{v} \mapsto 1 \}
  6010. \]
  6011. \fi}
  6012. We recommend creating an auxiliary function named \code{color\_graph}
  6013. that takes an interference graph and a list of all the variables in
  6014. the program. This function should return a mapping of variables to
  6015. their colors (represented as natural numbers). By creating this helper
  6016. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  6017. when we add support for functions.
  6018. To prioritize the processing of highly saturated nodes inside the
  6019. \code{color\_graph} function, we recommend using the priority queue
  6020. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  6021. addition, you will need to maintain a mapping from variables to their
  6022. handles in the priority queue so that you can notify the priority
  6023. queue when their saturation changes.}
  6024. {\if\edition\racketEd
  6025. \begin{figure}[tp]
  6026. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  6027. \small
  6028. \begin{tcolorbox}[title=Priority Queue]
  6029. A \emph{priority queue}\index{subject}{priority queue}
  6030. is a collection of items in which the
  6031. removal of items is governed by priority. In a \emph{min} queue,
  6032. lower priority items are removed first. An implementation is in
  6033. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  6034. \begin{description}
  6035. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  6036. priority queue that uses the $\itm{cmp}$ predicate to determine
  6037. whether its first argument has lower or equal priority to its
  6038. second argument.
  6039. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  6040. items in the queue.
  6041. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  6042. the item into the queue and returns a handle for the item in the
  6043. queue.
  6044. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6045. the lowest priority.
  6046. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6047. notifies the queue that the priority has decreased for the item
  6048. associated with the given handle.
  6049. \end{description}
  6050. \end{tcolorbox}
  6051. %\end{wrapfigure}
  6052. \caption{The priority queue data structure.}
  6053. \label{fig:priority-queue}
  6054. \end{figure}
  6055. \fi}
  6056. With the coloring complete, we finalize the assignment of variables to
  6057. registers and stack locations. We map the first $k$ colors to the $k$
  6058. registers and the rest of the colors to stack locations. Suppose for
  6059. the moment that we have just one register to use for register
  6060. allocation, \key{rcx}. Then we have the following assignment.
  6061. \[
  6062. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6063. \]
  6064. Composing this mapping with the coloring, we arrive at the following
  6065. assignment of variables to locations.
  6066. {\if\edition\racketEd
  6067. \begin{gather*}
  6068. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6069. \ttm{w} \mapsto \key{\%rcx}, \,
  6070. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6071. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6072. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6073. \ttm{t} \mapsto \key{\%rcx} \}
  6074. \end{gather*}
  6075. \fi}
  6076. {\if\edition\pythonEd\pythonColor
  6077. \begin{gather*}
  6078. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6079. \ttm{w} \mapsto \key{\%rcx}, \,
  6080. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6081. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6082. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6083. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6084. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6085. \end{gather*}
  6086. \fi}
  6087. Adapt the code from the \code{assign\_homes} pass
  6088. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6089. assigned location. Applying this assignment to our running
  6090. example shown next, on the left, yields the program on the right.
  6091. \begin{center}
  6092. {\if\edition\racketEd
  6093. \begin{minipage}{0.35\textwidth}
  6094. \begin{lstlisting}
  6095. movq $1, v
  6096. movq $42, w
  6097. movq v, x
  6098. addq $7, x
  6099. movq x, y
  6100. movq x, z
  6101. addq w, z
  6102. movq y, t
  6103. negq t
  6104. movq z, %rax
  6105. addq t, %rax
  6106. jmp conclusion
  6107. \end{lstlisting}
  6108. \end{minipage}
  6109. $\Rightarrow\qquad$
  6110. \begin{minipage}{0.45\textwidth}
  6111. \begin{lstlisting}
  6112. movq $1, -8(%rbp)
  6113. movq $42, %rcx
  6114. movq -8(%rbp), -8(%rbp)
  6115. addq $7, -8(%rbp)
  6116. movq -8(%rbp), -16(%rbp)
  6117. movq -8(%rbp), -8(%rbp)
  6118. addq %rcx, -8(%rbp)
  6119. movq -16(%rbp), %rcx
  6120. negq %rcx
  6121. movq -8(%rbp), %rax
  6122. addq %rcx, %rax
  6123. jmp conclusion
  6124. \end{lstlisting}
  6125. \end{minipage}
  6126. \fi}
  6127. {\if\edition\pythonEd\pythonColor
  6128. \begin{minipage}{0.35\textwidth}
  6129. \begin{lstlisting}
  6130. movq $1, v
  6131. movq $42, w
  6132. movq v, x
  6133. addq $7, x
  6134. movq x, y
  6135. movq x, z
  6136. addq w, z
  6137. movq y, tmp_0
  6138. negq tmp_0
  6139. movq z, tmp_1
  6140. addq tmp_0, tmp_1
  6141. movq tmp_1, %rdi
  6142. callq print_int
  6143. \end{lstlisting}
  6144. \end{minipage}
  6145. $\Rightarrow\qquad$
  6146. \begin{minipage}{0.45\textwidth}
  6147. \begin{lstlisting}
  6148. movq $1, -8(%rbp)
  6149. movq $42, %rcx
  6150. movq -8(%rbp), -8(%rbp)
  6151. addq $7, -8(%rbp)
  6152. movq -8(%rbp), -16(%rbp)
  6153. movq -8(%rbp), -8(%rbp)
  6154. addq %rcx, -8(%rbp)
  6155. movq -16(%rbp), %rcx
  6156. negq %rcx
  6157. movq -8(%rbp), -8(%rbp)
  6158. addq %rcx, -8(%rbp)
  6159. movq -8(%rbp), %rdi
  6160. callq print_int
  6161. \end{lstlisting}
  6162. \end{minipage}
  6163. \fi}
  6164. \end{center}
  6165. \begin{exercise}\normalfont\normalsize
  6166. Implement the \code{allocate\_registers} \racket{pass}\python{function}.
  6167. Create five programs that exercise all aspects of the register
  6168. allocation algorithm, including spilling variables to the stack.
  6169. %
  6170. {\if\edition\racketEd
  6171. Replace \code{assign\_homes} in the list of \code{passes} in the
  6172. \code{run-tests.rkt} script with the three new passes:
  6173. \code{uncover\_live}, \code{build\_interference}, and
  6174. \code{allocate\_registers}.
  6175. Temporarily remove the call to \code{compiler-tests}.
  6176. Run the script to test the register allocator.
  6177. \fi}
  6178. %
  6179. {\if\edition\pythonEd\pythonColor
  6180. Update the \code{assign\_homes} pass to make use of
  6181. the functions you have created to perform register allocation:
  6182. \code{uncover\_live}, \code{build\_interference}, and
  6183. \code{allocate\_registers}.
  6184. Run the \code{run-tests.py} script to check whether the
  6185. output programs produce the same result as the input programs.
  6186. Inspect the generated x86 programs to make sure that some variables
  6187. are assigned to registers.
  6188. \fi}
  6189. \end{exercise}
  6190. \section{Patch Instructions}
  6191. \label{sec:patch-instructions}
  6192. The remaining step in the compilation to x86 is to ensure that the
  6193. instructions have at most one argument that is a memory access.
  6194. %
  6195. In the running example, the instruction \code{movq -8(\%rbp),
  6196. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6197. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6198. then move \code{rax} into \code{-16(\%rbp)}.
  6199. %
  6200. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6201. problematic, but they can simply be deleted. In general, we recommend
  6202. deleting all the trivial moves whose source and destination are the
  6203. same location.
  6204. %
  6205. The following is the output of \code{patch\_instructions} on the
  6206. running example.
  6207. \begin{center}
  6208. {\if\edition\racketEd
  6209. \begin{minipage}{0.35\textwidth}
  6210. \begin{lstlisting}
  6211. movq $1, -8(%rbp)
  6212. movq $42, %rcx
  6213. movq -8(%rbp), -8(%rbp)
  6214. addq $7, -8(%rbp)
  6215. movq -8(%rbp), -16(%rbp)
  6216. movq -8(%rbp), -8(%rbp)
  6217. addq %rcx, -8(%rbp)
  6218. movq -16(%rbp), %rcx
  6219. negq %rcx
  6220. movq -8(%rbp), %rax
  6221. addq %rcx, %rax
  6222. jmp conclusion
  6223. \end{lstlisting}
  6224. \end{minipage}
  6225. $\Rightarrow\qquad$
  6226. \begin{minipage}{0.45\textwidth}
  6227. \begin{lstlisting}
  6228. movq $1, -8(%rbp)
  6229. movq $42, %rcx
  6230. addq $7, -8(%rbp)
  6231. movq -8(%rbp), %rax
  6232. movq %rax, -16(%rbp)
  6233. addq %rcx, -8(%rbp)
  6234. movq -16(%rbp), %rcx
  6235. negq %rcx
  6236. movq -8(%rbp), %rax
  6237. addq %rcx, %rax
  6238. jmp conclusion
  6239. \end{lstlisting}
  6240. \end{minipage}
  6241. \fi}
  6242. {\if\edition\pythonEd\pythonColor
  6243. \begin{minipage}{0.35\textwidth}
  6244. \begin{lstlisting}
  6245. movq $1, -8(%rbp)
  6246. movq $42, %rcx
  6247. movq -8(%rbp), -8(%rbp)
  6248. addq $7, -8(%rbp)
  6249. movq -8(%rbp), -16(%rbp)
  6250. movq -8(%rbp), -8(%rbp)
  6251. addq %rcx, -8(%rbp)
  6252. movq -16(%rbp), %rcx
  6253. negq %rcx
  6254. movq -8(%rbp), -8(%rbp)
  6255. addq %rcx, -8(%rbp)
  6256. movq -8(%rbp), %rdi
  6257. callq print_int
  6258. \end{lstlisting}
  6259. \end{minipage}
  6260. $\Rightarrow\qquad$
  6261. \begin{minipage}{0.45\textwidth}
  6262. \begin{lstlisting}
  6263. movq $1, -8(%rbp)
  6264. movq $42, %rcx
  6265. addq $7, -8(%rbp)
  6266. movq -8(%rbp), %rax
  6267. movq %rax, -16(%rbp)
  6268. addq %rcx, -8(%rbp)
  6269. movq -16(%rbp), %rcx
  6270. negq %rcx
  6271. addq %rcx, -8(%rbp)
  6272. movq -8(%rbp), %rdi
  6273. callq print_int
  6274. \end{lstlisting}
  6275. \end{minipage}
  6276. \fi}
  6277. \end{center}
  6278. \begin{exercise}\normalfont\normalsize
  6279. %
  6280. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6281. %
  6282. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6283. %in the \code{run-tests.rkt} script.
  6284. %
  6285. Run the script to test the \code{patch\_instructions} pass.
  6286. \end{exercise}
  6287. \section{Generate Prelude and Conclusion}
  6288. \label{sec:print-x86-reg-alloc}
  6289. \index{subject}{calling conventions}
  6290. \index{subject}{prelude}\index{subject}{conclusion}
  6291. Recall that this pass generates the prelude and conclusion
  6292. instructions to satisfy the x86 calling conventions
  6293. (section~\ref{sec:calling-conventions}). With the addition of the
  6294. register allocator, the callee-saved registers used by the register
  6295. allocator must be saved in the prelude and restored in the conclusion.
  6296. In the \code{allocate\_registers} pass,
  6297. %
  6298. \racket{add an entry to the \itm{info}
  6299. of \code{X86Program} named \code{used\_callee}}
  6300. %
  6301. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6302. %
  6303. that stores the set of callee-saved registers that were assigned to
  6304. variables. The \code{prelude\_and\_conclusion} pass can then access
  6305. this information to decide which callee-saved registers need to be
  6306. saved and restored.
  6307. %
  6308. When calculating the amount to adjust the \code{rsp} in the prelude,
  6309. make sure to take into account the space used for saving the
  6310. callee-saved registers. Also, remember that the frame needs to be a
  6311. multiple of 16 bytes! We recommend using the following equation for
  6312. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6313. of stack locations used by spilled variables\footnote{Sometimes two or
  6314. more spilled variables are assigned to the same stack location, so
  6315. $S$ can be less than the number of spilled variables.} and $C$ be
  6316. the number of callee-saved registers that were
  6317. allocated\index{subject}{allocate} to
  6318. variables. The $\itm{align}$ function rounds a number up to the
  6319. nearest 16 bytes.
  6320. \[
  6321. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6322. \]
  6323. The reason we subtract $8\itm{C}$ in this equation is that the
  6324. prelude uses \code{pushq} to save each of the callee-saved registers,
  6325. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6326. \racket{An overview of all the passes involved in register
  6327. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6328. {\if\edition\racketEd
  6329. \begin{figure}[tbp]
  6330. \begin{tcolorbox}[colback=white]
  6331. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6332. \node (Lvar) at (0,2) {\large \LangVar{}};
  6333. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6334. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6335. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6336. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6337. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6338. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6339. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6340. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6341. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6342. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6343. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6344. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6345. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6346. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6347. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6348. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6349. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6350. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6351. \end{tikzpicture}
  6352. \end{tcolorbox}
  6353. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6354. \label{fig:reg-alloc-passes}
  6355. \end{figure}
  6356. \fi}
  6357. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6358. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6359. use of registers and the stack, we limit the register allocator for
  6360. this example to use just two registers: \code{rcx} (color $0$) and
  6361. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6362. \code{main} function, we push \code{rbx} onto the stack because it is
  6363. a callee-saved register and it was assigned to a variable by the
  6364. register allocator. We subtract \code{8} from the \code{rsp} at the
  6365. end of the prelude to reserve space for the one spilled variable.
  6366. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6367. Moving on to the program proper, we see how the registers were
  6368. allocated.
  6369. %
  6370. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6371. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6372. %
  6373. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6374. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6375. were assigned to \code{rbx}.}
  6376. %
  6377. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6378. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6379. callee-save register \code{rbx} onto the stack. The spilled variables
  6380. must be placed lower on the stack than the saved callee-save
  6381. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6382. \code{-16(\%rbp)}.
  6383. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6384. done in the prelude. We move the stack pointer up by \code{8} bytes
  6385. (the room for spilled variables), then pop the old values of
  6386. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6387. \code{retq} to return control to the operating system.
  6388. \begin{figure}[tbp]
  6389. \begin{minipage}{0.55\textwidth}
  6390. \begin{tcolorbox}[colback=white]
  6391. % var_test_28.rkt
  6392. % (use-minimal-set-of-registers! #t)
  6393. % 0 -> rcx
  6394. % 1 -> rbx
  6395. %
  6396. % t 0 rcx
  6397. % z 1 rbx
  6398. % w 0 rcx
  6399. % y 2 rbp -16
  6400. % v 1 rbx
  6401. % x 1 rbx
  6402. {\if\edition\racketEd
  6403. \begin{lstlisting}
  6404. start:
  6405. movq $1, %rbx
  6406. movq $42, %rcx
  6407. addq $7, %rbx
  6408. movq %rbx, -16(%rbp)
  6409. addq %rcx, %rbx
  6410. movq -16(%rbp), %rcx
  6411. negq %rcx
  6412. movq %rbx, %rax
  6413. addq %rcx, %rax
  6414. jmp conclusion
  6415. .globl main
  6416. main:
  6417. pushq %rbp
  6418. movq %rsp, %rbp
  6419. pushq %rbx
  6420. subq $8, %rsp
  6421. jmp start
  6422. conclusion:
  6423. addq $8, %rsp
  6424. popq %rbx
  6425. popq %rbp
  6426. retq
  6427. \end{lstlisting}
  6428. \fi}
  6429. {\if\edition\pythonEd\pythonColor
  6430. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6431. \begin{lstlisting}
  6432. .globl main
  6433. main:
  6434. pushq %rbp
  6435. movq %rsp, %rbp
  6436. pushq %rbx
  6437. subq $8, %rsp
  6438. movq $1, %rcx
  6439. movq $42, %rbx
  6440. addq $7, %rcx
  6441. movq %rcx, -16(%rbp)
  6442. addq %rbx, -16(%rbp)
  6443. negq %rcx
  6444. movq -16(%rbp), %rbx
  6445. addq %rcx, %rbx
  6446. movq %rbx, %rdi
  6447. callq print_int
  6448. addq $8, %rsp
  6449. popq %rbx
  6450. popq %rbp
  6451. retq
  6452. \end{lstlisting}
  6453. \fi}
  6454. \end{tcolorbox}
  6455. \end{minipage}
  6456. \caption{The x86 output from the running example
  6457. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6458. and \code{rcx}.}
  6459. \label{fig:running-example-x86}
  6460. \end{figure}
  6461. \begin{exercise}\normalfont\normalsize
  6462. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6463. %
  6464. \racket{
  6465. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6466. list of passes and the call to \code{compiler-tests}.}
  6467. %
  6468. Run the script to test the complete compiler for \LangVar{} that
  6469. performs register allocation.
  6470. \end{exercise}
  6471. \section{Challenge: Move Biasing}
  6472. \label{sec:move-biasing}
  6473. \index{subject}{move biasing}
  6474. This section describes an enhancement to the register allocator,
  6475. called move biasing, for students who are looking for an extra
  6476. challenge.
  6477. {\if\edition\racketEd
  6478. To motivate the need for move biasing we return to the running example,
  6479. but this time we use all the general purpose registers. So, we have
  6480. the following mapping of color numbers to registers.
  6481. \[
  6482. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6483. \]
  6484. Using the same assignment of variables to color numbers that was
  6485. produced by the register allocator described in the last section, we
  6486. get the following program.
  6487. \begin{center}
  6488. \begin{minipage}{0.35\textwidth}
  6489. \begin{lstlisting}
  6490. movq $1, v
  6491. movq $42, w
  6492. movq v, x
  6493. addq $7, x
  6494. movq x, y
  6495. movq x, z
  6496. addq w, z
  6497. movq y, t
  6498. negq t
  6499. movq z, %rax
  6500. addq t, %rax
  6501. jmp conclusion
  6502. \end{lstlisting}
  6503. \end{minipage}
  6504. $\Rightarrow\qquad$
  6505. \begin{minipage}{0.45\textwidth}
  6506. \begin{lstlisting}
  6507. movq $1, %rdx
  6508. movq $42, %rcx
  6509. movq %rdx, %rdx
  6510. addq $7, %rdx
  6511. movq %rdx, %rsi
  6512. movq %rdx, %rdx
  6513. addq %rcx, %rdx
  6514. movq %rsi, %rcx
  6515. negq %rcx
  6516. movq %rdx, %rax
  6517. addq %rcx, %rax
  6518. jmp conclusion
  6519. \end{lstlisting}
  6520. \end{minipage}
  6521. \end{center}
  6522. In this output code there are two \key{movq} instructions that
  6523. can be removed because their source and target are the same. However,
  6524. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6525. register, we could instead remove three \key{movq} instructions. We
  6526. can accomplish this by taking into account which variables appear in
  6527. \key{movq} instructions with which other variables.
  6528. \fi}
  6529. {\if\edition\pythonEd\pythonColor
  6530. %
  6531. To motivate the need for move biasing we return to the running example
  6532. and recall that in section~\ref{sec:patch-instructions} we were able to
  6533. remove three trivial move instructions from the running
  6534. example. However, we could remove another trivial move if we were able
  6535. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6536. We say that two variables $p$ and $q$ are \emph{move
  6537. related}\index{subject}{move related} if they participate together in
  6538. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6539. \key{movq} $q$\key{,} $p$.
  6540. %
  6541. Recall that we color variables that are more saturated before coloring
  6542. variables that are less saturated, and in the case of equally
  6543. saturated variables, we choose randomly. Now we break such ties by
  6544. giving preference to variables that have an available color that is
  6545. the same as the color of a move-related variable.
  6546. %
  6547. Furthermore, when the register allocator chooses a color for a
  6548. variable, it should prefer a color that has already been used for a
  6549. move-related variable if one exists (and assuming that they do not
  6550. interfere). This preference should not override the preference for
  6551. registers over stack locations. So, this preference should be used as
  6552. a tie breaker in choosing between two registers or in choosing between
  6553. two stack locations.
  6554. We recommend representing the move relationships in a graph, similarly
  6555. to how we represented interference. The following is the \emph{move
  6556. graph} for our example.
  6557. {\if\edition\racketEd
  6558. \[
  6559. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6560. \node (rax) at (0,0) {$\ttm{rax}$};
  6561. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6562. \node (t) at (0,2) {$\ttm{t}$};
  6563. \node (z) at (3,2) {$\ttm{z}$};
  6564. \node (x) at (6,2) {$\ttm{x}$};
  6565. \node (y) at (3,0) {$\ttm{y}$};
  6566. \node (w) at (6,0) {$\ttm{w}$};
  6567. \node (v) at (9,0) {$\ttm{v}$};
  6568. \draw (v) to (x);
  6569. \draw (x) to (y);
  6570. \draw (x) to (z);
  6571. \draw (y) to (t);
  6572. \end{tikzpicture}
  6573. \]
  6574. \fi}
  6575. %
  6576. {\if\edition\pythonEd\pythonColor
  6577. \[
  6578. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6579. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6580. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6581. \node (z) at (3,2) {$\ttm{z}$};
  6582. \node (x) at (6,2) {$\ttm{x}$};
  6583. \node (y) at (3,0) {$\ttm{y}$};
  6584. \node (w) at (6,0) {$\ttm{w}$};
  6585. \node (v) at (9,0) {$\ttm{v}$};
  6586. \draw (y) to (t0);
  6587. \draw (z) to (x);
  6588. \draw (z) to (t1);
  6589. \draw (x) to (y);
  6590. \draw (x) to (v);
  6591. \end{tikzpicture}
  6592. \]
  6593. \fi}
  6594. {\if\edition\racketEd
  6595. Now we replay the graph coloring, pausing to see the coloring of
  6596. \code{y}. Recall the following configuration. The most saturated vertices
  6597. were \code{w} and \code{y}.
  6598. \[
  6599. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6600. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6601. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6602. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6603. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6604. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6605. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6606. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6607. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6608. \draw (t1) to (rax);
  6609. \draw (t1) to (z);
  6610. \draw (z) to (y);
  6611. \draw (z) to (w);
  6612. \draw (x) to (w);
  6613. \draw (y) to (w);
  6614. \draw (v) to (w);
  6615. \draw (v) to (rsp);
  6616. \draw (w) to (rsp);
  6617. \draw (x) to (rsp);
  6618. \draw (y) to (rsp);
  6619. \path[-.,bend left=15] (z) edge node {} (rsp);
  6620. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6621. \draw (rax) to (rsp);
  6622. \end{tikzpicture}
  6623. \]
  6624. %
  6625. The last time, we chose to color \code{w} with $0$. This time, we see
  6626. that \code{w} is not move-related to any vertex, but \code{y} is
  6627. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6628. the same color as \code{t}.
  6629. \[
  6630. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6631. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6632. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6633. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6634. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6635. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6636. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6637. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6638. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6639. \draw (t1) to (rax);
  6640. \draw (t1) to (z);
  6641. \draw (z) to (y);
  6642. \draw (z) to (w);
  6643. \draw (x) to (w);
  6644. \draw (y) to (w);
  6645. \draw (v) to (w);
  6646. \draw (v) to (rsp);
  6647. \draw (w) to (rsp);
  6648. \draw (x) to (rsp);
  6649. \draw (y) to (rsp);
  6650. \path[-.,bend left=15] (z) edge node {} (rsp);
  6651. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6652. \draw (rax) to (rsp);
  6653. \end{tikzpicture}
  6654. \]
  6655. Now \code{w} is the most saturated, so we color it $2$.
  6656. \[
  6657. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6658. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6659. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6660. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6661. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6662. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6663. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6664. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6665. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6666. \draw (t1) to (rax);
  6667. \draw (t1) to (z);
  6668. \draw (z) to (y);
  6669. \draw (z) to (w);
  6670. \draw (x) to (w);
  6671. \draw (y) to (w);
  6672. \draw (v) to (w);
  6673. \draw (v) to (rsp);
  6674. \draw (w) to (rsp);
  6675. \draw (x) to (rsp);
  6676. \draw (y) to (rsp);
  6677. \path[-.,bend left=15] (z) edge node {} (rsp);
  6678. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6679. \draw (rax) to (rsp);
  6680. \end{tikzpicture}
  6681. \]
  6682. At this point, vertices \code{x} and \code{v} are most saturated, but
  6683. \code{x} is move related to \code{y} and \code{z}, so we color
  6684. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6685. \[
  6686. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6687. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6688. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6689. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6690. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6691. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6692. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6693. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6694. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6695. \draw (t1) to (rax);
  6696. \draw (t) to (z);
  6697. \draw (z) to (y);
  6698. \draw (z) to (w);
  6699. \draw (x) to (w);
  6700. \draw (y) to (w);
  6701. \draw (v) to (w);
  6702. \draw (v) to (rsp);
  6703. \draw (w) to (rsp);
  6704. \draw (x) to (rsp);
  6705. \draw (y) to (rsp);
  6706. \path[-.,bend left=15] (z) edge node {} (rsp);
  6707. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6708. \draw (rax) to (rsp);
  6709. \end{tikzpicture}
  6710. \]
  6711. \fi}
  6712. %
  6713. {\if\edition\pythonEd\pythonColor
  6714. Now we replay the graph coloring, pausing before the coloring of
  6715. \code{w}. Recall the following configuration. The most saturated vertices
  6716. were \code{tmp\_1}, \code{w}, and \code{y}.
  6717. \[
  6718. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6719. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6720. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6721. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6722. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6723. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6724. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6725. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6726. \draw (t0) to (t1);
  6727. \draw (t0) to (z);
  6728. \draw (z) to (y);
  6729. \draw (z) to (w);
  6730. \draw (x) to (w);
  6731. \draw (y) to (w);
  6732. \draw (v) to (w);
  6733. \end{tikzpicture}
  6734. \]
  6735. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6736. or \code{y}. Note, however, that \code{w} is not move related to any
  6737. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6738. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6739. \code{y} and color it $0$, we can delete another move instruction.
  6740. \[
  6741. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6742. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6743. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6744. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6745. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6746. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6747. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6748. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6749. \draw (t0) to (t1);
  6750. \draw (t0) to (z);
  6751. \draw (z) to (y);
  6752. \draw (z) to (w);
  6753. \draw (x) to (w);
  6754. \draw (y) to (w);
  6755. \draw (v) to (w);
  6756. \end{tikzpicture}
  6757. \]
  6758. Now \code{w} is the most saturated, so we color it $2$.
  6759. \[
  6760. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6761. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6762. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6763. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6764. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6765. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6766. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6767. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6768. \draw (t0) to (t1);
  6769. \draw (t0) to (z);
  6770. \draw (z) to (y);
  6771. \draw (z) to (w);
  6772. \draw (x) to (w);
  6773. \draw (y) to (w);
  6774. \draw (v) to (w);
  6775. \end{tikzpicture}
  6776. \]
  6777. To finish the coloring, \code{x} and \code{v} get $0$ and
  6778. \code{tmp\_1} gets $1$.
  6779. \[
  6780. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6781. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6782. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6783. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6784. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6785. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6786. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6787. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6788. \draw (t0) to (t1);
  6789. \draw (t0) to (z);
  6790. \draw (z) to (y);
  6791. \draw (z) to (w);
  6792. \draw (x) to (w);
  6793. \draw (y) to (w);
  6794. \draw (v) to (w);
  6795. \end{tikzpicture}
  6796. \]
  6797. \fi}
  6798. So, we have the following assignment of variables to registers.
  6799. {\if\edition\racketEd
  6800. \begin{gather*}
  6801. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6802. \ttm{w} \mapsto \key{\%rsi}, \,
  6803. \ttm{x} \mapsto \key{\%rcx}, \,
  6804. \ttm{y} \mapsto \key{\%rcx}, \,
  6805. \ttm{z} \mapsto \key{\%rdx}, \,
  6806. \ttm{t} \mapsto \key{\%rcx} \}
  6807. \end{gather*}
  6808. \fi}
  6809. {\if\edition\pythonEd\pythonColor
  6810. \begin{gather*}
  6811. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6812. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6813. \ttm{x} \mapsto \key{\%rcx}, \,
  6814. \ttm{y} \mapsto \key{\%rcx}, \\
  6815. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6816. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6817. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6818. \end{gather*}
  6819. \fi}
  6820. %
  6821. We apply this register assignment to the running example shown next,
  6822. on the left, to obtain the code in the middle. The
  6823. \code{patch\_instructions} then deletes the trivial moves to obtain
  6824. the code on the right.
  6825. {\if\edition\racketEd
  6826. \begin{center}
  6827. \begin{minipage}{0.2\textwidth}
  6828. \begin{lstlisting}
  6829. movq $1, v
  6830. movq $42, w
  6831. movq v, x
  6832. addq $7, x
  6833. movq x, y
  6834. movq x, z
  6835. addq w, z
  6836. movq y, t
  6837. negq t
  6838. movq z, %rax
  6839. addq t, %rax
  6840. jmp conclusion
  6841. \end{lstlisting}
  6842. \end{minipage}
  6843. $\Rightarrow\qquad$
  6844. \begin{minipage}{0.25\textwidth}
  6845. \begin{lstlisting}
  6846. movq $1, %rcx
  6847. movq $42, %rsi
  6848. movq %rcx, %rcx
  6849. addq $7, %rcx
  6850. movq %rcx, %rcx
  6851. movq %rcx, %rdx
  6852. addq %rsi, %rdx
  6853. movq %rcx, %rcx
  6854. negq %rcx
  6855. movq %rdx, %rax
  6856. addq %rcx, %rax
  6857. jmp conclusion
  6858. \end{lstlisting}
  6859. \end{minipage}
  6860. $\Rightarrow\qquad$
  6861. \begin{minipage}{0.23\textwidth}
  6862. \begin{lstlisting}
  6863. movq $1, %rcx
  6864. movq $42, %rsi
  6865. addq $7, %rcx
  6866. movq %rcx, %rdx
  6867. addq %rsi, %rdx
  6868. negq %rcx
  6869. movq %rdx, %rax
  6870. addq %rcx, %rax
  6871. jmp conclusion
  6872. \end{lstlisting}
  6873. \end{minipage}
  6874. \end{center}
  6875. \fi}
  6876. {\if\edition\pythonEd\pythonColor
  6877. \begin{center}
  6878. \begin{minipage}{0.20\textwidth}
  6879. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6880. movq $1, v
  6881. movq $42, w
  6882. movq v, x
  6883. addq $7, x
  6884. movq x, y
  6885. movq x, z
  6886. addq w, z
  6887. movq y, tmp_0
  6888. negq tmp_0
  6889. movq z, tmp_1
  6890. addq tmp_0, tmp_1
  6891. movq tmp_1, %rdi
  6892. callq _print_int
  6893. \end{lstlisting}
  6894. \end{minipage}
  6895. ${\Rightarrow\qquad}$
  6896. \begin{minipage}{0.35\textwidth}
  6897. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6898. movq $1, %rcx
  6899. movq $42, -16(%rbp)
  6900. movq %rcx, %rcx
  6901. addq $7, %rcx
  6902. movq %rcx, %rcx
  6903. movq %rcx, -8(%rbp)
  6904. addq -16(%rbp), -8(%rbp)
  6905. movq %rcx, %rcx
  6906. negq %rcx
  6907. movq -8(%rbp), -8(%rbp)
  6908. addq %rcx, -8(%rbp)
  6909. movq -8(%rbp), %rdi
  6910. callq _print_int
  6911. \end{lstlisting}
  6912. \end{minipage}
  6913. ${\Rightarrow\qquad}$
  6914. \begin{minipage}{0.20\textwidth}
  6915. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6916. movq $1, %rcx
  6917. movq $42, -16(%rbp)
  6918. addq $7, %rcx
  6919. movq %rcx, -8(%rbp)
  6920. movq -16(%rbp), %rax
  6921. addq %rax, -8(%rbp)
  6922. negq %rcx
  6923. addq %rcx, -8(%rbp)
  6924. movq -8(%rbp), %rdi
  6925. callq print_int
  6926. \end{lstlisting}
  6927. \end{minipage}
  6928. \end{center}
  6929. \fi}
  6930. \begin{exercise}\normalfont\normalsize
  6931. Change your implementation of \code{allocate\_registers} to take move
  6932. biasing into account. Create two new tests that include at least one
  6933. opportunity for move biasing, and visually inspect the output x86
  6934. programs to make sure that your move biasing is working properly. Make
  6935. sure that your compiler still passes all the tests.
  6936. \end{exercise}
  6937. %To do: another neat challenge would be to do
  6938. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6939. %% \subsection{Output of the Running Example}
  6940. %% \label{sec:reg-alloc-output}
  6941. % challenge: prioritize variables based on execution frequencies
  6942. % and the number of uses of a variable
  6943. % challenge: enhance the coloring algorithm using Chaitin's
  6944. % approach of prioritizing high-degree variables
  6945. % by removing low-degree variables (coloring them later)
  6946. % from the interference graph
  6947. \section{Further Reading}
  6948. \label{sec:register-allocation-further-reading}
  6949. Early register allocation algorithms were developed for Fortran
  6950. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6951. of graph coloring began in the late 1970s and early 1980s with the
  6952. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6953. algorithm is based on the following observation of
  6954. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6955. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6956. $v$ removed is also $k$ colorable. To see why, suppose that the
  6957. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6958. different colors, but because there are fewer than $k$ neighbors, there
  6959. will be one or more colors left over to use for coloring $v$ in $G$.
  6960. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6961. less than $k$ from the graph and recursively colors the rest of the
  6962. graph. Upon returning from the recursion, it colors $v$ with one of
  6963. the available colors and returns. \citet{Chaitin:1982vn} augments
  6964. this algorithm to handle spilling as follows. If there are no vertices
  6965. of degree lower than $k$ then pick a vertex at random, spill it,
  6966. remove it from the graph, and proceed recursively to color the rest of
  6967. the graph.
  6968. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6969. move-related and that don't interfere with each other, in a process
  6970. called \emph{coalescing}. Although coalescing decreases the number of
  6971. moves, it can make the graph more difficult to
  6972. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6973. which two variables are merged only if they have fewer than $k$
  6974. neighbors of high degree. \citet{George:1996aa} observes that
  6975. conservative coalescing is sometimes too conservative and made it more
  6976. aggressive by iterating the coalescing with the removal of low-degree
  6977. vertices.
  6978. %
  6979. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6980. also proposed \emph{biased coloring}, in which a variable is assigned to
  6981. the same color as another move-related variable if possible, as
  6982. discussed in section~\ref{sec:move-biasing}.
  6983. %
  6984. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6985. performs coalescing, graph coloring, and spill code insertion until
  6986. all variables have been assigned a location.
  6987. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6988. spilled variables that don't have to be: a high-degree variable can be
  6989. colorable if many of its neighbors are assigned the same color.
  6990. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6991. high-degree vertex is not immediately spilled. Instead the decision is
  6992. deferred until after the recursive call, when it is apparent whether
  6993. there is an available color or not. We observe that this algorithm is
  6994. equivalent to the smallest-last ordering
  6995. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6996. be registers and the rest to be stack locations.
  6997. %% biased coloring
  6998. Earlier editions of the compiler course at Indiana University
  6999. \citep{Dybvig:2010aa} were based on the algorithm of
  7000. \citet{Briggs:1994kx}.
  7001. The smallest-last ordering algorithm is one of many \emph{greedy}
  7002. coloring algorithms. A greedy coloring algorithm visits all the
  7003. vertices in a particular order and assigns each one the first
  7004. available color. An \emph{offline} greedy algorithm chooses the
  7005. ordering up front, prior to assigning colors. The algorithm of
  7006. \citet{Chaitin:1981vl} should be considered offline because the vertex
  7007. ordering does not depend on the colors assigned. Other orderings are
  7008. possible. For example, \citet{Chow:1984ys} ordered variables according
  7009. to an estimate of runtime cost.
  7010. An \emph{online} greedy coloring algorithm uses information about the
  7011. current assignment of colors to influence the order in which the
  7012. remaining vertices are colored. The saturation-based algorithm
  7013. described in this chapter is one such algorithm. We choose to use
  7014. saturation-based coloring because it is fun to introduce graph
  7015. coloring via sudoku!
  7016. A register allocator may choose to map each variable to just one
  7017. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  7018. variable to one or more locations. The latter can be achieved by
  7019. \emph{live range splitting}, where a variable is replaced by several
  7020. variables that each handle part of its live
  7021. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  7022. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  7023. %% replacement algorithm, bottom-up local
  7024. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  7025. %% Cooper: top-down (priority bassed), bottom-up
  7026. %% top-down
  7027. %% order variables by priority (estimated cost)
  7028. %% caveat: split variables into two groups:
  7029. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  7030. %% color the constrained ones first
  7031. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  7032. %% cite J. Cocke for an algorithm that colors variables
  7033. %% in a high-degree first ordering
  7034. %Register Allocation via Usage Counts, Freiburghouse CACM
  7035. \citet{Palsberg:2007si} observes that many of the interference graphs
  7036. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  7037. that is, every cycle with four or more edges has an edge that is not
  7038. part of the cycle but that connects two vertices on the cycle. Such
  7039. graphs can be optimally colored by the greedy algorithm with a vertex
  7040. ordering determined by maximum cardinality search.
  7041. In situations in which compile time is of utmost importance, such as
  7042. in just-in-time compilers, graph coloring algorithms can be too
  7043. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  7044. be more appropriate.
  7045. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  7046. {\if\edition\racketEd
  7047. \addtocontents{toc}{\newpage}
  7048. \fi}
  7049. \chapter{Booleans and Conditionals}
  7050. \label{ch:Lif}
  7051. \setcounter{footnote}{0}
  7052. The \LangVar{} language has only a single kind of value, the
  7053. integers. In this chapter we add a second kind of value, the Booleans,
  7054. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7055. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7056. are written
  7057. \TRUE{}\index{subject}{True@\TRUE{}} and
  7058. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7059. language includes several operations that involve Booleans
  7060. (\key{and}\index{subject}{and@\ANDNAME{}},
  7061. \key{or}\index{subject}{or@\ORNAME{}},
  7062. \key{not}\index{subject}{not@\NOTNAME{}},
  7063. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7064. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7065. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7066. conditional expression\index{subject}{conditional expression}%
  7067. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7068. With the addition of \key{if}, programs can have
  7069. nontrivial control flow\index{subject}{control flow}, which
  7070. %
  7071. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7072. %
  7073. \python{impacts liveness analysis and motivates a new pass named
  7074. \code{explicate\_control}.}
  7075. %
  7076. Also, because we now have two kinds of values, we need to handle
  7077. programs that apply an operation to the wrong kind of value, such as
  7078. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7079. There are two language design options for such situations. One option
  7080. is to signal an error and the other is to provide a wider
  7081. interpretation of the operation. \racket{The Racket
  7082. language}\python{Python} uses a mixture of these two options,
  7083. depending on the operation and the kind of value. For example, the
  7084. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7085. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7086. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7087. %
  7088. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7089. in Racket because \code{car} expects a pair.}
  7090. %
  7091. \python{On the other hand, \code{1[0]} results in a runtime error
  7092. in Python because an ``\code{int} object is not subscriptable.''}
  7093. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7094. design choices as \racket{Racket}\python{Python}, except that much of the
  7095. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7096. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7097. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7098. \python{MyPy} reports a compile-time error
  7099. %
  7100. \racket{because Racket expects the type of the argument to be of the form
  7101. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7102. %
  7103. \python{stating that a ``value of type \code{int} is not indexable.''}
  7104. The \LangIf{} language performs type checking during compilation just as
  7105. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7106. the alternative choice, that is, a dynamically typed language like
  7107. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7108. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7109. restrictive, for example, rejecting \racket{\code{(not
  7110. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7111. fairly simple because the focus of this book is on compilation and not
  7112. type systems, about which there are already several excellent
  7113. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7114. This chapter is organized as follows. We begin by defining the syntax
  7115. and interpreter for the \LangIf{} language
  7116. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7117. checking (aka semantic analysis\index{subject}{semantic analysis})
  7118. and define a type checker for \LangIf{}
  7119. (section~\ref{sec:type-check-Lif}).
  7120. %
  7121. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7122. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7123. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7124. %
  7125. The remaining sections of this chapter discuss how Booleans and
  7126. conditional control flow require changes to the existing compiler
  7127. passes and the addition of new ones. We introduce the \code{shrink}
  7128. pass to translate some operators into others, thereby reducing the
  7129. number of operators that need to be handled in later passes.
  7130. %
  7131. The main event of this chapter is the \code{explicate\_control} pass
  7132. that is responsible for translating \code{if}s into conditional
  7133. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7134. %
  7135. Regarding register allocation, there is the interesting question of
  7136. how to handle conditional \code{goto}s during liveness analysis.
  7137. \section{The \LangIf{} Language}
  7138. \label{sec:lang-if}
  7139. Definitions of the concrete syntax and abstract syntax of the
  7140. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7141. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7142. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7143. literals\index{subject}{literals}
  7144. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7145. \python{, and the \code{if} statement}. We expand the set of
  7146. operators to include
  7147. \begin{enumerate}
  7148. \item the logical operators \key{and}, \key{or}, and \key{not},
  7149. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7150. for comparing integers or Booleans for equality, and
  7151. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7152. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7153. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7154. comparing integers.
  7155. \end{enumerate}
  7156. \racket{We reorganize the abstract syntax for the primitive
  7157. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7158. rule for all of them. This means that the grammar no longer checks
  7159. whether the arity of an operator matches the number of
  7160. arguments. That responsibility is moved to the type checker for
  7161. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7162. \newcommand{\LifGrammarRacket}{
  7163. \begin{array}{lcl}
  7164. \Type &::=& \key{Boolean} \\
  7165. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7166. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7167. \Exp &::=& \itm{bool}
  7168. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7169. \MID (\key{not}\;\Exp) \\
  7170. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7171. \end{array}
  7172. }
  7173. \newcommand{\LifASTRacket}{
  7174. \begin{array}{lcl}
  7175. \Type &::=& \key{Boolean} \\
  7176. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7177. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7178. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7179. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7180. \end{array}
  7181. }
  7182. \newcommand{\LintOpAST}{
  7183. \begin{array}{rcl}
  7184. \Type &::=& \key{Integer} \\
  7185. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7186. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7187. \end{array}
  7188. }
  7189. \newcommand{\LifGrammarPython}{
  7190. \begin{array}{rcl}
  7191. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7192. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7193. \MID \key{not}~\Exp \\
  7194. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7195. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7196. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7197. \end{array}
  7198. }
  7199. \newcommand{\LifASTPython}{
  7200. \begin{array}{lcl}
  7201. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7202. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7203. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7204. \Exp &::=& \BOOL{\itm{bool}}
  7205. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7206. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7207. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7208. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7209. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7210. \end{array}
  7211. }
  7212. \begin{figure}[tp]
  7213. \centering
  7214. \begin{tcolorbox}[colback=white]
  7215. {\if\edition\racketEd
  7216. \[
  7217. \begin{array}{l}
  7218. \gray{\LintGrammarRacket{}} \\ \hline
  7219. \gray{\LvarGrammarRacket{}} \\ \hline
  7220. \LifGrammarRacket{} \\
  7221. \begin{array}{lcl}
  7222. \LangIfM{} &::=& \Exp
  7223. \end{array}
  7224. \end{array}
  7225. \]
  7226. \fi}
  7227. {\if\edition\pythonEd\pythonColor
  7228. \[
  7229. \begin{array}{l}
  7230. \gray{\LintGrammarPython} \\ \hline
  7231. \gray{\LvarGrammarPython} \\ \hline
  7232. \LifGrammarPython \\
  7233. \begin{array}{rcl}
  7234. \LangIfM{} &::=& \Stmt^{*}
  7235. \end{array}
  7236. \end{array}
  7237. \]
  7238. \fi}
  7239. \end{tcolorbox}
  7240. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7241. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7242. \label{fig:Lif-concrete-syntax}
  7243. \index{subject}{Lif@\LangIf{} concrete syntax}
  7244. \end{figure}
  7245. \begin{figure}[tp]
  7246. %\begin{minipage}{0.66\textwidth}
  7247. \begin{tcolorbox}[colback=white]
  7248. \centering
  7249. {\if\edition\racketEd
  7250. \[
  7251. \begin{array}{l}
  7252. \gray{\LintOpAST} \\ \hline
  7253. \gray{\LvarASTRacket{}} \\ \hline
  7254. \LifASTRacket{} \\
  7255. \begin{array}{lcl}
  7256. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7257. \end{array}
  7258. \end{array}
  7259. \]
  7260. \fi}
  7261. {\if\edition\pythonEd\pythonColor
  7262. \[
  7263. \begin{array}{l}
  7264. \gray{\LintASTPython} \\ \hline
  7265. \gray{\LvarASTPython} \\ \hline
  7266. \LifASTPython \\
  7267. \begin{array}{lcl}
  7268. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7269. \end{array}
  7270. \end{array}
  7271. \]
  7272. \fi}
  7273. \end{tcolorbox}
  7274. %\end{minipage}
  7275. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7276. \python{
  7277. \index{subject}{BoolOp@\texttt{BoolOp}}
  7278. \index{subject}{Compare@\texttt{Compare}}
  7279. \index{subject}{Lt@\texttt{Lt}}
  7280. \index{subject}{LtE@\texttt{LtE}}
  7281. \index{subject}{Gt@\texttt{Gt}}
  7282. \index{subject}{GtE@\texttt{GtE}}
  7283. }
  7284. \caption{The abstract syntax of \LangIf{}.}
  7285. \label{fig:Lif-syntax}
  7286. \index{subject}{Lif@\LangIf{} abstract syntax}
  7287. \end{figure}
  7288. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7289. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7290. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7291. evaluate to the corresponding Boolean values, behavior that is
  7292. inherited from the interpreter for \LangInt{}
  7293. (figure~\ref{fig:interp-Lint-class}).
  7294. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7295. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7296. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7297. \code{and}, \code{or}, and \code{not} behave according to propositional
  7298. logic. In addition, the \code{and} and \code{or} operations perform
  7299. \emph{short-circuit evaluation}.
  7300. %
  7301. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7302. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7303. %
  7304. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7305. evaluated if $e_1$ evaluates to \TRUE{}.
  7306. \racket{With the increase in the number of primitive operations, the
  7307. interpreter would become repetitive without some care. We refactor
  7308. the case for \code{Prim}, moving the code that differs with each
  7309. operation into the \code{interp\_op} method shown in
  7310. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7311. \code{or} operations separately because of their short-circuiting
  7312. behavior.}
  7313. \begin{figure}[tbp]
  7314. \begin{tcolorbox}[colback=white]
  7315. {\if\edition\racketEd
  7316. \begin{lstlisting}
  7317. (define interp-Lif-class
  7318. (class interp-Lvar-class
  7319. (super-new)
  7320. (define/public (interp_op op) ...)
  7321. (define/override ((interp_exp env) e)
  7322. (define recur (interp_exp env))
  7323. (match e
  7324. [(Bool b) b]
  7325. [(If cnd thn els)
  7326. (match (recur cnd)
  7327. [#t (recur thn)]
  7328. [#f (recur els)])]
  7329. [(Prim 'and (list e1 e2))
  7330. (match (recur e1)
  7331. [#t (match (recur e2) [#t #t] [#f #f])]
  7332. [#f #f])]
  7333. [(Prim 'or (list e1 e2))
  7334. (define v1 (recur e1))
  7335. (match v1
  7336. [#t #t]
  7337. [#f (match (recur e2) [#t #t] [#f #f])])]
  7338. [(Prim op args)
  7339. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7340. [else ((super interp_exp env) e)]))
  7341. ))
  7342. (define (interp_Lif p)
  7343. (send (new interp-Lif-class) interp_program p))
  7344. \end{lstlisting}
  7345. \fi}
  7346. {\if\edition\pythonEd\pythonColor
  7347. \begin{lstlisting}
  7348. class InterpLif(InterpLvar):
  7349. def interp_exp(self, e, env):
  7350. match e:
  7351. case IfExp(test, body, orelse):
  7352. if self.interp_exp(test, env):
  7353. return self.interp_exp(body, env)
  7354. else:
  7355. return self.interp_exp(orelse, env)
  7356. case UnaryOp(Not(), v):
  7357. return not self.interp_exp(v, env)
  7358. case BoolOp(And(), values):
  7359. if self.interp_exp(values[0], env):
  7360. return self.interp_exp(values[1], env)
  7361. else:
  7362. return False
  7363. case BoolOp(Or(), values):
  7364. if self.interp_exp(values[0], env):
  7365. return True
  7366. else:
  7367. return self.interp_exp(values[1], env)
  7368. case Compare(left, [cmp], [right]):
  7369. l = self.interp_exp(left, env)
  7370. r = self.interp_exp(right, env)
  7371. return self.interp_cmp(cmp)(l, r)
  7372. case _:
  7373. return super().interp_exp(e, env)
  7374. def interp_stmt(self, s, env, cont):
  7375. match s:
  7376. case If(test, body, orelse):
  7377. match self.interp_exp(test, env):
  7378. case True:
  7379. return self.interp_stmts(body + cont, env)
  7380. case False:
  7381. return self.interp_stmts(orelse + cont, env)
  7382. case _:
  7383. return super().interp_stmt(s, env, cont)
  7384. ...
  7385. \end{lstlisting}
  7386. \fi}
  7387. \end{tcolorbox}
  7388. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7389. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7390. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7391. \label{fig:interp-Lif}
  7392. \end{figure}
  7393. {\if\edition\racketEd
  7394. \begin{figure}[tbp]
  7395. \begin{tcolorbox}[colback=white]
  7396. \begin{lstlisting}
  7397. (define/public (interp_op op)
  7398. (match op
  7399. ['+ fx+]
  7400. ['- fx-]
  7401. ['read read-fixnum]
  7402. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7403. ['eq? (lambda (v1 v2)
  7404. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7405. (and (boolean? v1) (boolean? v2))
  7406. (and (vector? v1) (vector? v2)))
  7407. (eq? v1 v2)]))]
  7408. ['< (lambda (v1 v2)
  7409. (cond [(and (fixnum? v1) (fixnum? v2))
  7410. (< v1 v2)]))]
  7411. ['<= (lambda (v1 v2)
  7412. (cond [(and (fixnum? v1) (fixnum? v2))
  7413. (<= v1 v2)]))]
  7414. ['> (lambda (v1 v2)
  7415. (cond [(and (fixnum? v1) (fixnum? v2))
  7416. (> v1 v2)]))]
  7417. ['>= (lambda (v1 v2)
  7418. (cond [(and (fixnum? v1) (fixnum? v2))
  7419. (>= v1 v2)]))]
  7420. [else (error 'interp_op "unknown operator")]))
  7421. \end{lstlisting}
  7422. \end{tcolorbox}
  7423. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7424. \label{fig:interp-op-Lif}
  7425. \end{figure}
  7426. \fi}
  7427. {\if\edition\pythonEd\pythonColor
  7428. \begin{figure}
  7429. \begin{tcolorbox}[colback=white]
  7430. \begin{lstlisting}
  7431. class InterpLif(InterpLvar):
  7432. ...
  7433. def interp_cmp(self, cmp):
  7434. match cmp:
  7435. case Lt():
  7436. return lambda x, y: x < y
  7437. case LtE():
  7438. return lambda x, y: x <= y
  7439. case Gt():
  7440. return lambda x, y: x > y
  7441. case GtE():
  7442. return lambda x, y: x >= y
  7443. case Eq():
  7444. return lambda x, y: x == y
  7445. case NotEq():
  7446. return lambda x, y: x != y
  7447. \end{lstlisting}
  7448. \end{tcolorbox}
  7449. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7450. \label{fig:interp-cmp-Lif}
  7451. \end{figure}
  7452. \fi}
  7453. \section{Type Checking \LangIf{} Programs}
  7454. \label{sec:type-check-Lif}
  7455. It is helpful to think about type checking\index{subject}{type
  7456. checking} in two complementary ways. A type checker predicts the
  7457. type of value that will be produced by each expression in the program.
  7458. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7459. type checker should predict that {\if\edition\racketEd
  7460. \begin{lstlisting}
  7461. (+ 10 (- (+ 12 20)))
  7462. \end{lstlisting}
  7463. \fi}
  7464. {\if\edition\pythonEd\pythonColor
  7465. \begin{lstlisting}
  7466. 10 + -(12 + 20)
  7467. \end{lstlisting}
  7468. \fi}
  7469. \noindent produces a value of type \INTTY{}, whereas
  7470. {\if\edition\racketEd
  7471. \begin{lstlisting}
  7472. (and (not #f) #t)
  7473. \end{lstlisting}
  7474. \fi}
  7475. {\if\edition\pythonEd\pythonColor
  7476. \begin{lstlisting}
  7477. (not False) and True
  7478. \end{lstlisting}
  7479. \fi}
  7480. \noindent produces a value of type \BOOLTY{}.
  7481. A second way to think about type checking is that it enforces a set of
  7482. rules about which operators can be applied to which kinds of
  7483. values. For example, our type checker for \LangIf{} signals an error
  7484. for the following expression:
  7485. %
  7486. {\if\edition\racketEd
  7487. \begin{lstlisting}
  7488. (not (+ 10 (- (+ 12 20))))
  7489. \end{lstlisting}
  7490. \fi}
  7491. {\if\edition\pythonEd\pythonColor
  7492. \begin{lstlisting}
  7493. not (10 + -(12 + 20))
  7494. \end{lstlisting}
  7495. \fi}
  7496. \noindent The subexpression
  7497. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7498. \python{\code{(10 + -(12 + 20))}}
  7499. has type \INTTY{}, but the type checker enforces the rule that the
  7500. argument of \code{not} must be an expression of type \BOOLTY{}.
  7501. We implement type checking using classes and methods because they
  7502. provide the open recursion needed to reuse code as we extend the type
  7503. checker in subsequent chapters, analogous to the use of classes and methods
  7504. for the interpreters (section~\ref{sec:extensible-interp}).
  7505. We separate the type checker for the \LangVar{} subset into its own
  7506. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7507. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7508. from the type checker for \LangVar{}. These type checkers are in the
  7509. files
  7510. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7511. and
  7512. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7513. of the support code.
  7514. %
  7515. Each type checker is a structurally recursive function over the AST.
  7516. Given an input expression \code{e}, the type checker either signals an
  7517. error or returns \racket{an expression and its type.}\python{its type.}
  7518. %
  7519. \racket{It returns an expression because there are situations in which
  7520. we want to change or update the expression.}
  7521. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7522. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7523. constant is \INTTY{}. To handle variables, the type checker uses the
  7524. environment \code{env} to map variables to types.
  7525. %
  7526. \racket{Consider the case for \key{let}. We type check the
  7527. initializing expression to obtain its type \key{T} and then
  7528. associate type \code{T} with the variable \code{x} in the
  7529. environment used to type check the body of the \key{let}. Thus,
  7530. when the type checker encounters a use of variable \code{x}, it can
  7531. find its type in the environment.}
  7532. %
  7533. \python{Consider the case for assignment. We type check the
  7534. initializing expression to obtain its type \key{t}. If the variable
  7535. \code{id} is already in the environment because there was a
  7536. prior assignment, we check that this initializer has the same type
  7537. as the prior one. If this is the first assignment to the variable,
  7538. we associate type \code{t} with the variable \code{id} in the
  7539. environment. Thus, when the type checker encounters a use of
  7540. variable \code{x}, it can find its type in the environment.}
  7541. %
  7542. \racket{Regarding primitive operators, we recursively analyze the
  7543. arguments and then invoke \code{type\_check\_op} to check whether
  7544. the argument types are allowed.}
  7545. %
  7546. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7547. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7548. \racket{Several auxiliary methods are used in the type checker. The
  7549. method \code{operator-types} defines a dictionary that maps the
  7550. operator names to their parameter and return types. The
  7551. \code{type-equal?} method determines whether two types are equal,
  7552. which for now simply dispatches to \code{equal?} (deep
  7553. equality). The \code{check-type-equal?} method triggers an error if
  7554. the two types are not equal. The \code{type-check-op} method looks
  7555. up the operator in the \code{operator-types} dictionary and then
  7556. checks whether the argument types are equal to the parameter types.
  7557. The result is the return type of the operator.}
  7558. %
  7559. \python{The auxiliary method \code{check\_type\_equal} triggers
  7560. an error if the two types are not equal.}
  7561. \begin{figure}[tbp]
  7562. \begin{tcolorbox}[colback=white]
  7563. {\if\edition\racketEd
  7564. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7565. (define type-check-Lvar-class
  7566. (class object%
  7567. (super-new)
  7568. (define/public (operator-types)
  7569. '((+ . ((Integer Integer) . Integer))
  7570. (- . ((Integer Integer) . Integer))
  7571. (read . (() . Integer))))
  7572. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7573. (define/public (check-type-equal? t1 t2 e)
  7574. (unless (type-equal? t1 t2)
  7575. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7576. (define/public (type-check-op op arg-types e)
  7577. (match (dict-ref (operator-types) op)
  7578. [`(,param-types . ,return-type)
  7579. (for ([at arg-types] [pt param-types])
  7580. (check-type-equal? at pt e))
  7581. return-type]
  7582. [else (error 'type-check-op "unrecognized ~a" op)]))
  7583. (define/public (type-check-exp env)
  7584. (lambda (e)
  7585. (match e
  7586. [(Int n) (values (Int n) 'Integer)]
  7587. [(Var x) (values (Var x) (dict-ref env x))]
  7588. [(Let x e body)
  7589. (define-values (e^ Te) ((type-check-exp env) e))
  7590. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7591. (values (Let x e^ b) Tb)]
  7592. [(Prim op es)
  7593. (define-values (new-es ts)
  7594. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7595. (values (Prim op new-es) (type-check-op op ts e))]
  7596. [else (error 'type-check-exp "couldn't match" e)])))
  7597. (define/public (type-check-program e)
  7598. (match e
  7599. [(Program info body)
  7600. (define-values (body^ Tb) ((type-check-exp '()) body))
  7601. (check-type-equal? Tb 'Integer body)
  7602. (Program info body^)]
  7603. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7604. ))
  7605. (define (type-check-Lvar p)
  7606. (send (new type-check-Lvar-class) type-check-program p))
  7607. \end{lstlisting}
  7608. \fi}
  7609. {\if\edition\pythonEd\pythonColor
  7610. \begin{lstlisting}[escapechar=`]
  7611. class TypeCheckLvar:
  7612. def check_type_equal(self, t1, t2, e):
  7613. if t1 != t2:
  7614. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7615. raise Exception(msg)
  7616. def type_check_exp(self, e, env):
  7617. match e:
  7618. case BinOp(left, (Add() | Sub()), right):
  7619. l = self.type_check_exp(left, env)
  7620. check_type_equal(l, int, left)
  7621. r = self.type_check_exp(right, env)
  7622. check_type_equal(r, int, right)
  7623. return int
  7624. case UnaryOp(USub(), v):
  7625. t = self.type_check_exp(v, env)
  7626. check_type_equal(t, int, v)
  7627. return int
  7628. case Name(id):
  7629. return env[id]
  7630. case Constant(value) if isinstance(value, int):
  7631. return int
  7632. case Call(Name('input_int'), []):
  7633. return int
  7634. def type_check_stmts(self, ss, env):
  7635. if len(ss) == 0:
  7636. return
  7637. match ss[0]:
  7638. case Assign([Name(id)], value):
  7639. t = self.type_check_exp(value, env)
  7640. if id in env:
  7641. check_type_equal(env[id], t, value)
  7642. else:
  7643. env[id] = t
  7644. return self.type_check_stmts(ss[1:], env)
  7645. case Expr(Call(Name('print'), [arg])):
  7646. t = self.type_check_exp(arg, env)
  7647. check_type_equal(t, int, arg)
  7648. return self.type_check_stmts(ss[1:], env)
  7649. case Expr(value):
  7650. self.type_check_exp(value, env)
  7651. return self.type_check_stmts(ss[1:], env)
  7652. def type_check_P(self, p):
  7653. match p:
  7654. case Module(body):
  7655. self.type_check_stmts(body, {})
  7656. \end{lstlisting}
  7657. \fi}
  7658. \end{tcolorbox}
  7659. \caption{Type checker for the \LangVar{} language.}
  7660. \label{fig:type-check-Lvar}
  7661. \end{figure}
  7662. \begin{figure}[tbp]
  7663. \begin{tcolorbox}[colback=white]
  7664. {\if\edition\racketEd
  7665. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7666. (define type-check-Lif-class
  7667. (class type-check-Lvar-class
  7668. (super-new)
  7669. (inherit check-type-equal?)
  7670. (define/override (operator-types)
  7671. (append '((and . ((Boolean Boolean) . Boolean))
  7672. (or . ((Boolean Boolean) . Boolean))
  7673. (< . ((Integer Integer) . Boolean))
  7674. (<= . ((Integer Integer) . Boolean))
  7675. (> . ((Integer Integer) . Boolean))
  7676. (>= . ((Integer Integer) . Boolean))
  7677. (not . ((Boolean) . Boolean)))
  7678. (super operator-types)))
  7679. (define/override (type-check-exp env)
  7680. (lambda (e)
  7681. (match e
  7682. [(Bool b) (values (Bool b) 'Boolean)]
  7683. [(Prim 'eq? (list e1 e2))
  7684. (define-values (e1^ T1) ((type-check-exp env) e1))
  7685. (define-values (e2^ T2) ((type-check-exp env) e2))
  7686. (check-type-equal? T1 T2 e)
  7687. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7688. [(If cnd thn els)
  7689. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7690. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7691. (define-values (els^ Te) ((type-check-exp env) els))
  7692. (check-type-equal? Tc 'Boolean e)
  7693. (check-type-equal? Tt Te e)
  7694. (values (If cnd^ thn^ els^) Te)]
  7695. [else ((super type-check-exp env) e)])))
  7696. ))
  7697. (define (type-check-Lif p)
  7698. (send (new type-check-Lif-class) type-check-program p))
  7699. \end{lstlisting}
  7700. \fi}
  7701. {\if\edition\pythonEd\pythonColor
  7702. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7703. class TypeCheckLif(TypeCheckLvar):
  7704. def type_check_exp(self, e, env):
  7705. match e:
  7706. case Constant(value) if isinstance(value, bool):
  7707. return bool
  7708. case BinOp(left, Sub(), right):
  7709. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7710. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7711. return int
  7712. case UnaryOp(Not(), v):
  7713. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7714. return bool
  7715. case BoolOp(op, values):
  7716. left = values[0] ; right = values[1]
  7717. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7718. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7719. return bool
  7720. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7721. or isinstance(cmp, NotEq):
  7722. l = self.type_check_exp(left, env)
  7723. r = self.type_check_exp(right, env)
  7724. check_type_equal(l, r, e)
  7725. return bool
  7726. case Compare(left, [cmp], [right]):
  7727. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7728. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7729. return bool
  7730. case IfExp(test, body, orelse):
  7731. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7732. b = self.type_check_exp(body, env)
  7733. o = self.type_check_exp(orelse, env)
  7734. check_type_equal(b, o, e)
  7735. return b
  7736. case _:
  7737. return super().type_check_exp(e, env)
  7738. def type_check_stmts(self, ss, env):
  7739. if len(ss) == 0:
  7740. return
  7741. match ss[0]:
  7742. case If(test, body, orelse):
  7743. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7744. b = self.type_check_stmts(body, env)
  7745. o = self.type_check_stmts(orelse, env)
  7746. check_type_equal(b, o, ss[0])
  7747. return self.type_check_stmts(ss[1:], env)
  7748. case _:
  7749. return super().type_check_stmts(ss, env)
  7750. \end{lstlisting}
  7751. \fi}
  7752. \end{tcolorbox}
  7753. \caption{Type checker for the \LangIf{} language.}
  7754. \label{fig:type-check-Lif}
  7755. \end{figure}
  7756. The definition of the type checker for \LangIf{} is shown in
  7757. figure~\ref{fig:type-check-Lif}.
  7758. %
  7759. The type of a Boolean constant is \BOOLTY{}.
  7760. %
  7761. \racket{The \code{operator-types} function adds dictionary entries for
  7762. the new operators.}
  7763. %
  7764. \python{The logical \code{not} operator requires its argument to be a
  7765. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7766. and logical \code{or} operators.}
  7767. %
  7768. The equality operator requires the two arguments to have the same type,
  7769. and therefore we handle it separately from the other operators.
  7770. %
  7771. \python{The other comparisons (less-than, etc.) require their
  7772. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7773. %
  7774. The condition of an \code{if} must
  7775. be of \BOOLTY{} type, and the two branches must have the same type.
  7776. \begin{exercise}\normalfont\normalsize
  7777. Create ten new test programs in \LangIf{}. Half the programs should
  7778. have a type error.
  7779. \racket{For those programs, create an empty file with the
  7780. same base name and with file extension \code{.tyerr}. For example, if
  7781. the test \code{cond\_test\_14.rkt}
  7782. is expected to error, then create
  7783. an empty file named \code{cond\_test\_14.tyerr}.
  7784. This indicates to \code{interp-tests} and
  7785. \code{compiler-tests} that a type error is expected.}
  7786. %
  7787. The other half of the test programs should not have type errors.
  7788. %
  7789. \racket{In the \code{run-tests.rkt} script, change the second argument
  7790. of \code{interp-tests} and \code{compiler-tests} to
  7791. \code{type-check-Lif}, which causes the type checker to run prior to
  7792. the compiler passes. Temporarily change the \code{passes} to an
  7793. empty list and run the script, thereby checking that the new test
  7794. programs either type check or do not, as intended.}
  7795. %
  7796. Run the test script to check that these test programs type check as
  7797. expected.
  7798. \end{exercise}
  7799. \clearpage
  7800. \section{The \LangCIf{} Intermediate Language}
  7801. \label{sec:Cif}
  7802. {\if\edition\racketEd
  7803. %
  7804. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7805. comparison operators to the \Exp{} nonterminal and the literals
  7806. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7807. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7808. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7809. comparison operation and the branches are \code{goto} statements,
  7810. making it straightforward to compile \code{if} statements to x86. The
  7811. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7812. expressions. A \code{goto} statement transfers control to the $\Tail$
  7813. expression corresponding to its label.
  7814. %
  7815. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7816. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7817. defines its abstract syntax.
  7818. %
  7819. \fi}
  7820. %
  7821. {\if\edition\pythonEd\pythonColor
  7822. %
  7823. The output of \key{explicate\_control} is a language similar to the
  7824. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7825. \code{goto} statements, so we name it \LangCIf{}.
  7826. %
  7827. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7828. the arguments of operators are restricted to atomic expressions. The
  7829. \LangCIf{} language does not include \code{if} expressions, but it does
  7830. include a restricted form of \code{if} statement. The condition must be
  7831. a comparison, and the two branches may contain only \code{goto}
  7832. statements. These restrictions make it easier to translate \code{if}
  7833. statements to x86. The \LangCIf{} language also adds a \code{return}
  7834. statement to finish the program with a specified value.
  7835. %
  7836. The \key{CProgram} construct contains a dictionary mapping labels to
  7837. lists of statements that end with a \emph{tail} statement, which is
  7838. either a \code{return} statement, a \code{goto}, or an
  7839. \code{if} statement.
  7840. %
  7841. A \code{goto} transfers control to the sequence of statements
  7842. associated with its label.
  7843. %
  7844. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7845. and figure~\ref{fig:c1-syntax} shows its
  7846. abstract syntax.
  7847. %
  7848. \fi}
  7849. %
  7850. \newcommand{\CifGrammarRacket}{
  7851. \begin{array}{lcl}
  7852. \Atm &::=& \itm{bool} \\
  7853. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7854. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7855. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7856. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7857. \end{array}
  7858. }
  7859. \newcommand{\CifASTRacket}{
  7860. \begin{array}{lcl}
  7861. \Atm &::=& \BOOL{\itm{bool}} \\
  7862. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7863. \Exp &::= & \UNIOP{\key{\textquotesingle not}}{\Atm} \MID \BINOP{\key{\textquotesingle}\itm{cmp}}{\Atm}{\Atm} \\
  7864. \Tail &::= & \GOTO{\itm{label}} \\
  7865. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7866. \end{array}
  7867. }
  7868. \newcommand{\CifGrammarPython}{
  7869. \begin{array}{lcl}
  7870. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7871. \Exp &::= & \Atm \MID \CREAD{}
  7872. \MID \CUNIOP{\key{-}}{\Atm}
  7873. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7874. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7875. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7876. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7877. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7878. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7879. \end{array}
  7880. }
  7881. \newcommand{\CifASTPython}{
  7882. \begin{array}{lcl}
  7883. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7884. \Exp &::= & \Atm \MID \READ{}
  7885. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7886. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7887. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7888. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7889. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7890. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7891. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7892. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7893. \end{array}
  7894. }
  7895. \begin{figure}[tbp]
  7896. \begin{tcolorbox}[colback=white]
  7897. \small
  7898. {\if\edition\racketEd
  7899. \[
  7900. \begin{array}{l}
  7901. \gray{\CvarGrammarRacket} \\ \hline
  7902. \CifGrammarRacket \\
  7903. \begin{array}{lcl}
  7904. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7905. \end{array}
  7906. \end{array}
  7907. \]
  7908. \fi}
  7909. {\if\edition\pythonEd\pythonColor
  7910. \[
  7911. \begin{array}{l}
  7912. \CifGrammarPython \\
  7913. \begin{array}{lcl}
  7914. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7915. \end{array}
  7916. \end{array}
  7917. \]
  7918. \fi}
  7919. \end{tcolorbox}
  7920. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7921. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7922. \label{fig:c1-concrete-syntax}
  7923. \index{subject}{Cif@\LangCIf{} concrete syntax}
  7924. \end{figure}
  7925. \begin{figure}[tp]
  7926. \begin{tcolorbox}[colback=white]
  7927. \small
  7928. {\if\edition\racketEd
  7929. \[
  7930. \begin{array}{l}
  7931. \gray{\CvarASTRacket} \\ \hline
  7932. \CifASTRacket \\
  7933. \begin{array}{lcl}
  7934. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7935. \end{array}
  7936. \end{array}
  7937. \]
  7938. \fi}
  7939. {\if\edition\pythonEd\pythonColor
  7940. \[
  7941. \begin{array}{l}
  7942. \CifASTPython \\
  7943. \begin{array}{lcl}
  7944. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7945. \end{array}
  7946. \end{array}
  7947. \]
  7948. \fi}
  7949. \end{tcolorbox}
  7950. \racket{
  7951. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7952. }
  7953. \index{subject}{Goto@\texttt{Goto}}
  7954. \index{subject}{Return@\texttt{Return}}
  7955. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7956. (figure~\ref{fig:c0-syntax})}.}
  7957. \label{fig:c1-syntax}
  7958. \index{subject}{Cif@\LangCIf{} abstract syntax}
  7959. \end{figure}
  7960. \section{The \LangXIf{} Language}
  7961. \label{sec:x86-if}
  7962. \index{subject}{x86}
  7963. To implement Booleans, the new logical operations, the
  7964. comparison operations, and the \key{if} expression\python{ and
  7965. statement}, we delve further into the x86
  7966. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7967. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7968. subset of x86, which includes instructions for logical operations,
  7969. comparisons, and \racket{conditional} jumps.
  7970. %
  7971. \python{The abstract syntax for an \LangXIf{} program contains a
  7972. dictionary mapping labels to sequences of instructions, each of
  7973. which we refer to as a \emph{basic block}\index{subject}{basic
  7974. block}.}
  7975. As x86 does not provide direct support for Booleans, we take the usual
  7976. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7977. \code{False} as $0$.
  7978. Furthermore, x86 does not provide an instruction that directly
  7979. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7980. However, the \code{xorq} instruction can be used to encode \code{not}.
  7981. The \key{xorq} instruction takes two arguments, performs a pairwise
  7982. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7983. and writes the results into its second argument. Recall the following
  7984. truth table for exclusive-or:
  7985. \begin{center}
  7986. \begin{tabular}{l|cc}
  7987. & 0 & 1 \\ \hline
  7988. 0 & 0 & 1 \\
  7989. 1 & 1 & 0
  7990. \end{tabular}
  7991. \end{center}
  7992. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7993. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7994. for the bit $1$, the result is the opposite of the second bit. Thus,
  7995. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7996. the first argument, as follows, where $\Arg$ is the translation of
  7997. $\Atm$ to x86:
  7998. \[
  7999. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  8000. \qquad\Rightarrow\qquad
  8001. \begin{array}{l}
  8002. \key{movq}~ \Arg\key{,} \Var\\
  8003. \key{xorq}~ \key{\$1,} \Var
  8004. \end{array}
  8005. \]
  8006. \newcommand{\GrammarXIfRacket}{
  8007. \begin{array}{lcl}
  8008. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8009. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8010. \Arg &::=& \key{\%}\itm{bytereg}\\
  8011. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8012. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8013. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8014. \MID \key{set}cc~\Arg
  8015. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8016. &\MID& \key{j}cc~\itm{label} \\
  8017. \end{array}
  8018. }
  8019. \newcommand{\GrammarXIfPython}{
  8020. \begin{array}{lcl}
  8021. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8022. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8023. \Arg &::=& \key{\%}\itm{bytereg}\\
  8024. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8025. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  8026. \MID \key{cmpq}~\Arg\key{,}~\Arg
  8027. \MID \key{set}cc~\Arg
  8028. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  8029. &\MID& \key{jmp}\,\itm{label} \MID \key{j}cc~\itm{label}
  8030. \MID \itm{label}\key{:}\; \Instr
  8031. \end{array}
  8032. }
  8033. \begin{figure}[tp]
  8034. \begin{tcolorbox}[colback=white]
  8035. {\if\edition\racketEd
  8036. \[
  8037. \begin{array}{l}
  8038. \gray{\GrammarXIntRacket} \\ \hline
  8039. \GrammarXIfRacket \\
  8040. \begin{array}{lcl}
  8041. \LangXIfM{} &::= & \key{.globl main} \\
  8042. & & \key{main:} \; \Instr\ldots
  8043. \end{array}
  8044. \end{array}
  8045. \]
  8046. \fi}
  8047. {\if\edition\pythonEd
  8048. \[
  8049. \begin{array}{l}
  8050. \gray{\GrammarXIntPython} \\ \hline
  8051. \GrammarXIfPython \\
  8052. \begin{array}{lcl}
  8053. \LangXIfM{} &::= & \key{.globl main} \\
  8054. & & \key{main:} \; \Instr\ldots
  8055. \end{array}
  8056. \end{array}
  8057. \]
  8058. \fi}
  8059. \end{tcolorbox}
  8060. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  8061. \label{fig:x86-1-concrete}
  8062. \index{subject}{x86if@\LangXIf{} concrete syntax}
  8063. \end{figure}
  8064. \newcommand{\ASTXIfRacket}{
  8065. \begin{array}{lcl}
  8066. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  8067. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  8068. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  8069. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  8070. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  8071. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  8072. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  8073. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  8074. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8075. \end{array}
  8076. }
  8077. \newcommand{\ASTXIfPython}{
  8078. \begin{array}{lcl}
  8079. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  8080. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  8081. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  8082. \MID \BYTEREG{\itm{bytereg}} \\
  8083. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8084. \Instr &::=& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8085. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8086. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8087. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8088. &\MID& \python{\JMP{\itm{label}}} \MID \JMPIF{\itm{cc}}{\itm{label}}
  8089. \end{array}
  8090. }
  8091. \begin{figure}[tp]
  8092. \begin{tcolorbox}[colback=white]
  8093. \small
  8094. {\if\edition\racketEd
  8095. \[\arraycolsep=3pt
  8096. \begin{array}{l}
  8097. \gray{\ASTXIntRacket} \\ \hline
  8098. \ASTXIfRacket \\
  8099. \begin{array}{lcl}
  8100. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8101. \end{array}
  8102. \end{array}
  8103. \]
  8104. \fi}
  8105. %
  8106. {\if\edition\pythonEd\pythonColor
  8107. \[
  8108. \begin{array}{l}
  8109. \gray{\ASTXIntPython} \\ \hline
  8110. \ASTXIfPython \\
  8111. \begin{array}{lcl}
  8112. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8113. \end{array}
  8114. \end{array}
  8115. \]
  8116. \fi}
  8117. \end{tcolorbox}
  8118. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8119. \label{fig:x86-1}
  8120. \index{subject}{x86if@\LangXIf{} abstract syntax}
  8121. \end{figure}
  8122. Next we consider the x86 instructions that are relevant for compiling
  8123. the comparison operations. The \key{cmpq} instruction compares its two
  8124. arguments to determine whether one argument is less than, equal to, or
  8125. greater than the other argument. The \key{cmpq} instruction is unusual
  8126. regarding the order of its arguments and where the result is
  8127. placed. The argument order is backward: if you want to test whether
  8128. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8129. \key{cmpq} is placed in the special EFLAGS register. This register
  8130. cannot be accessed directly, but it can be queried by a number of
  8131. instructions, including the \key{set} instruction. The instruction
  8132. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8133. depending on whether the contents of the EFLAGS register matches the
  8134. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8135. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8136. The \key{set} instruction has a quirk in that its destination argument
  8137. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8138. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8139. register. Thankfully, the \key{movzbq} instruction can be used to
  8140. move from a single-byte register to a normal 64-bit register. The
  8141. abstract syntax for the \code{set} instruction differs from the
  8142. concrete syntax in that it separates the instruction name from the
  8143. condition code.
  8144. \python{The x86 instructions for jumping are relevant to the
  8145. compilation of \key{if} expressions.}
  8146. %
  8147. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8148. counter to the address of the instruction after the specified
  8149. label.}
  8150. %
  8151. \racket{The x86 instruction for conditional jump is relevant to the
  8152. compilation of \key{if} expressions.}
  8153. %
  8154. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8155. counter to point to the instruction after \itm{label}, depending on
  8156. whether the result in the EFLAGS register matches the condition code
  8157. \itm{cc}; otherwise, the jump instruction falls through to the next
  8158. instruction. Like the abstract syntax for \code{set}, the abstract
  8159. syntax for conditional jump separates the instruction name from the
  8160. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8161. corresponds to \code{jle foo}. Because the conditional jump instruction
  8162. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8163. a \key{cmpq} instruction to set the EFLAGS register.
  8164. \section{Shrink the \LangIf{} Language}
  8165. \label{sec:shrink-Lif}
  8166. The \code{shrink} pass translates some of the language features into
  8167. other features, thereby reducing the kinds of expressions in the
  8168. language. For example, the short-circuiting nature of the \code{and}
  8169. and \code{or} logical operators can be expressed using \code{if} as
  8170. follows.
  8171. \begin{align*}
  8172. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8173. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8174. \end{align*}
  8175. By performing these translations in the front end of the compiler,
  8176. subsequent passes of the compiler can be shorter.
  8177. On the other hand, translations sometimes reduce the efficiency of the
  8178. generated code by increasing the number of instructions. For example,
  8179. expressing subtraction in terms of addition and negation
  8180. \[
  8181. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8182. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8183. \]
  8184. produces code with two x86 instructions (\code{negq} and \code{addq})
  8185. instead of just one (\code{subq}). Thus, we do not recommend
  8186. translating subtraction into addition and negation.
  8187. \begin{exercise}\normalfont\normalsize
  8188. %
  8189. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8190. the language by translating them to \code{if} expressions in \LangIf{}.
  8191. %
  8192. Create four test programs that involve these operators.
  8193. %
  8194. {\if\edition\racketEd
  8195. In the \code{run-tests.rkt} script, add the following entry for
  8196. \code{shrink} to the list of passes (it should be the only pass at
  8197. this point).
  8198. \begin{lstlisting}
  8199. (list "shrink" shrink interp_Lif type-check-Lif)
  8200. \end{lstlisting}
  8201. This instructs \code{interp-tests} to run the interpreter
  8202. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8203. output of \code{shrink}.
  8204. \fi}
  8205. %
  8206. Run the script to test your compiler on all the test programs.
  8207. \end{exercise}
  8208. {\if\edition\racketEd
  8209. \section{Uniquify Variables}
  8210. \label{sec:uniquify-Lif}
  8211. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8212. \code{if} expressions.
  8213. \begin{exercise}\normalfont\normalsize
  8214. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8215. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8216. \begin{lstlisting}
  8217. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8218. \end{lstlisting}
  8219. Run the script to test your compiler.
  8220. \end{exercise}
  8221. \fi}
  8222. \section{Remove Complex Operands}
  8223. \label{sec:remove-complex-opera-Lif}
  8224. The output language of \code{remove\_complex\_operands} is
  8225. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8226. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8227. but the \code{if} expression is not. All three subexpressions of an
  8228. \code{if} are allowed to be complex expressions, but the operands of
  8229. the \code{not} operator and comparison operators must be atomic.
  8230. %
  8231. \python{We add a new language form, the \code{Begin} expression, to aid
  8232. in the translation of \code{if} expressions. When we recursively
  8233. process the two branches of the \code{if}, we generate temporary
  8234. variables and their initializing expressions. However, these
  8235. expressions may contain side effects and should be executed only
  8236. when the condition of the \code{if} is true (for the ``then''
  8237. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8238. provides a way to initialize the temporary variables within the two branches
  8239. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8240. form executes the statements $ss$ and then returns the result of
  8241. expression $e$.}
  8242. \racket{Add cases to the \code{rco\_exp} and \code{rco\_atom}
  8243. functions for the new features in \LangIf{}. In recursively
  8244. processing subexpressions, recall that you should invoke
  8245. \code{rco\_atom} when the output needs to be an \Atm{} (as specified
  8246. in the grammar for \LangIfANF{}) and invoke \code{rco\_exp} when the
  8247. output should be \Exp{}.}
  8248. %
  8249. \python{Add cases to the \code{rco\_exp} function for the new features
  8250. in \LangIf{}. In recursively processing subexpressions, recall that
  8251. you should invoke \code{rco\_exp} with the extra argument
  8252. \code{True} when the output needs to be an \Atm{} (as specified in
  8253. the grammar for \LangIfANF{}) and \code{False} when the output
  8254. should be \Exp{}.}
  8255. %
  8256. Regarding \code{if}, it is particularly important \emph{not} to
  8257. replace its condition with a temporary variable, because that would
  8258. interfere with the generation of high-quality output in the upcoming
  8259. \code{explicate\_control} pass.
  8260. \newcommand{\LifMonadASTRacket}{
  8261. \begin{array}{rcl}
  8262. \Atm &::=& \BOOL{\itm{bool}}\\
  8263. \Exp &::=& \UNIOP{\key{\textquotesingle not}}{\Atm}
  8264. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8265. \MID \IF{\Exp}{\Exp}{\Exp}
  8266. \end{array}
  8267. }
  8268. \newcommand{\LifMonadASTPython}{
  8269. \begin{array}{rcl}
  8270. \Atm &::=& \BOOL{\itm{bool}}\\
  8271. \Exp &::=& \UNIOP{\key{Not()}}{\Atm}
  8272. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8273. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8274. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8275. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8276. \end{array}
  8277. }
  8278. \begin{figure}[tp]
  8279. \centering
  8280. \begin{tcolorbox}[colback=white]
  8281. {\if\edition\racketEd
  8282. \[
  8283. \begin{array}{l}
  8284. \gray{\LvarMonadASTRacket} \\ \hline
  8285. \LifMonadASTRacket \\
  8286. \begin{array}{rcl}
  8287. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8288. \end{array}
  8289. \end{array}
  8290. \]
  8291. \fi}
  8292. {\if\edition\pythonEd\pythonColor
  8293. \[
  8294. \begin{array}{l}
  8295. \gray{\LvarMonadASTPython} \\ \hline
  8296. \LifMonadASTPython \\
  8297. \begin{array}{rcl}
  8298. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8299. \end{array}
  8300. \end{array}
  8301. \]
  8302. \fi}
  8303. \end{tcolorbox}
  8304. \python{\index{subject}{Begin@\texttt{Begin}}}
  8305. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8306. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8307. \label{fig:Lif-anf-syntax}
  8308. \index{subject}{Lifmon@\LangIfANF{} abstract syntax}
  8309. \end{figure}
  8310. \begin{exercise}\normalfont\normalsize
  8311. %
  8312. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8313. and \code{rco\_exp} functions.
  8314. %
  8315. Create three new \LangIf{} programs that exercise the interesting
  8316. code in this pass.
  8317. %
  8318. {\if\edition\racketEd
  8319. In the \code{run-tests.rkt} script, add the following entry to the
  8320. list of \code{passes} and then run the script to test your compiler.
  8321. \begin{lstlisting}
  8322. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8323. \end{lstlisting}
  8324. \fi}
  8325. \end{exercise}
  8326. \section{Explicate Control}
  8327. \label{sec:explicate-control-Lif}
  8328. \racket{Recall that the purpose of \code{explicate\_control} is to
  8329. make the order of evaluation explicit in the syntax of the program.
  8330. With the addition of \key{if}, this becomes more interesting.}
  8331. %
  8332. The \code{explicate\_control} pass translates from \LangIfANF{} to \LangCIf{}.
  8333. %
  8334. The main challenge to overcome is that the condition of an \key{if}
  8335. can be an arbitrary expression in \LangIfANF{}, whereas in \LangCIf{} the
  8336. condition must be a comparison.
  8337. As a motivating example, consider the following \LangIfANF{} program that has an
  8338. \key{if} expression nested in the condition of another \key{if}:%
  8339. \python{\footnote{Programmers rarely write nested \code{if}
  8340. expressions, but they do write nested expressions involving
  8341. logical \code{and}, which, as we have seen, translates to
  8342. \code{if}.}}
  8343. % cond_test_41.rkt, if_lt_eq.py
  8344. \begin{center}
  8345. \begin{minipage}{0.96\textwidth}
  8346. {\if\edition\racketEd
  8347. \begin{lstlisting}
  8348. (let ([x (read)])
  8349. (let ([y (read)])
  8350. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8351. (+ y 2)
  8352. (+ y 10))))
  8353. \end{lstlisting}
  8354. \fi}
  8355. {\if\edition\pythonEd\pythonColor
  8356. \begin{lstlisting}
  8357. x = input_int()
  8358. y = input_int()
  8359. tmp_0 = y + 2 if (x == 0 if x < 1 else x == 2) else y + 10
  8360. print(tmp_0)
  8361. \end{lstlisting}
  8362. \fi}
  8363. \end{minipage}
  8364. \end{center}
  8365. %
  8366. The naive way to compile \key{if} and the comparison operations would
  8367. be to handle each of them in isolation, regardless of their context.
  8368. Each comparison would be translated into a \key{cmpq} instruction
  8369. followed by several instructions to move the result from the EFLAGS
  8370. register into a general purpose register or stack location. Each
  8371. \key{if} would be translated into a \key{cmpq} instruction followed by
  8372. a conditional jump. The generated code for the inner \key{if} in this
  8373. example would be as follows:
  8374. \begin{center}
  8375. \begin{minipage}{0.96\textwidth}
  8376. \begin{lstlisting}
  8377. cmpq $1, x
  8378. setl %al
  8379. movzbq %al, tmp
  8380. cmpq $1, tmp
  8381. je then_branch_1
  8382. jmp else_branch_1
  8383. \end{lstlisting}
  8384. \end{minipage}
  8385. \end{center}
  8386. Notice that the three instructions starting with \code{setl} are
  8387. redundant; the conditional jump could come immediately after the first
  8388. \code{cmpq}.
  8389. Our goal is to compile \key{if} expressions so that the relevant
  8390. comparison instruction appears directly before the conditional jump.
  8391. For example, we want to generate the following code for the inner
  8392. \code{if}:
  8393. \begin{center}
  8394. \begin{minipage}{0.96\textwidth}
  8395. \begin{lstlisting}
  8396. cmpq $1, x
  8397. jl then_branch_1
  8398. jmp else_branch_1
  8399. \end{lstlisting}
  8400. \end{minipage}
  8401. \end{center}
  8402. One way to achieve this goal is to reorganize the code at the level of
  8403. \LangIfANF{}, pushing the outer \key{if} inside the inner one, yielding
  8404. the following code:
  8405. \begin{center}
  8406. \begin{minipage}{0.96\textwidth}
  8407. {\if\edition\racketEd
  8408. \begin{lstlisting}
  8409. (let ([x (read)])
  8410. (let ([y (read)])
  8411. (if (< x 1)
  8412. (if (eq? x 0)
  8413. (+ y 2)
  8414. (+ y 10))
  8415. (if (eq? x 2)
  8416. (+ y 2)
  8417. (+ y 10)))))
  8418. \end{lstlisting}
  8419. \fi}
  8420. {\if\edition\pythonEd\pythonColor
  8421. \begin{lstlisting}
  8422. x = input_int()
  8423. y = input_int()
  8424. tmp_0 = ((y + 2) if x == 0 else (y + 10)) \
  8425. if (x < 1) \
  8426. else ((y + 2) if (x == 2) else (y + 10))
  8427. print(tmp_0)
  8428. \end{lstlisting}
  8429. \fi}
  8430. \end{minipage}
  8431. \end{center}
  8432. Unfortunately, this approach duplicates the two branches from the
  8433. outer \code{if}, and a compiler must never duplicate code! After all,
  8434. the two branches could be very large expressions.
  8435. How can we apply this transformation without duplicating code? In
  8436. other words, how can two different parts of a program refer to one
  8437. piece of code?
  8438. %
  8439. The answer is that we must move away from abstract syntax \emph{trees}
  8440. and instead use \emph{graphs}.
  8441. %
  8442. At the level of x86 assembly, this is straightforward because we can
  8443. label the code for each branch and insert jumps in all the places that
  8444. need to execute the branch. In this way, jump instructions are edges
  8445. in the graph and the basic blocks are the nodes.
  8446. %
  8447. Likewise, our intermediate language \LangCIf{} provides the ability to
  8448. label a sequence of statements and to jump to a label via \code{goto}.
  8449. As a preview of what \code{explicate\_control} will do,
  8450. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8451. \code{explicate\_control} on this example. Note how the condition of
  8452. every \code{if} is a comparison operation and that we have not
  8453. duplicated any code but instead have used labels and \code{goto} to
  8454. enable sharing of code.
  8455. \begin{figure}[tbp]
  8456. \begin{tcolorbox}[colback=white]
  8457. {\if\edition\racketEd
  8458. \begin{tabular}{lll}
  8459. \begin{minipage}{0.4\textwidth}
  8460. % cond_test_41.rkt
  8461. \begin{lstlisting}
  8462. (let ([x (read)])
  8463. (let ([y (read)])
  8464. (if (if (< x 1)
  8465. (eq? x 0)
  8466. (eq? x 2))
  8467. (+ y 2)
  8468. (+ y 10))))
  8469. \end{lstlisting}
  8470. \end{minipage}
  8471. &
  8472. $\Rightarrow$
  8473. &
  8474. \begin{minipage}{0.55\textwidth}
  8475. \begin{lstlisting}
  8476. start:
  8477. x = (read);
  8478. y = (read);
  8479. if (< x 1)
  8480. goto block_4;
  8481. else
  8482. goto block_5;
  8483. block_4:
  8484. if (eq? x 0)
  8485. goto block_2;
  8486. else
  8487. goto block_3;
  8488. block_5:
  8489. if (eq? x 2)
  8490. goto block_2;
  8491. else
  8492. goto block_3;
  8493. block_2:
  8494. return (+ y 2);
  8495. block_3:
  8496. return (+ y 10);
  8497. \end{lstlisting}
  8498. \end{minipage}
  8499. \end{tabular}
  8500. \fi}
  8501. {\if\edition\pythonEd\pythonColor
  8502. \begin{tabular}{lll}
  8503. \begin{minipage}{0.4\textwidth}
  8504. % tests/if/if_lt_eq.py
  8505. \begin{lstlisting}
  8506. x = input_int()
  8507. y = input_int()
  8508. tmp_0 = y + 2 \
  8509. if (x == 0 \
  8510. if x < 1 \
  8511. else x == 2) \
  8512. else y + 10
  8513. print(tmp_0)
  8514. \end{lstlisting}
  8515. \end{minipage}
  8516. &
  8517. $\Rightarrow\qquad$
  8518. &
  8519. \begin{minipage}{0.55\textwidth}
  8520. \begin{lstlisting}
  8521. start:
  8522. x = input_int()
  8523. y = input_int()
  8524. if x < 1:
  8525. goto block_6
  8526. else:
  8527. goto block_7
  8528. block_6:
  8529. if x == 0:
  8530. goto block_4
  8531. else:
  8532. goto block_5
  8533. block_7:
  8534. if x == 2:
  8535. goto block_4
  8536. else:
  8537. goto block_5
  8538. block_4:
  8539. tmp_0 = (y + 2)
  8540. goto block_3
  8541. block_5:
  8542. tmp_0 = (y + 10)
  8543. goto block_3
  8544. block_3:
  8545. print(tmp_0)
  8546. return 0
  8547. \end{lstlisting}
  8548. \end{minipage}
  8549. \end{tabular}
  8550. \fi}
  8551. \end{tcolorbox}
  8552. \caption{Translation from \LangIfANF{} to \LangCIf{}
  8553. via the \code{explicate\_control}.}
  8554. \label{fig:explicate-control-s1-38}
  8555. \end{figure}
  8556. {\if\edition\racketEd
  8557. %
  8558. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8559. \code{explicate\_control} for \LangVarANF{} using two recursive
  8560. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8561. former function translates expressions in tail position, whereas the
  8562. latter function translates expressions on the right-hand side of a
  8563. \key{let}. With the addition of \key{if} expression to \LangIfANF{} we
  8564. have a new kind of position to deal with: the predicate position of
  8565. the \key{if}. We need another function, \code{explicate\_pred}, that
  8566. decides how to compile an \key{if} by analyzing its condition. So,
  8567. \code{explicate\_pred} takes an \LangIfANF{} expression and two
  8568. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8569. and outputs a tail. In the following paragraphs we discuss specific
  8570. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8571. \code{explicate\_pred} functions.
  8572. %
  8573. \fi}
  8574. %
  8575. {\if\edition\pythonEd\pythonColor
  8576. %
  8577. We recommend implementing \code{explicate\_control} using the
  8578. following four auxiliary functions.
  8579. \begin{description}
  8580. \item[\code{explicate\_effect}] generates code for expressions as
  8581. statements, so their result is ignored and only their side effects
  8582. matter.
  8583. \item[\code{explicate\_assign}] generates code for expressions
  8584. on the right-hand side of an assignment.
  8585. \item[\code{explicate\_pred}] generates code for an \code{if}
  8586. expression or statement by analyzing the condition expression.
  8587. \item[\code{explicate\_stmt}] generates code for statements.
  8588. \end{description}
  8589. These four functions should build the dictionary of basic blocks. The
  8590. following auxiliary function \code{create\_block} is used to create a
  8591. new basic block from a list of statements. If the list just contains a
  8592. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8593. \code{create\_block} creates a new basic block and returns a
  8594. \code{goto} to its label.
  8595. \begin{center}
  8596. \begin{minipage}{\textwidth}
  8597. \begin{lstlisting}
  8598. def create_block(stmts, basic_blocks):
  8599. match stmts:
  8600. case [Goto(l)]:
  8601. return stmts
  8602. case _:
  8603. label = label_name(generate_name('block'))
  8604. basic_blocks[label] = stmts
  8605. return [Goto(label)]
  8606. \end{lstlisting}
  8607. \end{minipage}
  8608. \end{center}
  8609. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8610. \code{explicate\_control} pass.
  8611. The \code{explicate\_effect} function has three parameters: (1) the
  8612. expression to be compiled; (2) the already-compiled code for this
  8613. expression's \emph{continuation}, that is, the list of statements that
  8614. should execute after this expression; and (3) the dictionary of
  8615. generated basic blocks. The \code{explicate\_effect} function returns
  8616. a list of \LangCIf{} statements and it may add to the dictionary of
  8617. basic blocks.
  8618. %
  8619. Let's consider a few of the cases for the expression to be compiled.
  8620. If the expression to be compiled is a constant, then it can be
  8621. discarded because it has no side effects. If it's a \CREAD{}, then it
  8622. has a side effect and should be preserved. So the expression should be
  8623. translated into a statement using the \code{Expr} AST class. If the
  8624. expression to be compiled is an \code{if} expression, we translate the
  8625. two branches using \code{explicate\_effect} and then translate the
  8626. condition expression using \code{explicate\_pred}, which generates
  8627. code for the entire \code{if}.
  8628. The \code{explicate\_assign} function has four parameters: (1) the
  8629. right-hand side of the assignment, (2) the left-hand side of the
  8630. assignment (the variable), (3) the continuation, and (4) the dictionary
  8631. of basic blocks. The \code{explicate\_assign} function returns a list
  8632. of \LangCIf{} statements, and it may add to the dictionary of basic
  8633. blocks.
  8634. When the right-hand side is an \code{if} expression, there is some
  8635. work to do. In particular, the two branches should be translated using
  8636. \code{explicate\_assign}, and the condition expression should be
  8637. translated using \code{explicate\_pred}. Otherwise we can simply
  8638. generate an assignment statement, with the given left- and right-hand
  8639. sides, concatenated with its continuation.
  8640. \begin{figure}[tbp]
  8641. \begin{tcolorbox}[colback=white]
  8642. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8643. def explicate_effect(e, cont, basic_blocks):
  8644. match e:
  8645. case IfExp(test, body, orelse):
  8646. ...
  8647. case Call(func, args):
  8648. ...
  8649. case Begin(body, result):
  8650. ...
  8651. case _:
  8652. ...
  8653. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8654. match rhs:
  8655. case IfExp(test, body, orelse):
  8656. ...
  8657. case Begin(body, result):
  8658. ...
  8659. case _:
  8660. return [Assign([lhs], rhs)] + cont
  8661. def explicate_pred(cnd, thn, els, basic_blocks):
  8662. match cnd:
  8663. case Compare(left, [op], [right]):
  8664. goto_thn = create_block(thn, basic_blocks)
  8665. goto_els = create_block(els, basic_blocks)
  8666. return [If(cnd, goto_thn, goto_els)]
  8667. case Constant(True):
  8668. return thn;
  8669. case Constant(False):
  8670. return els;
  8671. case UnaryOp(Not(), operand):
  8672. ...
  8673. case IfExp(test, body, orelse):
  8674. ...
  8675. case Begin(body, result):
  8676. ...
  8677. case _:
  8678. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8679. create_block(els, basic_blocks),
  8680. create_block(thn, basic_blocks))]
  8681. def explicate_stmt(s, cont, basic_blocks):
  8682. match s:
  8683. case Assign([lhs], rhs):
  8684. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8685. case Expr(value):
  8686. return explicate_effect(value, cont, basic_blocks)
  8687. case If(test, body, orelse):
  8688. ...
  8689. def explicate_control(p):
  8690. match p:
  8691. case Module(body):
  8692. new_body = [Return(Constant(0))]
  8693. basic_blocks = {}
  8694. for s in reversed(body):
  8695. new_body = explicate_stmt(s, new_body, basic_blocks)
  8696. basic_blocks[label_name('start')] = new_body
  8697. return CProgram(basic_blocks)
  8698. \end{lstlisting}
  8699. \end{tcolorbox}
  8700. \caption{Skeleton for the \code{explicate\_control} pass.}
  8701. \label{fig:explicate-control-Lif}
  8702. \end{figure}
  8703. \fi}
  8704. {\if\edition\racketEd
  8705. \subsection{Explicate Tail and Assign}
  8706. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8707. additional cases for Boolean constants and \key{if}. The cases for
  8708. \code{if} should recursively compile the two branches using either
  8709. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8710. cases should then invoke \code{explicate\_pred} on the condition
  8711. expression, passing in the generated code for the two branches. For
  8712. example, consider the following program with an \code{if} in tail
  8713. position.
  8714. % cond_test_6.rkt
  8715. \begin{lstlisting}
  8716. (let ([x (read)])
  8717. (if (eq? x 0) 42 777))
  8718. \end{lstlisting}
  8719. The two branches are recursively compiled to return statements. We
  8720. then delegate to \code{explicate\_pred}, passing the condition
  8721. \code{(eq? x 0)} and the two return statements. We return to this
  8722. example shortly when we discuss \code{explicate\_pred}.
  8723. Next let us consider a program with an \code{if} on the right-hand
  8724. side of a \code{let}.
  8725. \begin{lstlisting}
  8726. (let ([y (read)])
  8727. (let ([x (if (eq? y 0) 40 777)])
  8728. (+ x 2)))
  8729. \end{lstlisting}
  8730. Note that the body of the inner \code{let} will have already been
  8731. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8732. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8733. to recursively process both branches of the \code{if}, and we do not
  8734. want to duplicate code, so we generate the following block using an
  8735. auxiliary function named \code{create\_block}, discussed in the next
  8736. section.
  8737. \begin{lstlisting}
  8738. block_6:
  8739. return (+ x 2)
  8740. \end{lstlisting}
  8741. We then use \code{goto block\_6;} as the \code{cont} argument for
  8742. compiling the branches. So the two branches compile to
  8743. \begin{center}
  8744. \begin{minipage}{0.2\textwidth}
  8745. \begin{lstlisting}
  8746. x = 40;
  8747. goto block_6;
  8748. \end{lstlisting}
  8749. \end{minipage}
  8750. \hspace{0.5in} and \hspace{0.5in}
  8751. \begin{minipage}{0.2\textwidth}
  8752. \begin{lstlisting}
  8753. x = 777;
  8754. goto block_6;
  8755. \end{lstlisting}
  8756. \end{minipage}
  8757. \end{center}
  8758. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8759. \code{(eq? y 0)} and the previously presented code for the branches.
  8760. \subsection{Create Block}
  8761. We recommend implementing the \code{create\_block} auxiliary function
  8762. as follows, using a global variable \code{basic-blocks} to store a
  8763. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8764. that \code{create\_block} generates a new label and then associates
  8765. the given \code{tail} with the new label in the \code{basic-blocks}
  8766. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8767. new label. However, if the given \code{tail} is already a \code{Goto},
  8768. then there is no need to generate a new label and entry in
  8769. \code{basic-blocks}; we can simply return that \code{Goto}.
  8770. %
  8771. \begin{lstlisting}
  8772. (define (create_block tail)
  8773. (match tail
  8774. [(Goto label) (Goto label)]
  8775. [else
  8776. (let ([label (gensym 'block)])
  8777. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8778. (Goto label))]))
  8779. \end{lstlisting}
  8780. \fi}
  8781. {\if\edition\racketEd
  8782. \subsection{Explicate Predicate}
  8783. The skeleton for the \code{explicate\_pred} function is given in
  8784. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8785. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8786. the code generated by explicate for the \emph{then} branch; and (3)
  8787. \code{els}, the code generated by explicate for the \emph{else}
  8788. branch. The \code{explicate\_pred} function should match on
  8789. \code{cnd} with a case for every kind of expression that can have type
  8790. \BOOLTY{}.
  8791. \begin{figure}[tbp]
  8792. \begin{tcolorbox}[colback=white]
  8793. \begin{lstlisting}
  8794. (define (explicate_pred cnd thn els)
  8795. (match cnd
  8796. [(Var x) ___]
  8797. [(Let x rhs body) ___]
  8798. [(Prim 'not (list e)) ___]
  8799. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8800. (IfStmt (Prim op es) (create_block thn)
  8801. (create_block els))]
  8802. [(Bool b) (if b thn els)]
  8803. [(If cnd^ thn^ els^) ___]
  8804. [else (error "explicate_pred unhandled case" cnd)]))
  8805. \end{lstlisting}
  8806. \end{tcolorbox}
  8807. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8808. \label{fig:explicate-pred}
  8809. \end{figure}
  8810. \fi}
  8811. %
  8812. {\if\edition\pythonEd\pythonColor
  8813. The \code{explicate\_pred} function has four parameters: (1) the
  8814. condition expression, (2) the generated statements for the \emph{then}
  8815. branch, (3) the generated statements for the \emph{else} branch, and
  8816. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8817. function returns a list of statements, and it adds to the dictionary
  8818. of basic blocks.
  8819. \fi}
  8820. Consider the case for comparison operators. We translate the
  8821. comparison to an \code{if} statement whose branches are \code{goto}
  8822. statements created by applying \code{create\_block} to the \code{thn}
  8823. and \code{els} parameters. Let us illustrate this translation by
  8824. returning to the program with an \code{if} expression in tail
  8825. position, shown next. We invoke \code{explicate\_pred} on its
  8826. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8827. %
  8828. {\if\edition\racketEd
  8829. \begin{lstlisting}
  8830. (let ([x (read)])
  8831. (if (eq? x 0) 42 777))
  8832. \end{lstlisting}
  8833. \fi}
  8834. %
  8835. {\if\edition\pythonEd\pythonColor
  8836. \begin{lstlisting}
  8837. x = input_int()
  8838. 42 if x == 0 else 777
  8839. \end{lstlisting}
  8840. \fi}
  8841. %
  8842. \noindent The two branches \code{42} and \code{777} were already
  8843. compiled to \code{return} statements, from which we now create the
  8844. following blocks:
  8845. %
  8846. \begin{center}
  8847. \begin{minipage}{\textwidth}
  8848. \begin{lstlisting}
  8849. block_1:
  8850. return 42;
  8851. block_2:
  8852. return 777;
  8853. \end{lstlisting}
  8854. \end{minipage}
  8855. \end{center}
  8856. %
  8857. After that, \code{explicate\_pred} compiles the comparison
  8858. \racket{\code{(eq? x 0)}}
  8859. \python{\code{x == 0}}
  8860. to the following \code{if} statement:
  8861. %
  8862. {\if\edition\racketEd
  8863. \begin{center}
  8864. \begin{minipage}{\textwidth}
  8865. \begin{lstlisting}
  8866. if (eq? x 0)
  8867. goto block_1;
  8868. else
  8869. goto block_2;
  8870. \end{lstlisting}
  8871. \end{minipage}
  8872. \end{center}
  8873. \fi}
  8874. {\if\edition\pythonEd\pythonColor
  8875. \begin{center}
  8876. \begin{minipage}{\textwidth}
  8877. \begin{lstlisting}
  8878. if x == 0:
  8879. goto block_1;
  8880. else
  8881. goto block_2;
  8882. \end{lstlisting}
  8883. \end{minipage}
  8884. \end{center}
  8885. \fi}
  8886. Next consider the case for Boolean constants. We perform a kind of
  8887. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8888. either the \code{thn} or \code{els} parameter, depending on whether the
  8889. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8890. following program:
  8891. {\if\edition\racketEd
  8892. \begin{lstlisting}
  8893. (if #t 42 777)
  8894. \end{lstlisting}
  8895. \fi}
  8896. {\if\edition\pythonEd\pythonColor
  8897. \begin{lstlisting}
  8898. 42 if True else 777
  8899. \end{lstlisting}
  8900. \fi}
  8901. %
  8902. \noindent Again, the two branches \code{42} and \code{777} were
  8903. compiled to \code{return} statements, so \code{explicate\_pred}
  8904. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8905. code for the \emph{then} branch.
  8906. \begin{lstlisting}
  8907. return 42;
  8908. \end{lstlisting}
  8909. This case demonstrates that we sometimes discard the \code{thn} or
  8910. \code{els} blocks that are input to \code{explicate\_pred}.
  8911. The case for \key{if} expressions in \code{explicate\_pred} is
  8912. particularly illuminating because it deals with the challenges
  8913. discussed previously regarding nested \key{if} expressions
  8914. (figure~\ref{fig:explicate-control-s1-38}). The
  8915. \racket{\lstinline{thn^}}\python{\code{body}} and
  8916. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8917. \key{if} inherit their context from the current one, that is,
  8918. predicate context. So, you should recursively apply
  8919. \code{explicate\_pred} to the
  8920. \racket{\lstinline{thn^}}\python{\code{body}} and
  8921. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8922. those recursive calls, pass \code{thn} and \code{els} as the extra
  8923. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8924. inside each recursive call. As discussed previously, to avoid
  8925. duplicating code, we need to add them to the dictionary of basic
  8926. blocks so that we can instead refer to them by name and execute them
  8927. with a \key{goto}.
  8928. {\if\edition\pythonEd\pythonColor
  8929. %
  8930. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8931. three parameters: (1) the statement to be compiled, (2) the code for its
  8932. continuation, and (3) the dictionary of basic blocks. The
  8933. \code{explicate\_stmt} returns a list of statements, and it may add to
  8934. the dictionary of basic blocks. The cases for assignment and an
  8935. expression-statement are given in full in the skeleton code: they
  8936. simply dispatch to \code{explicate\_assign} and
  8937. \code{explicate\_effect}, respectively. The case for \code{if}
  8938. statements is not given; it is similar to the case for \code{if}
  8939. expressions.
  8940. The \code{explicate\_control} function itself is given in
  8941. figure~\ref{fig:explicate-control-Lif}. It applies
  8942. \code{explicate\_stmt} to each statement in the program, from back to
  8943. front. Thus, the result so far, stored in \code{new\_body}, can be
  8944. used as the continuation parameter in the next call to
  8945. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8946. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8947. the dictionary of basic blocks, labeling it the ``start'' block.
  8948. %
  8949. \fi}
  8950. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8951. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8952. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8953. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8954. %% results from the two recursive calls. We complete the case for
  8955. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8956. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8957. %% the result $B_5$.
  8958. %% \[
  8959. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8960. %% \quad\Rightarrow\quad
  8961. %% B_5
  8962. %% \]
  8963. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8964. %% inherit the current context, so they are in tail position. Thus, the
  8965. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8966. %% \code{explicate\_tail}.
  8967. %% %
  8968. %% We need to pass $B_0$ as the accumulator argument for both of these
  8969. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8970. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8971. %% to the control-flow graph and obtain a promised goto $G_0$.
  8972. %% %
  8973. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8974. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8975. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8976. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8977. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8978. %% \[
  8979. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8980. %% \]
  8981. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8982. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8983. %% should not be confused with the labels for the blocks that appear in
  8984. %% the generated code. We initially construct unlabeled blocks; we only
  8985. %% attach labels to blocks when we add them to the control-flow graph, as
  8986. %% we see in the next case.
  8987. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8988. %% function. The context of the \key{if} is an assignment to some
  8989. %% variable $x$ and then the control continues to some promised block
  8990. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8991. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8992. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8993. %% branches of the \key{if} inherit the current context, so they are in
  8994. %% assignment positions. Let $B_2$ be the result of applying
  8995. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8996. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8997. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8998. %% the result of applying \code{explicate\_pred} to the predicate
  8999. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  9000. %% translates to the promise $B_4$.
  9001. %% \[
  9002. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  9003. %% \]
  9004. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  9005. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  9006. \code{remove\_complex\_operands} pass and then the
  9007. \code{explicate\_control} pass on the example program. We walk through
  9008. the output program.
  9009. %
  9010. Following the order of evaluation in the output of
  9011. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  9012. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  9013. in the predicate of the inner \key{if}. In the output of
  9014. \code{explicate\_control}, in the
  9015. block labeled \code{start}, two assignment statements are followed by an
  9016. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  9017. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  9018. The blocks associated with those labels contain the
  9019. translations of the code
  9020. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9021. and
  9022. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  9023. respectively. In particular, we start
  9024. \racket{\code{block\_4}}\python{\code{block\_6}}
  9025. with the comparison
  9026. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  9027. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  9028. or \racket{\code{block\_3}}\python{\code{block\_5}},
  9029. which correspond to the two branches of the outer \key{if}, that is,
  9030. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  9031. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  9032. %
  9033. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  9034. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  9035. %
  9036. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  9037. {\if\edition\racketEd
  9038. \subsection{Interactions between Explicate and Shrink}
  9039. The way in which the \code{shrink} pass transforms logical operations
  9040. such as \code{and} and \code{or} can impact the quality of code
  9041. generated by \code{explicate\_control}. For example, consider the
  9042. following program:
  9043. % cond_test_21.rkt, and_eq_input.py
  9044. \begin{lstlisting}
  9045. (if (and (eq? (read) 0) (eq? (read) 1))
  9046. 0
  9047. 42)
  9048. \end{lstlisting}
  9049. The \code{and} operation should transform into something that the
  9050. \code{explicate\_pred} function can analyze and descend through to
  9051. reach the underlying \code{eq?} conditions. Ideally, for this program
  9052. your \code{explicate\_control} pass should generate code similar to
  9053. the following:
  9054. \begin{center}
  9055. \begin{minipage}{\textwidth}
  9056. \begin{lstlisting}
  9057. start:
  9058. tmp1 = (read);
  9059. if (eq? tmp1 0) goto block40;
  9060. else goto block39;
  9061. block40:
  9062. tmp2 = (read);
  9063. if (eq? tmp2 1) goto block38;
  9064. else goto block39;
  9065. block38:
  9066. return 0;
  9067. block39:
  9068. return 42;
  9069. \end{lstlisting}
  9070. \end{minipage}
  9071. \end{center}
  9072. \fi}
  9073. \begin{exercise}\normalfont\normalsize
  9074. \racket{
  9075. Implement the pass \code{explicate\_control} by adding the cases for
  9076. Boolean constants and \key{if} to the \code{explicate\_tail} and
  9077. \code{explicate\_assign} functions. Implement the auxiliary function
  9078. \code{explicate\_pred} for predicate contexts.}
  9079. \python{Implement \code{explicate\_control} pass with its
  9080. four auxiliary functions.}
  9081. %
  9082. Create test cases that exercise all the new cases in the code for
  9083. this pass.
  9084. %
  9085. {\if\edition\racketEd
  9086. Add the following entry to the list of \code{passes} in
  9087. \code{run-tests.rkt}:
  9088. \begin{lstlisting}
  9089. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  9090. \end{lstlisting}
  9091. and then run \code{run-tests.rkt} to test your compiler.
  9092. \fi}
  9093. \end{exercise}
  9094. \section{Select Instructions}
  9095. \label{sec:select-Lif}
  9096. \index{subject}{select instructions}
  9097. The \code{select\_instructions} pass translates \LangCIf{} to
  9098. \LangXIfVar{}.
  9099. %
  9100. \racket{Recall that we implement this pass using three auxiliary
  9101. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9102. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9103. %
  9104. \racket{For $\Atm$, we have new cases for the Booleans.}
  9105. %
  9106. \python{We begin with the Boolean constants.}
  9107. As previously discussed, we encode them as integers.
  9108. \[
  9109. \TRUE{} \quad\Rightarrow\quad \key{1}
  9110. \qquad\qquad
  9111. \FALSE{} \quad\Rightarrow\quad \key{0}
  9112. \]
  9113. For translating statements, we discuss some of the cases. The
  9114. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9115. discussed at the beginning of this section. Given an assignment, if
  9116. the left-hand-side variable is the same as the argument of \code{not},
  9117. then just the \code{xorq} instruction suffices.
  9118. \[
  9119. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9120. \quad\Rightarrow\quad
  9121. \key{xorq}~\key{\$}1\key{,}~\Var
  9122. \]
  9123. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9124. semantics of x86. In the following translation, let $\Arg$ be the
  9125. result of translating $\Atm$ to x86.
  9126. \[
  9127. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9128. \quad\Rightarrow\quad
  9129. \begin{array}{l}
  9130. \key{movq}~\Arg\key{,}~\Var\\
  9131. \key{xorq}~\key{\$}1\key{,}~\Var
  9132. \end{array}
  9133. \]
  9134. Next consider the cases for equality comparisons. Translating this
  9135. operation to x86 is slightly involved due to the unusual nature of the
  9136. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9137. We recommend translating an assignment with an equality on the
  9138. right-hand side into a sequence of three instructions. Let $\Arg_1$
  9139. be the translation of $\Atm_1$ to x86 and likewise for $\Arg_2$.\\
  9140. \begin{tabular}{lll}
  9141. \begin{minipage}{0.4\textwidth}
  9142. $\CASSIGN{\Var}{ \CEQ{\Atm_1}{\Atm_2} }$
  9143. \end{minipage}
  9144. &
  9145. $\Rightarrow$
  9146. &
  9147. \begin{minipage}{0.4\textwidth}
  9148. \begin{lstlisting}
  9149. cmpq |$\Arg_2$|, |$\Arg_1$|
  9150. sete %al
  9151. movzbq %al, |$\Var$|
  9152. \end{lstlisting}
  9153. \end{minipage}
  9154. \end{tabular} \\
  9155. The translations for the other comparison operators are similar to
  9156. this but use different condition codes for the \code{set} instruction.
  9157. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9158. \key{goto} and \key{if} statements. Both are straightforward to
  9159. translate to x86.}
  9160. %
  9161. A \key{goto} statement becomes a jump instruction.
  9162. \[
  9163. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9164. \]
  9165. %
  9166. An \key{if} statement becomes a compare instruction followed by a
  9167. conditional jump (for the \emph{then} branch), and the fall-through is to
  9168. a regular jump (for the \emph{else} branch). Again, $\Arg_1$ and $\Arg_2$
  9169. are the translations of $\Atm_1$ and $\Atm_2$, respectively.\\
  9170. \begin{tabular}{lll}
  9171. \begin{minipage}{0.4\textwidth}
  9172. \begin{lstlisting}
  9173. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9174. goto |$\ell_1$||$\racket{\key{;}}$|
  9175. else|$\python{\key{:}}$|
  9176. goto |$\ell_2$||$\racket{\key{;}}$|
  9177. \end{lstlisting}
  9178. \end{minipage}
  9179. &
  9180. $\Rightarrow$
  9181. &
  9182. \begin{minipage}{0.4\textwidth}
  9183. \begin{lstlisting}
  9184. cmpq |$\Arg_2$|, |$\Arg_1$|
  9185. je |$\ell_1$|
  9186. jmp |$\ell_2$|
  9187. \end{lstlisting}
  9188. \end{minipage}
  9189. \end{tabular} \\
  9190. Again, the translations for the other comparison operators are similar to this
  9191. but use different condition codes for the conditional jump instruction.
  9192. \python{Regarding the \key{return} statement, we recommend treating it
  9193. as an assignment to the \key{rax} register followed by a jump to the
  9194. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9195. \begin{exercise}\normalfont\normalsize
  9196. Expand your \code{select\_instructions} pass to handle the new
  9197. features of the \LangCIf{} language.
  9198. %
  9199. {\if\edition\racketEd
  9200. Add the following entry to the list of \code{passes} in
  9201. \code{run-tests.rkt}
  9202. \begin{lstlisting}
  9203. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9204. \end{lstlisting}
  9205. \fi}
  9206. %
  9207. Run the script to test your compiler on all the test programs.
  9208. \end{exercise}
  9209. \section{Register Allocation}
  9210. \label{sec:register-allocation-Lif}
  9211. \index{subject}{register allocation}
  9212. The changes required for compiling \LangIf{} affect liveness analysis,
  9213. building the interference graph, and assigning homes, but the graph
  9214. coloring algorithm itself does not change.
  9215. \subsection{Liveness Analysis}
  9216. \label{sec:liveness-analysis-Lif}
  9217. \index{subject}{liveness analysis}
  9218. Recall that for \LangVar{} we implemented liveness analysis for a
  9219. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9220. the addition of \key{if} expressions to \LangIf{},
  9221. \code{explicate\_control} produces many basic blocks.
  9222. %% We recommend that you create a new auxiliary function named
  9223. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9224. %% control-flow graph.
  9225. The first question is, in what order should we process the basic blocks?
  9226. Recall that to perform liveness analysis on a basic block we need to
  9227. know the live-after set for the last instruction in the block. If a
  9228. basic block has no successors (i.e., contains no jumps to other
  9229. blocks), then it has an empty live-after set and we can immediately
  9230. apply liveness analysis to it. If a basic block has some successors,
  9231. then we need to complete liveness analysis on those blocks
  9232. first. These ordering constraints are the reverse of a
  9233. \emph{topological order}\index{subject}{topological order} on a graph
  9234. representation of the program. In particular, the \emph{control flow
  9235. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9236. of a program has a node for each basic block and an edge for each jump
  9237. from one block to another. It is straightforward to generate a CFG
  9238. from the dictionary of basic blocks. One then transposes the CFG and
  9239. applies the topological sort algorithm.
  9240. %
  9241. %
  9242. \racket{We recommend using the \code{tsort} and \code{transpose}
  9243. functions of the Racket \code{graph} package to accomplish this.}
  9244. %
  9245. \python{We provide implementations of \code{topological\_sort} and
  9246. \code{transpose} in the file \code{graph.py} of the support code.}
  9247. %
  9248. As an aside, a topological ordering is only guaranteed to exist if the
  9249. graph does not contain any cycles. This is the case for the
  9250. control-flow graphs that we generate from \LangIf{} programs.
  9251. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9252. and learn how to handle cycles in the control-flow graph.
  9253. \racket{You need to construct a directed graph to represent the
  9254. control-flow graph. Do not use the \code{directed-graph} of the
  9255. \code{graph} package because that allows at most one edge
  9256. between each pair of vertices, whereas a control-flow graph may have
  9257. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9258. file in the support code implements a graph representation that
  9259. allows multiple edges between a pair of vertices.}
  9260. {\if\edition\racketEd
  9261. The next question is how to analyze jump instructions. Recall that in
  9262. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9263. \code{label->live} that maps each label to the set of live locations
  9264. at the beginning of its block. We use \code{label->live} to determine
  9265. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9266. that we have many basic blocks, \code{label->live} needs to be updated
  9267. as we process the blocks. In particular, after performing liveness
  9268. analysis on a block, we take the live-before set of its first
  9269. instruction and associate that with the block's label in the
  9270. \code{label->live} alist.
  9271. \fi}
  9272. %
  9273. {\if\edition\pythonEd\pythonColor
  9274. %
  9275. The next question is how to analyze jump instructions. The locations
  9276. that are live before a \code{jmp} should be the locations in
  9277. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9278. maintaining a dictionary named \code{live\_before\_block} that maps each
  9279. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9280. block. After performing liveness analysis on each block, we take the
  9281. live-before set of its first instruction and associate that with the
  9282. block's label in the \code{live\_before\_block} dictionary.
  9283. %
  9284. \fi}
  9285. In \LangXIfVar{} we also have the conditional jump
  9286. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9287. this instruction is particularly interesting because during
  9288. compilation, we do not know which way a conditional jump will go. Thus
  9289. we do not know whether to use the live-before set for the block
  9290. associated with the $\itm{label}$ or the live-before set for the
  9291. following instruction. So we use both, by taking the union of the
  9292. live-before sets from the following instruction and from the mapping
  9293. for $\itm{label}$ in
  9294. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9295. The auxiliary functions for computing the variables in an
  9296. instruction's argument and for computing the variables read-from ($R$)
  9297. or written-to ($W$) by an instruction need to be updated to handle the
  9298. new kinds of arguments and instructions in \LangXIfVar{}.
  9299. \begin{exercise}\normalfont\normalsize
  9300. {\if\edition\racketEd
  9301. %
  9302. Update the \code{uncover\_live} pass to apply liveness analysis to
  9303. every basic block in the program.
  9304. %
  9305. Add the following entry to the list of \code{passes} in the
  9306. \code{run-tests.rkt} script:
  9307. \begin{lstlisting}
  9308. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9309. \end{lstlisting}
  9310. \fi}
  9311. {\if\edition\pythonEd\pythonColor
  9312. %
  9313. Update the \code{uncover\_live} function to perform liveness analysis,
  9314. in reverse topological order, on all the basic blocks in the
  9315. program.
  9316. %
  9317. \fi}
  9318. % Check that the live-after sets that you generate for
  9319. % example X matches the following... -Jeremy
  9320. \end{exercise}
  9321. \subsection{Build the Interference Graph}
  9322. \label{sec:build-interference-Lif}
  9323. Many of the new instructions in \LangXIfVar{} can be handled in the
  9324. same way as the instructions in \LangXVar{}.
  9325. % Thus, if your code was
  9326. % already quite general, it will not need to be changed to handle the
  9327. % new instructions. If your code is not general enough, we recommend that
  9328. % you change your code to be more general. For example, you can factor
  9329. % out the computing of the the read and write sets for each kind of
  9330. % instruction into auxiliary functions.
  9331. %
  9332. Some instructions, such as the \key{movzbq} instruction, require special care,
  9333. similar to the \key{movq} instruction. Refer to rule number 1 in
  9334. section~\ref{sec:build-interference}.
  9335. \begin{exercise}\normalfont\normalsize
  9336. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9337. {\if\edition\racketEd
  9338. Add the following entries to the list of \code{passes} in the
  9339. \code{run-tests.rkt} script:
  9340. \begin{lstlisting}
  9341. (list "build_interference" build_interference interp-pseudo-x86-1)
  9342. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9343. \end{lstlisting}
  9344. \fi}
  9345. % Check that the interference graph that you generate for
  9346. % example X matches the following graph G... -Jeremy
  9347. \end{exercise}
  9348. \section{Patch Instructions}
  9349. The new instructions \key{cmpq} and \key{movzbq} have some special
  9350. restrictions that need to be handled in the \code{patch\_instructions}
  9351. pass.
  9352. %
  9353. The second argument of the \key{cmpq} instruction must not be an
  9354. immediate value (such as an integer). So, if you are comparing two
  9355. immediates, we recommend inserting a \key{movq} instruction to put the
  9356. second argument in \key{rax}. On the other hand, if you implemented
  9357. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9358. update it for \LangIf{} and then this situation would not arise.
  9359. %
  9360. As usual, \key{cmpq} may have at most one memory reference.
  9361. %
  9362. The second argument of the \key{movzbq} must be a register.
  9363. \begin{exercise}\normalfont\normalsize
  9364. %
  9365. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9366. %
  9367. {\if\edition\racketEd
  9368. Add the following entry to the list of \code{passes} in
  9369. \code{run-tests.rkt}, and then run this script to test your compiler.
  9370. \begin{lstlisting}
  9371. (list "patch_instructions" patch_instructions interp-x86-1)
  9372. \end{lstlisting}
  9373. \fi}
  9374. \end{exercise}
  9375. {\if\edition\pythonEd\pythonColor
  9376. \section{Generate Prelude and Conclusion}
  9377. \label{sec:prelude-conclusion-cond}
  9378. The generation of the \code{main} function with its prelude and
  9379. conclusion must change to accommodate how the program now consists of
  9380. one or more basic blocks. After the prelude in \code{main}, jump to
  9381. the \code{start} block. Place the conclusion in a basic block labeled
  9382. with \code{conclusion}.
  9383. \fi}
  9384. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9385. \LangIf{} translated to x86, showing the results of
  9386. \code{explicate\_control}, \code{select\_instructions}, and the final
  9387. x86 assembly.
  9388. \begin{figure}[tbp]
  9389. \begin{tcolorbox}[colback=white]
  9390. {\if\edition\racketEd
  9391. \begin{tabular}{lll}
  9392. \begin{minipage}{0.4\textwidth}
  9393. % cond_test_20.rkt, eq_input.py
  9394. \begin{lstlisting}
  9395. (if (eq? (read) 1) 42 0)
  9396. \end{lstlisting}
  9397. $\Downarrow$
  9398. \begin{lstlisting}
  9399. start:
  9400. tmp7951 = (read);
  9401. if (eq? tmp7951 1)
  9402. goto block7952;
  9403. else
  9404. goto block7953;
  9405. block7952:
  9406. return 42;
  9407. block7953:
  9408. return 0;
  9409. \end{lstlisting}
  9410. $\Downarrow$
  9411. \begin{lstlisting}
  9412. start:
  9413. callq read_int
  9414. movq %rax, tmp7951
  9415. cmpq $1, tmp7951
  9416. je block7952
  9417. jmp block7953
  9418. block7953:
  9419. movq $0, %rax
  9420. jmp conclusion
  9421. block7952:
  9422. movq $42, %rax
  9423. jmp conclusion
  9424. \end{lstlisting}
  9425. \end{minipage}
  9426. &
  9427. $\Rightarrow\qquad$
  9428. \begin{minipage}{0.4\textwidth}
  9429. \begin{lstlisting}
  9430. start:
  9431. callq read_int
  9432. movq %rax, %rcx
  9433. cmpq $1, %rcx
  9434. je block7952
  9435. jmp block7953
  9436. block7953:
  9437. movq $0, %rax
  9438. jmp conclusion
  9439. block7952:
  9440. movq $42, %rax
  9441. jmp conclusion
  9442. .globl main
  9443. main:
  9444. pushq %rbp
  9445. movq %rsp, %rbp
  9446. pushq %r13
  9447. pushq %r12
  9448. pushq %rbx
  9449. pushq %r14
  9450. subq $0, %rsp
  9451. jmp start
  9452. conclusion:
  9453. addq $0, %rsp
  9454. popq %r14
  9455. popq %rbx
  9456. popq %r12
  9457. popq %r13
  9458. popq %rbp
  9459. retq
  9460. \end{lstlisting}
  9461. \end{minipage}
  9462. \end{tabular}
  9463. \fi}
  9464. {\if\edition\pythonEd\pythonColor
  9465. \begin{tabular}{lll}
  9466. \begin{minipage}{0.4\textwidth}
  9467. % cond_test_20.rkt, eq_input.py
  9468. \begin{lstlisting}
  9469. print(42 if input_int() == 1 else 0)
  9470. \end{lstlisting}
  9471. $\Downarrow$
  9472. \begin{lstlisting}
  9473. start:
  9474. tmp_0 = input_int()
  9475. if tmp_0 == 1:
  9476. goto block_3
  9477. else:
  9478. goto block_4
  9479. block_3:
  9480. tmp_1 = 42
  9481. goto block_2
  9482. block_4:
  9483. tmp_1 = 0
  9484. goto block_2
  9485. block_2:
  9486. print(tmp_1)
  9487. return 0
  9488. \end{lstlisting}
  9489. $\Downarrow$
  9490. \begin{lstlisting}
  9491. start:
  9492. callq read_int
  9493. movq %rax, tmp_0
  9494. cmpq 1, tmp_0
  9495. je block_3
  9496. jmp block_4
  9497. block_3:
  9498. movq 42, tmp_1
  9499. jmp block_2
  9500. block_4:
  9501. movq 0, tmp_1
  9502. jmp block_2
  9503. block_2:
  9504. movq tmp_1, %rdi
  9505. callq print_int
  9506. movq 0, %rax
  9507. jmp conclusion
  9508. \end{lstlisting}
  9509. \end{minipage}
  9510. &
  9511. $\Rightarrow\qquad$
  9512. \begin{minipage}{0.4\textwidth}
  9513. \begin{lstlisting}
  9514. .globl main
  9515. main:
  9516. pushq %rbp
  9517. movq %rsp, %rbp
  9518. subq $0, %rsp
  9519. jmp start
  9520. start:
  9521. callq read_int
  9522. movq %rax, %rcx
  9523. cmpq $1, %rcx
  9524. je block_3
  9525. jmp block_4
  9526. block_3:
  9527. movq $42, %rcx
  9528. jmp block_2
  9529. block_4:
  9530. movq $0, %rcx
  9531. jmp block_2
  9532. block_2:
  9533. movq %rcx, %rdi
  9534. callq print_int
  9535. movq $0, %rax
  9536. jmp conclusion
  9537. conclusion:
  9538. addq $0, %rsp
  9539. popq %rbp
  9540. retq
  9541. \end{lstlisting}
  9542. \end{minipage}
  9543. \end{tabular}
  9544. \fi}
  9545. \end{tcolorbox}
  9546. \caption{Example compilation of an \key{if} expression to x86, showing
  9547. the results of \code{explicate\_control},
  9548. \code{select\_instructions}, and the final x86 assembly code. }
  9549. \label{fig:if-example-x86}
  9550. \end{figure}
  9551. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9552. compilation of \LangIf{}.
  9553. \begin{figure}[htbp]
  9554. \begin{tcolorbox}[colback=white]
  9555. {\if\edition\racketEd
  9556. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9557. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9558. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9559. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9560. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9561. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9562. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9563. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9564. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9565. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9566. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9567. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9568. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9569. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9570. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9571. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9572. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9573. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9574. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9575. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9576. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9577. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9578. \end{tikzpicture}
  9579. \fi}
  9580. {\if\edition\pythonEd\pythonColor
  9581. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9582. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9583. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9584. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9585. \node (C-1) at (0,0) {\large \LangCIf{}};
  9586. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9587. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9588. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9589. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9590. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9591. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9592. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9593. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9594. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9595. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9596. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9597. \end{tikzpicture}
  9598. \fi}
  9599. \end{tcolorbox}
  9600. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9601. \label{fig:Lif-passes}
  9602. \end{figure}
  9603. \section{Challenge: Optimize Blocks and Remove Jumps}
  9604. \label{sec:opt-jumps}
  9605. We discuss two challenges that involve optimizing the control-flow of
  9606. the program.
  9607. \subsection{Optimize Blocks}
  9608. The algorithm for \code{explicate\_control} that we discussed in
  9609. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9610. blocks. It creates a block whenever a continuation \emph{might} get
  9611. used more than once (for example, whenever the \code{cont} parameter
  9612. is passed into two or more recursive calls). However, some
  9613. continuation arguments may not be used at all. Consider the case for
  9614. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9615. the \code{els} continuation.
  9616. %
  9617. {\if\edition\racketEd
  9618. The following example program falls into this
  9619. case, and it creates two unused blocks.
  9620. \begin{center}
  9621. \begin{tabular}{lll}
  9622. \begin{minipage}{0.4\textwidth}
  9623. % cond_test_82.rkt
  9624. \begin{lstlisting}
  9625. (let ([y (if #t
  9626. (read)
  9627. (if (eq? (read) 0)
  9628. 777
  9629. (let ([x (read)])
  9630. (+ 1 x))))])
  9631. (+ y 2))
  9632. \end{lstlisting}
  9633. \end{minipage}
  9634. &
  9635. $\Rightarrow$
  9636. &
  9637. \begin{minipage}{0.4\textwidth}
  9638. \begin{lstlisting}
  9639. start:
  9640. y = (read);
  9641. goto block_5;
  9642. block_5:
  9643. return (+ y 2);
  9644. block_6:
  9645. y = 777;
  9646. goto block_5;
  9647. block_7:
  9648. x = (read);
  9649. y = (+ 1 x2);
  9650. goto block_5;
  9651. \end{lstlisting}
  9652. \end{minipage}
  9653. \end{tabular}
  9654. \end{center}
  9655. \fi}
  9656. {\if\edition\pythonEd
  9657. The following example program falls into this
  9658. case, and it creates the unused \code{block\_9}.
  9659. \begin{center}
  9660. \begin{minipage}{0.4\textwidth}
  9661. % if/if_true.py
  9662. \begin{lstlisting}
  9663. if True:
  9664. print(0)
  9665. else:
  9666. x = 1 if False else 2
  9667. print(x)
  9668. \end{lstlisting}
  9669. \end{minipage}
  9670. $\Rightarrow\qquad\qquad$
  9671. \begin{minipage}{0.4\textwidth}
  9672. \begin{lstlisting}
  9673. start:
  9674. print(0)
  9675. goto block_8
  9676. block_9:
  9677. print(x)
  9678. goto block_8
  9679. block_8:
  9680. return 0
  9681. \end{lstlisting}
  9682. \end{minipage}
  9683. \end{center}
  9684. \fi}
  9685. The question is, how can we decide whether to create a basic block?
  9686. \emph{Lazy evaluation}\index{subject}{lazy
  9687. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9688. delaying the creation of a basic block until the point in time at which
  9689. we know that it will be used.
  9690. %
  9691. {\if\edition\racketEd
  9692. %
  9693. Racket provides support for
  9694. lazy evaluation with the
  9695. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9696. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9697. \index{subject}{delay} creates a
  9698. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9699. expressions is postponed. When \key{(force}
  9700. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9701. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9702. result of $e_n$ is cached in the promise and returned. If \code{force}
  9703. is applied again to the same promise, then the cached result is
  9704. returned. If \code{force} is applied to an argument that is not a
  9705. promise, \code{force} simply returns the argument.
  9706. %
  9707. \fi}
  9708. %
  9709. {\if\edition\pythonEd\pythonColor
  9710. %
  9711. Although Python does not provide direct support for lazy evaluation,
  9712. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9713. by wrapping it inside a function with no parameters. We \emph{force}
  9714. its evaluation by calling the function. However, we might need to
  9715. force multiple times, so we store the result of calling the
  9716. function instead of recomputing it each time. The following
  9717. \code{Promise} class handles this memoization process.
  9718. \begin{minipage}{0.8\textwidth}
  9719. \begin{lstlisting}
  9720. @dataclass
  9721. class Promise:
  9722. fun : typing.Any
  9723. cache : list[stmt] = None
  9724. def force(self):
  9725. if self.cache is None:
  9726. self.cache = self.fun(); return self.cache
  9727. else:
  9728. return self.cache
  9729. \end{lstlisting}
  9730. \end{minipage}
  9731. \noindent However, in some cases of \code{explicate\_pred}, we return
  9732. a list of statements, and in other cases we return a function that
  9733. computes a list of statements. To uniformly deal with both regular
  9734. data and promises, we define the following \code{force} function that
  9735. checks whether its input is delayed (i.e., whether it is a
  9736. \code{Promise}) and then either (1) forces the promise or (2) returns
  9737. the input.
  9738. %
  9739. \begin{lstlisting}
  9740. def force(promise):
  9741. if isinstance(promise, Promise):
  9742. return promise.force()
  9743. else:
  9744. return promise
  9745. \end{lstlisting}
  9746. %
  9747. \fi}
  9748. We use promises for the input and output of the functions
  9749. \code{explicate\_pred}, \code{explicate\_assign},
  9750. %
  9751. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9752. %
  9753. So, instead of taking and returning \racket{$\Tail$
  9754. expressions}\python{lists of statements}, they take and return
  9755. promises. Furthermore, when we come to a situation in which a
  9756. continuation might be used more than once, as in the case for
  9757. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9758. that creates a basic block for each continuation (if there is not
  9759. already one) and then returns a \code{goto} statement to that basic
  9760. block. When we come to a situation in which we have a promise but need an
  9761. actual piece of code, for example, to create a larger piece of code with a
  9762. constructor such as \code{Seq}, then insert a call to \code{force}.
  9763. %
  9764. {\if\edition\racketEd
  9765. %
  9766. Also, we must modify the \code{create\_block} function to begin with
  9767. \code{delay} to create a promise. When forced, this promise forces the
  9768. original promise. If that returns a \code{Goto} (because the block was
  9769. already added to \code{basic-blocks}), then we return the
  9770. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9771. return a \code{Goto} to the new label.
  9772. \begin{center}
  9773. \begin{minipage}{\textwidth}
  9774. \begin{lstlisting}
  9775. (define (create_block tail)
  9776. (delay
  9777. (define t (force tail))
  9778. (match t
  9779. [(Goto label) (Goto label)]
  9780. [else
  9781. (let ([label (gensym 'block)])
  9782. (set! basic-blocks (cons (cons label t) basic-blocks))
  9783. (Goto label))])))
  9784. \end{lstlisting}
  9785. \end{minipage}
  9786. \end{center}
  9787. \fi}
  9788. {\if\edition\pythonEd\pythonColor
  9789. %
  9790. Here is the new version of the \code{create\_block} auxiliary function
  9791. that delays the creation of the new basic block.\\
  9792. \begin{minipage}{\textwidth}
  9793. \begin{lstlisting}
  9794. def create_block(promise, basic_blocks):
  9795. def delay():
  9796. stmts = force(promise)
  9797. match stmts:
  9798. case [Goto(l)]:
  9799. return [Goto(l)]
  9800. case _:
  9801. label = label_name(generate_name('block'))
  9802. basic_blocks[label] = stmts
  9803. return [Goto(label)]
  9804. return Promise(delay)
  9805. \end{lstlisting}
  9806. \end{minipage}
  9807. \fi}
  9808. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9809. improved \code{explicate\_control} on this example.
  9810. \racket{As you can see, the number of basic blocks has been reduced
  9811. from four blocks to two blocks.}%
  9812. \python{As you can see, the number of basic blocks has been reduced
  9813. from three blocks to two blocks.}
  9814. \begin{figure}[tbp]
  9815. \begin{tcolorbox}[colback=white]
  9816. {\if\edition\racketEd
  9817. \begin{tabular}{lll}
  9818. \begin{minipage}{0.45\textwidth}
  9819. % cond_test_82.rkt
  9820. \begin{lstlisting}
  9821. (let ([y (if #t
  9822. (read)
  9823. (if (eq? (read) 0)
  9824. 777
  9825. (let ([x (read)])
  9826. (+ 1 x))))])
  9827. (+ y 2))
  9828. \end{lstlisting}
  9829. \end{minipage}
  9830. &
  9831. $\quad\Rightarrow\quad$
  9832. &
  9833. \begin{minipage}{0.4\textwidth}
  9834. \begin{lstlisting}
  9835. start:
  9836. y = (read);
  9837. goto block_5;
  9838. block_5:
  9839. return (+ y 2);
  9840. \end{lstlisting}
  9841. \end{minipage}
  9842. \end{tabular}
  9843. \fi}
  9844. {\if\edition\pythonEd\pythonColor
  9845. \begin{tabular}{lll}
  9846. \begin{minipage}{0.4\textwidth}
  9847. % if/if_true.py
  9848. \begin{lstlisting}
  9849. if True:
  9850. print(0)
  9851. else:
  9852. x = 1 if False else 2
  9853. print(x)
  9854. \end{lstlisting}
  9855. \end{minipage}
  9856. &
  9857. $\Rightarrow$
  9858. &
  9859. \begin{minipage}{0.55\textwidth}
  9860. \begin{lstlisting}
  9861. start:
  9862. print(0)
  9863. goto block_4
  9864. block_4:
  9865. return 0
  9866. \end{lstlisting}
  9867. \end{minipage}
  9868. \end{tabular}
  9869. \fi}
  9870. \end{tcolorbox}
  9871. \caption{Translation from \LangIf{} to \LangCIf{}
  9872. via the improved \code{explicate\_control}.}
  9873. \label{fig:explicate-control-challenge}
  9874. \end{figure}
  9875. %% Recall that in the example output of \code{explicate\_control} in
  9876. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9877. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9878. %% block. The first goal of this challenge assignment is to remove those
  9879. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9880. %% \code{explicate\_control} on the left and shows the result of bypassing
  9881. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9882. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9883. %% \code{block55}. The optimized code on the right of
  9884. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9885. %% \code{then} branch jumping directly to \code{block55}. The story is
  9886. %% similar for the \code{else} branch, as well as for the two branches in
  9887. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9888. %% have been optimized in this way, there are no longer any jumps to
  9889. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9890. %% \begin{figure}[tbp]
  9891. %% \begin{tabular}{lll}
  9892. %% \begin{minipage}{0.4\textwidth}
  9893. %% \begin{lstlisting}
  9894. %% block62:
  9895. %% tmp54 = (read);
  9896. %% if (eq? tmp54 2) then
  9897. %% goto block59;
  9898. %% else
  9899. %% goto block60;
  9900. %% block61:
  9901. %% tmp53 = (read);
  9902. %% if (eq? tmp53 0) then
  9903. %% goto block57;
  9904. %% else
  9905. %% goto block58;
  9906. %% block60:
  9907. %% goto block56;
  9908. %% block59:
  9909. %% goto block55;
  9910. %% block58:
  9911. %% goto block56;
  9912. %% block57:
  9913. %% goto block55;
  9914. %% block56:
  9915. %% return (+ 700 77);
  9916. %% block55:
  9917. %% return (+ 10 32);
  9918. %% start:
  9919. %% tmp52 = (read);
  9920. %% if (eq? tmp52 1) then
  9921. %% goto block61;
  9922. %% else
  9923. %% goto block62;
  9924. %% \end{lstlisting}
  9925. %% \end{minipage}
  9926. %% &
  9927. %% $\Rightarrow$
  9928. %% &
  9929. %% \begin{minipage}{0.55\textwidth}
  9930. %% \begin{lstlisting}
  9931. %% block62:
  9932. %% tmp54 = (read);
  9933. %% if (eq? tmp54 2) then
  9934. %% goto block55;
  9935. %% else
  9936. %% goto block56;
  9937. %% block61:
  9938. %% tmp53 = (read);
  9939. %% if (eq? tmp53 0) then
  9940. %% goto block55;
  9941. %% else
  9942. %% goto block56;
  9943. %% block56:
  9944. %% return (+ 700 77);
  9945. %% block55:
  9946. %% return (+ 10 32);
  9947. %% start:
  9948. %% tmp52 = (read);
  9949. %% if (eq? tmp52 1) then
  9950. %% goto block61;
  9951. %% else
  9952. %% goto block62;
  9953. %% \end{lstlisting}
  9954. %% \end{minipage}
  9955. %% \end{tabular}
  9956. %% \caption{Optimize jumps by removing trivial blocks.}
  9957. %% \label{fig:optimize-jumps}
  9958. %% \end{figure}
  9959. %% The name of this pass is \code{optimize-jumps}. We recommend
  9960. %% implementing this pass in two phases. The first phrase builds a hash
  9961. %% table that maps labels to possibly improved labels. The second phase
  9962. %% changes the target of each \code{goto} to use the improved label. If
  9963. %% the label is for a trivial block, then the hash table should map the
  9964. %% label to the first non-trivial block that can be reached from this
  9965. %% label by jumping through trivial blocks. If the label is for a
  9966. %% non-trivial block, then the hash table should map the label to itself;
  9967. %% we do not want to change jumps to non-trivial blocks.
  9968. %% The first phase can be accomplished by constructing an empty hash
  9969. %% table, call it \code{short-cut}, and then iterating over the control
  9970. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9971. %% then update the hash table, mapping the block's source to the target
  9972. %% of the \code{goto}. Also, the hash table may already have mapped some
  9973. %% labels to the block's source, to you must iterate through the hash
  9974. %% table and update all of those so that they instead map to the target
  9975. %% of the \code{goto}.
  9976. %% For the second phase, we recommend iterating through the $\Tail$ of
  9977. %% each block in the program, updating the target of every \code{goto}
  9978. %% according to the mapping in \code{short-cut}.
  9979. \begin{exercise}\normalfont\normalsize
  9980. Implement the improvements to the \code{explicate\_control} pass.
  9981. Check that it removes trivial blocks in a few example programs. Then
  9982. check that your compiler still passes all your tests.
  9983. \end{exercise}
  9984. \subsection{Remove Jumps}
  9985. There is an opportunity for removing jumps that is apparent in the
  9986. example of figure~\ref{fig:explicate-control-challenge}. The
  9987. \code{start} block ends with a jump to
  9988. \racket{\code{block\_5}}\python{\code{block\_4}}, and there are no
  9989. other jumps to \racket{\code{block\_5}}\python{\code{block\_4}} in
  9990. the rest of the program. In this situation we can avoid the runtime
  9991. overhead of this jump by merging
  9992. \racket{\code{block\_5}}\python{\code{block\_4}} into the preceding
  9993. block, which in this case is the \code{start} block.
  9994. Figure~\ref{fig:remove-jumps} shows the output of
  9995. \code{allocate\_registers} on the left and the result of this
  9996. optimization on the right.
  9997. \begin{figure}[tbp]
  9998. \begin{tcolorbox}[colback=white]
  9999. {\if\edition\racketEd
  10000. \begin{tabular}{lll}
  10001. \begin{minipage}{0.5\textwidth}
  10002. % cond_test_82.rkt
  10003. \begin{lstlisting}
  10004. start:
  10005. callq read_int
  10006. movq %rax, %rcx
  10007. jmp block_5
  10008. block_5:
  10009. movq %rcx, %rax
  10010. addq $2, %rax
  10011. jmp conclusion
  10012. \end{lstlisting}
  10013. \end{minipage}
  10014. &
  10015. $\Rightarrow\qquad$
  10016. \begin{minipage}{0.4\textwidth}
  10017. \begin{lstlisting}
  10018. start:
  10019. callq read_int
  10020. movq %rax, %rcx
  10021. movq %rcx, %rax
  10022. addq $2, %rax
  10023. jmp conclusion
  10024. \end{lstlisting}
  10025. \end{minipage}
  10026. \end{tabular}
  10027. \fi}
  10028. {\if\edition\pythonEd\pythonColor
  10029. \begin{tabular}{lll}
  10030. \begin{minipage}{0.5\textwidth}
  10031. % cond_test_20.rkt
  10032. \begin{lstlisting}
  10033. start:
  10034. callq read_int
  10035. movq %rax, tmp_0
  10036. cmpq 1, tmp_0
  10037. je block_3
  10038. jmp block_4
  10039. block_3:
  10040. movq 42, tmp_1
  10041. jmp block_2
  10042. block_4:
  10043. movq 0, tmp_1
  10044. jmp block_2
  10045. block_2:
  10046. movq tmp_1, %rdi
  10047. callq print_int
  10048. movq 0, %rax
  10049. jmp conclusion
  10050. \end{lstlisting}
  10051. \end{minipage}
  10052. &
  10053. $\Rightarrow\qquad$
  10054. \begin{minipage}{0.4\textwidth}
  10055. \begin{lstlisting}
  10056. start:
  10057. callq read_int
  10058. movq %rax, tmp_0
  10059. cmpq 1, tmp_0
  10060. je block_3
  10061. movq 0, tmp_1
  10062. jmp block_2
  10063. block_3:
  10064. movq 42, tmp_1
  10065. jmp block_2
  10066. block_2:
  10067. movq tmp_1, %rdi
  10068. callq print_int
  10069. movq 0, %rax
  10070. jmp conclusion
  10071. \end{lstlisting}
  10072. \end{minipage}
  10073. \end{tabular}
  10074. \fi}
  10075. \end{tcolorbox}
  10076. \caption{Merging basic blocks by removing unnecessary jumps.}
  10077. \label{fig:remove-jumps}
  10078. \end{figure}
  10079. \begin{exercise}\normalfont\normalsize
  10080. %
  10081. Implement a pass named \code{remove\_jumps} that merges basic blocks
  10082. into their preceding basic block, when there is only one preceding
  10083. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  10084. %
  10085. {\if\edition\racketEd
  10086. In the \code{run-tests.rkt} script, add the following entry to the
  10087. list of \code{passes} between \code{allocate\_registers}
  10088. and \code{patch\_instructions}:
  10089. \begin{lstlisting}
  10090. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  10091. \end{lstlisting}
  10092. \fi}
  10093. %
  10094. Run the script to test your compiler.
  10095. %
  10096. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  10097. blocks on several test programs.
  10098. \end{exercise}
  10099. \section{Further Reading}
  10100. \label{sec:cond-further-reading}
  10101. The algorithm for \code{explicate\_control} is based on the
  10102. \code{expose-basic-blocks} pass in the course notes of
  10103. \citet{Dybvig:2010aa}.
  10104. %
  10105. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10106. \citet{Appel:2003fk}, and is related to translations into continuation
  10107. passing
  10108. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10109. %
  10110. The treatment of conditionals in the \code{explicate\_control} pass is
  10111. similar to short-cut Boolean
  10112. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10113. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10114. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10115. \chapter{Loops and Dataflow Analysis}
  10116. \label{ch:Lwhile}
  10117. \setcounter{footnote}{0}
  10118. % TODO: define R'_8
  10119. % TODO: multi-graph
  10120. {\if\edition\racketEd
  10121. %
  10122. In this chapter we study two features that are the hallmarks of
  10123. imperative programming languages: loops and assignments to local
  10124. variables. The following example demonstrates these new features by
  10125. computing the sum of the first five positive integers:
  10126. % similar to loop_test_1.rkt
  10127. \begin{lstlisting}
  10128. (let ([sum 0])
  10129. (let ([i 5])
  10130. (begin
  10131. (while (> i 0)
  10132. (begin
  10133. (set! sum (+ sum i))
  10134. (set! i (- i 1))))
  10135. sum)))
  10136. \end{lstlisting}
  10137. The \code{while} loop consists of a condition and a
  10138. body.\footnote{The \code{while} loop is not a built-in
  10139. feature of the Racket language, but Racket includes many looping
  10140. constructs and it is straightforward to define \code{while} as a
  10141. macro.} The body is evaluated repeatedly so long as the condition
  10142. remains true.
  10143. %
  10144. The \code{set!} consists of a variable and a right-hand side
  10145. expression. The \code{set!} updates value of the variable to the
  10146. value of the right-hand side.
  10147. %
  10148. The primary purpose of both the \code{while} loop and \code{set!} is
  10149. to cause side effects, so they do not give a meaningful result
  10150. value. Instead, their result is the \code{\#<void>} value. The
  10151. expression \code{(void)} is an explicit way to create the
  10152. \code{\#<void>} value, and it has type \code{Void}. The
  10153. \code{\#<void>} value can be passed around just like other values
  10154. inside an \LangLoop{} program, and it can be compared for equality with
  10155. another \code{\#<void>} value. However, there are no other operations
  10156. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10157. Racket defines the \code{void?} predicate that returns \code{\#t}
  10158. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10159. %
  10160. \footnote{Racket's \code{Void} type corresponds to what is often
  10161. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10162. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10163. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10164. %
  10165. With the addition of side effect-producing features such as
  10166. \code{while} loop and \code{set!}, it is helpful to include a language
  10167. feature for sequencing side effects: the \code{begin} expression. It
  10168. consists of one or more subexpressions that are evaluated
  10169. left to right.
  10170. %
  10171. \fi}
  10172. {\if\edition\pythonEd\pythonColor
  10173. %
  10174. In this chapter we study loops, one of the hallmarks of imperative
  10175. programming languages. The following example demonstrates the
  10176. \code{while} loop by computing the sum of the first five positive
  10177. integers.
  10178. \begin{lstlisting}
  10179. sum = 0
  10180. i = 5
  10181. while i > 0:
  10182. sum = sum + i
  10183. i = i - 1
  10184. print(sum)
  10185. \end{lstlisting}
  10186. The \code{while} loop consists of a condition and a body (a sequence
  10187. of statements). The body is evaluated repeatedly so long as the
  10188. condition remains true.
  10189. %
  10190. \fi}
  10191. \section{The \LangLoop{} Language}
  10192. \newcommand{\LwhileGrammarRacket}{
  10193. \begin{array}{lcl}
  10194. \Type &::=& \key{Void}\\
  10195. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10196. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10197. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10198. \end{array}
  10199. }
  10200. \newcommand{\LwhileASTRacket}{
  10201. \begin{array}{lcl}
  10202. \Type &::=& \key{Void}\\
  10203. \Exp &::=& \SETBANG{\Var}{\Exp}
  10204. \MID \BEGIN{\Exp^{*}}{\Exp}
  10205. \MID \WHILE{\Exp}{\Exp}
  10206. \MID \VOID{}
  10207. \end{array}
  10208. }
  10209. \newcommand{\LwhileGrammarPython}{
  10210. \begin{array}{rcl}
  10211. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10212. \end{array}
  10213. }
  10214. \newcommand{\LwhileASTPython}{
  10215. \begin{array}{lcl}
  10216. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10217. \end{array}
  10218. }
  10219. \begin{figure}[tp]
  10220. \centering
  10221. \begin{tcolorbox}[colback=white]
  10222. \small
  10223. {\if\edition\racketEd
  10224. \[
  10225. \begin{array}{l}
  10226. \gray{\LintGrammarRacket{}} \\ \hline
  10227. \gray{\LvarGrammarRacket{}} \\ \hline
  10228. \gray{\LifGrammarRacket{}} \\ \hline
  10229. \LwhileGrammarRacket \\
  10230. \begin{array}{lcl}
  10231. \LangLoopM{} &::=& \Exp
  10232. \end{array}
  10233. \end{array}
  10234. \]
  10235. \fi}
  10236. {\if\edition\pythonEd\pythonColor
  10237. \[
  10238. \begin{array}{l}
  10239. \gray{\LintGrammarPython} \\ \hline
  10240. \gray{\LvarGrammarPython} \\ \hline
  10241. \gray{\LifGrammarPython} \\ \hline
  10242. \LwhileGrammarPython \\
  10243. \begin{array}{rcl}
  10244. \LangLoopM{} &::=& \Stmt^{*}
  10245. \end{array}
  10246. \end{array}
  10247. \]
  10248. \fi}
  10249. \end{tcolorbox}
  10250. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10251. \label{fig:Lwhile-concrete-syntax}
  10252. \index{subject}{Lwhile@\LangLoop{} concrete syntax}
  10253. \end{figure}
  10254. \begin{figure}[tp]
  10255. \centering
  10256. \begin{tcolorbox}[colback=white]
  10257. \small
  10258. {\if\edition\racketEd
  10259. \[
  10260. \begin{array}{l}
  10261. \gray{\LintOpAST} \\ \hline
  10262. \gray{\LvarASTRacket{}} \\ \hline
  10263. \gray{\LifASTRacket{}} \\ \hline
  10264. \LwhileASTRacket{} \\
  10265. \begin{array}{lcl}
  10266. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10267. \end{array}
  10268. \end{array}
  10269. \]
  10270. \fi}
  10271. {\if\edition\pythonEd\pythonColor
  10272. \[
  10273. \begin{array}{l}
  10274. \gray{\LintASTPython} \\ \hline
  10275. \gray{\LvarASTPython} \\ \hline
  10276. \gray{\LifASTPython} \\ \hline
  10277. \LwhileASTPython \\
  10278. \begin{array}{lcl}
  10279. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10280. \end{array}
  10281. \end{array}
  10282. \]
  10283. \fi}
  10284. \end{tcolorbox}
  10285. \python{
  10286. \index{subject}{While@\texttt{While}}
  10287. }
  10288. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10289. \label{fig:Lwhile-syntax}
  10290. \index{subject}{Lwhile@\LangLoop{} abstract syntax}
  10291. \end{figure}
  10292. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10293. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10294. shows the definition of its abstract syntax.
  10295. %
  10296. The definitional interpreter for \LangLoop{} is shown in
  10297. figure~\ref{fig:interp-Lwhile}.
  10298. %
  10299. {\if\edition\racketEd
  10300. %
  10301. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10302. and \code{Void}, and we make changes to the cases for \code{Var} and
  10303. \code{Let} regarding variables. To support assignment to variables and
  10304. to make their lifetimes indefinite (see the second example in
  10305. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10306. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10307. value.
  10308. %
  10309. Now we discuss the new cases. For \code{SetBang}, we find the
  10310. variable in the environment to obtain a boxed value, and then we change
  10311. it using \code{set-box!} to the result of evaluating the right-hand
  10312. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10313. %
  10314. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10315. if the result is true, (2) evaluate the body.
  10316. The result value of a \code{while} loop is also \code{\#<void>}.
  10317. %
  10318. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10319. subexpressions \itm{es} for their effects and then evaluates
  10320. and returns the result from \itm{body}.
  10321. %
  10322. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10323. %
  10324. \fi}
  10325. {\if\edition\pythonEd\pythonColor
  10326. %
  10327. We add a new case for \code{While} in the \code{interp\_stmts}
  10328. function, in which we repeatedly interpret the \code{body} so long as the
  10329. \code{test} expression remains true.
  10330. %
  10331. \fi}
  10332. \begin{figure}[tbp]
  10333. \begin{tcolorbox}[colback=white]
  10334. {\if\edition\racketEd
  10335. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10336. (define interp-Lwhile-class
  10337. (class interp-Lif-class
  10338. (super-new)
  10339. (define/override ((interp-exp env) e)
  10340. (define recur (interp-exp env))
  10341. (match e
  10342. [(Let x e body)
  10343. (define new-env (dict-set env x (box (recur e))))
  10344. ((interp-exp new-env) body)]
  10345. [(Var x) (unbox (dict-ref env x))]
  10346. [(SetBang x rhs)
  10347. (set-box! (dict-ref env x) (recur rhs))]
  10348. [(WhileLoop cnd body)
  10349. (define (loop)
  10350. (cond [(recur cnd) (recur body) (loop)]
  10351. [else (void)]))
  10352. (loop)]
  10353. [(Begin es body)
  10354. (for ([e es]) (recur e))
  10355. (recur body)]
  10356. [(Void) (void)]
  10357. [else ((super interp-exp env) e)]))
  10358. ))
  10359. (define (interp-Lwhile p)
  10360. (send (new interp-Lwhile-class) interp-program p))
  10361. \end{lstlisting}
  10362. \fi}
  10363. {\if\edition\pythonEd\pythonColor
  10364. \begin{lstlisting}
  10365. class InterpLwhile(InterpLif):
  10366. def interp_stmt(self, s, env, cont):
  10367. match s:
  10368. case While(test, body, []):
  10369. if self.interp_exp(test, env):
  10370. self.interp_stmts(body + [s] + cont, env)
  10371. else:
  10372. return self.interp_stmts(cont, env)
  10373. case _:
  10374. return super().interp_stmt(s, env, cont)
  10375. \end{lstlisting}
  10376. \fi}
  10377. \end{tcolorbox}
  10378. \caption{Interpreter for \LangLoop{}.}
  10379. \label{fig:interp-Lwhile}
  10380. \end{figure}
  10381. The definition of the type checker for \LangLoop{} is shown in
  10382. figure~\ref{fig:type-check-Lwhile}.
  10383. %
  10384. {\if\edition\racketEd
  10385. %
  10386. The type checking of the \code{SetBang} expression requires the type
  10387. of the variable and the right-hand side to agree. The result type is
  10388. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10389. and the result type is \code{Void}. For \code{Begin}, the result type
  10390. is the type of its last subexpression.
  10391. %
  10392. \fi}
  10393. %
  10394. {\if\edition\pythonEd\pythonColor
  10395. %
  10396. A \code{while} loop is well typed if the type of the \code{test}
  10397. expression is \code{bool} and the statements in the \code{body} are
  10398. well typed.
  10399. %
  10400. \fi}
  10401. \begin{figure}[tbp]
  10402. \begin{tcolorbox}[colback=white]
  10403. {\if\edition\racketEd
  10404. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10405. (define type-check-Lwhile-class
  10406. (class type-check-Lif-class
  10407. (super-new)
  10408. (inherit check-type-equal?)
  10409. (define/override (type-check-exp env)
  10410. (lambda (e)
  10411. (define recur (type-check-exp env))
  10412. (match e
  10413. [(SetBang x rhs)
  10414. (define-values (rhs^ rhsT) (recur rhs))
  10415. (define varT (dict-ref env x))
  10416. (check-type-equal? rhsT varT e)
  10417. (values (SetBang x rhs^) 'Void)]
  10418. [(WhileLoop cnd body)
  10419. (define-values (cnd^ Tc) (recur cnd))
  10420. (check-type-equal? Tc 'Boolean e)
  10421. (define-values (body^ Tbody) ((type-check-exp env) body))
  10422. (values (WhileLoop cnd^ body^) 'Void)]
  10423. [(Begin es body)
  10424. (define-values (es^ ts)
  10425. (for/lists (l1 l2) ([e es]) (recur e)))
  10426. (define-values (body^ Tbody) (recur body))
  10427. (values (Begin es^ body^) Tbody)]
  10428. [else ((super type-check-exp env) e)])))
  10429. ))
  10430. (define (type-check-Lwhile p)
  10431. (send (new type-check-Lwhile-class) type-check-program p))
  10432. \end{lstlisting}
  10433. \fi}
  10434. {\if\edition\pythonEd\pythonColor
  10435. \begin{lstlisting}
  10436. class TypeCheckLwhile(TypeCheckLif):
  10437. def type_check_stmts(self, ss, env):
  10438. if len(ss) == 0:
  10439. return
  10440. match ss[0]:
  10441. case While(test, body, []):
  10442. test_t = self.type_check_exp(test, env)
  10443. check_type_equal(bool, test_t, test)
  10444. body_t = self.type_check_stmts(body, env)
  10445. return self.type_check_stmts(ss[1:], env)
  10446. case _:
  10447. return super().type_check_stmts(ss, env)
  10448. \end{lstlisting}
  10449. \fi}
  10450. \end{tcolorbox}
  10451. \caption{Type checker for the \LangLoop{} language.}
  10452. \label{fig:type-check-Lwhile}
  10453. \end{figure}
  10454. {\if\edition\racketEd
  10455. %
  10456. At first glance, the translation of these language features to x86
  10457. seems straightforward because the \LangCIf{} intermediate language
  10458. already supports all the ingredients that we need: assignment,
  10459. \code{goto}, conditional branching, and sequencing. However,
  10460. complications arise, which we discuss in the next section. After
  10461. that we introduce the changes necessary to the existing passes.
  10462. %
  10463. \fi}
  10464. {\if\edition\pythonEd\pythonColor
  10465. %
  10466. At first glance, the translation of \code{while} loops to x86 seems
  10467. straightforward because the \LangCIf{} intermediate language already
  10468. supports \code{goto} and conditional branching. However, there are
  10469. complications that arise, which we discuss in the next section. After
  10470. that we introduce the changes necessary to the existing passes.
  10471. %
  10472. \fi}
  10473. \section{Cyclic Control Flow and Dataflow Analysis}
  10474. \label{sec:dataflow-analysis}
  10475. Up until this point, the programs generated in
  10476. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10477. \code{while} loop introduces a cycle. Does that matter?
  10478. %
  10479. Indeed, it does. Recall that for register allocation, the compiler
  10480. performs liveness analysis to determine which variables can share the
  10481. same register. To accomplish this, we analyzed the control-flow graph
  10482. in reverse topological order
  10483. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10484. well defined only for acyclic graphs.
  10485. Let us return to the example of computing the sum of the first five
  10486. positive integers. Here is the program after instruction
  10487. selection\index{subject}{instruction selection} but before register
  10488. allocation.
  10489. \begin{center}
  10490. {\if\edition\racketEd
  10491. \begin{minipage}{0.45\textwidth}
  10492. \begin{lstlisting}
  10493. (define (main) : Integer
  10494. mainstart:
  10495. movq $0, sum
  10496. movq $5, i
  10497. jmp block5
  10498. block5:
  10499. movq i, tmp3
  10500. cmpq tmp3, $0
  10501. jl block7
  10502. jmp block8
  10503. \end{lstlisting}
  10504. \end{minipage}
  10505. \begin{minipage}{0.45\textwidth}
  10506. \begin{lstlisting}
  10507. block7:
  10508. addq i, sum
  10509. movq $1, tmp4
  10510. negq tmp4
  10511. addq tmp4, i
  10512. jmp block5
  10513. block8:
  10514. movq $27, %rax
  10515. addq sum, %rax
  10516. jmp mainconclusion)
  10517. \end{lstlisting}
  10518. \end{minipage}
  10519. \fi}
  10520. {\if\edition\pythonEd\pythonColor
  10521. \begin{minipage}{0.45\textwidth}
  10522. \begin{lstlisting}
  10523. mainstart:
  10524. movq $0, sum
  10525. movq $5, i
  10526. jmp block5
  10527. block5:
  10528. cmpq $0, i
  10529. jg block7
  10530. jmp block8
  10531. \end{lstlisting}
  10532. \end{minipage}
  10533. \begin{minipage}{0.45\textwidth}
  10534. \begin{lstlisting}
  10535. block7:
  10536. addq i, sum
  10537. subq $1, i
  10538. jmp block5
  10539. block8:
  10540. movq sum, %rdi
  10541. callq print_int
  10542. movq $0, %rax
  10543. jmp mainconclusion
  10544. \end{lstlisting}
  10545. \end{minipage}
  10546. \fi}
  10547. \end{center}
  10548. Recall that liveness analysis works backward, starting at the end
  10549. of each function. For this example we could start with \code{block8}
  10550. because we know what is live at the beginning of the conclusion:
  10551. only \code{rax} and \code{rsp}. So the live-before set
  10552. for \code{block8} is \code{\{rsp,sum\}}.
  10553. %
  10554. Next we might try to analyze \code{block5} or \code{block7}, but
  10555. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10556. we are stuck.
  10557. The way out of this impasse is to realize that we can compute an
  10558. underapproximation of each live-before set by starting with empty
  10559. live-after sets. By \emph{underapproximation}, we mean that the set
  10560. contains only variables that are live for some execution of the
  10561. program, but the set may be missing some variables that are live.
  10562. Next, the underapproximations for each block can be improved by (1)
  10563. updating the live-after set for each block using the approximate
  10564. live-before sets from the other blocks, and (2) performing liveness
  10565. analysis again on each block. In fact, by iterating this process, the
  10566. underapproximations eventually become the correct solutions!
  10567. %
  10568. This approach of iteratively analyzing a control-flow graph is
  10569. applicable to many static analysis problems and goes by the name
  10570. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10571. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10572. Washington.
  10573. Let us apply this approach to the previously presented example. We use
  10574. the empty set for the initial live-before set for each block. Let
  10575. $m_0$ be the following mapping from label names to sets of locations
  10576. (variables and registers):
  10577. \begin{center}
  10578. \begin{lstlisting}
  10579. mainstart: {}, block5: {}, block7: {}, block8: {}
  10580. \end{lstlisting}
  10581. \end{center}
  10582. Using the above live-before approximations, we determine the
  10583. live-after for each block and then apply liveness analysis to each
  10584. block. This produces our next approximation $m_1$ of the live-before
  10585. sets.
  10586. \begin{center}
  10587. \begin{lstlisting}
  10588. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10589. \end{lstlisting}
  10590. \end{center}
  10591. For the second round, the live-after for \code{mainstart} is the
  10592. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10593. the liveness analysis for \code{mainstart} computes the empty set. The
  10594. live-after for \code{block5} is the union of the live-before sets for
  10595. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10596. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10597. sum\}}. The live-after for \code{block7} is the live-before for
  10598. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10599. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10600. Together these yield the following approximation $m_2$ of
  10601. the live-before sets:
  10602. \begin{center}
  10603. \begin{lstlisting}
  10604. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10605. \end{lstlisting}
  10606. \end{center}
  10607. In the preceding iteration, only \code{block5} changed, so we can
  10608. limit our attention to \code{mainstart} and \code{block7}, the two
  10609. blocks that jump to \code{block5}. As a result, the live-before sets
  10610. for \code{mainstart} and \code{block7} are updated to include
  10611. \code{rsp}, yielding the following approximation $m_3$:
  10612. \begin{center}
  10613. \begin{lstlisting}
  10614. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10615. \end{lstlisting}
  10616. \end{center}
  10617. Because \code{block7} changed, we analyze \code{block5} once more, but
  10618. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10619. our approximations have converged, so $m_3$ is the solution.
  10620. This iteration process is guaranteed to converge to a solution by the
  10621. Kleene fixed-point theorem, a general theorem about functions on
  10622. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10623. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10624. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10625. join operator
  10626. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10627. will be working with join semilattices.} When two elements are
  10628. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10629. as much information as $m_i$, so we can think of $m_j$ as a
  10630. better-than-or-equal-to approximation in relation to $m_i$. The
  10631. bottom element $\bot$ represents the complete lack of information,
  10632. that is, the worst approximation. The join operator takes two lattice
  10633. elements and combines their information; that is, it produces the
  10634. least upper bound of the two.\index{subject}{least upper bound}
  10635. A dataflow analysis typically involves two lattices: one lattice to
  10636. represent abstract states and another lattice that aggregates the
  10637. abstract states of all the blocks in the control-flow graph. For
  10638. liveness analysis, an abstract state is a set of locations. We form
  10639. the lattice $L$ by taking its elements to be sets of locations, the
  10640. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10641. set, and the join operator to be set union.
  10642. %
  10643. We form a second lattice $M$ by taking its elements to be mappings
  10644. from the block labels to sets of locations (elements of $L$). We
  10645. order the mappings point-wise, using the ordering of $L$. So, given any
  10646. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10647. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10648. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10649. to the empty set, $\bot_M(\ell) = \emptyset$.
  10650. We can think of one iteration of liveness analysis applied to the
  10651. whole program as being a function $f$ on the lattice $M$. It takes a
  10652. mapping as input and computes a new mapping.
  10653. \[
  10654. f(m_i) = m_{i+1}
  10655. \]
  10656. Next let us think for a moment about what a final solution $m_s$
  10657. should look like. If we perform liveness analysis using the solution
  10658. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10659. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10660. \[
  10661. f(m_s) = m_s
  10662. \]
  10663. Furthermore, the solution should include only locations that are
  10664. forced to be there by performing liveness analysis on the program, so
  10665. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10666. The Kleene fixed-point theorem states that if a function $f$ is
  10667. monotone (better inputs produce better outputs), then the least fixed
  10668. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10669. chain} that starts at $\bot$ and iterates $f$ as
  10670. follows:\index{subject}{Kleene fixed-point theorem}
  10671. \[
  10672. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10673. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10674. \]
  10675. When a lattice contains only finitely long ascending chains, then
  10676. every Kleene chain tops out at some fixed point after some number of
  10677. iterations of $f$.
  10678. \[
  10679. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10680. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10681. \]
  10682. The liveness analysis is indeed a monotone function and the lattice
  10683. $M$ has finitely long ascending chains because there are only a
  10684. finite number of variables and blocks in the program. Thus we are
  10685. guaranteed that iteratively applying liveness analysis to all blocks
  10686. in the program will eventually produce the least fixed point solution.
  10687. Next let us consider dataflow analysis in general and discuss the
  10688. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10689. %
  10690. The algorithm has four parameters: the control-flow graph \code{G}, a
  10691. function \code{transfer} that applies the analysis to one block, and the
  10692. \code{bottom} and \code{join} operators for the lattice of abstract
  10693. states. The \code{analyze\_dataflow} function is formulated as a
  10694. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10695. function come from the predecessor nodes in the control-flow
  10696. graph. However, liveness analysis is a \emph{backward} dataflow
  10697. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10698. function with the transpose of the control-flow graph.
  10699. The algorithm begins by creating the bottom mapping, represented by a
  10700. hash table. It then pushes all the nodes in the control-flow graph
  10701. onto the work list (a queue). The algorithm repeats the \code{while}
  10702. loop as long as there are items in the work list. In each iteration, a
  10703. node is popped from the work list and processed. The \code{input} for
  10704. the node is computed by taking the join of the abstract states of all
  10705. the predecessor nodes. The \code{transfer} function is then applied to
  10706. obtain the \code{output} abstract state. If the output differs from
  10707. the previous state for this block, the mapping for this block is
  10708. updated and its successor nodes are pushed onto the work list.
  10709. \begin{figure}[tb]
  10710. \begin{tcolorbox}[colback=white]
  10711. {\if\edition\racketEd
  10712. \begin{lstlisting}
  10713. (define (analyze_dataflow G transfer bottom join)
  10714. (define mapping (make-hash))
  10715. (for ([v (in-vertices G)])
  10716. (dict-set! mapping v bottom))
  10717. (define worklist (make-queue))
  10718. (for ([v (in-vertices G)])
  10719. (enqueue! worklist v))
  10720. (define trans-G (transpose G))
  10721. (while (not (queue-empty? worklist))
  10722. (define node (dequeue! worklist))
  10723. (define input (for/fold ([state bottom])
  10724. ([pred (in-neighbors trans-G node)])
  10725. (join state (dict-ref mapping pred))))
  10726. (define output (transfer node input))
  10727. (cond [(not (equal? output (dict-ref mapping node)))
  10728. (dict-set! mapping node output)
  10729. (for ([v (in-neighbors G node)])
  10730. (enqueue! worklist v))]))
  10731. mapping)
  10732. \end{lstlisting}
  10733. \fi}
  10734. {\if\edition\pythonEd\pythonColor
  10735. \begin{lstlisting}
  10736. def analyze_dataflow(G, transfer, bottom, join):
  10737. trans_G = transpose(G)
  10738. mapping = dict((v, bottom) for v in G.vertices())
  10739. worklist = deque(G.vertices)
  10740. while worklist:
  10741. node = worklist.pop()
  10742. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10743. input = reduce(join, inputs, bottom)
  10744. output = transfer(node, input)
  10745. if output != mapping[node]:
  10746. mapping[node] = output
  10747. worklist.extend(G.adjacent(node))
  10748. \end{lstlisting}
  10749. \fi}
  10750. \end{tcolorbox}
  10751. \caption{Generic work list algorithm for dataflow analysis.}
  10752. \label{fig:generic-dataflow}
  10753. \end{figure}
  10754. {\if\edition\racketEd
  10755. \section{Mutable Variables and Remove Complex Operands}
  10756. There is a subtle interaction between the
  10757. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10758. and the left-to-right order of evaluation of Racket. Consider the
  10759. following example:
  10760. \begin{lstlisting}
  10761. (let ([x 2])
  10762. (+ x (begin (set! x 40) x)))
  10763. \end{lstlisting}
  10764. The result of this program is \code{42} because the first read from
  10765. \code{x} produces \code{2} and the second produces \code{40}. However,
  10766. if we naively apply the \code{remove\_complex\_operands} pass to this
  10767. example we obtain the following program whose result is \code{80}!
  10768. \begin{lstlisting}
  10769. (let ([x 2])
  10770. (let ([tmp (begin (set! x 40) x)])
  10771. (+ x tmp)))
  10772. \end{lstlisting}
  10773. The problem is that with mutable variables, the ordering between
  10774. reads and writes is important, and the
  10775. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10776. before the first read of \code{x}.
  10777. We recommend solving this problem by giving special treatment to reads
  10778. from mutable variables, that is, variables that occur on the left-hand
  10779. side of a \code{set!}. We mark each read from a mutable variable with
  10780. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10781. that the read operation is effectful in that it can produce different
  10782. results at different points in time. Let's apply this idea to the
  10783. following variation that also involves a variable that is not mutated:
  10784. % loop_test_24.rkt
  10785. \begin{lstlisting}
  10786. (let ([x 2])
  10787. (let ([y 0])
  10788. (+ y (+ x (begin (set! x 40) x)))))
  10789. \end{lstlisting}
  10790. We first analyze this program to discover that variable \code{x}
  10791. is mutable but \code{y} is not. We then transform the program as
  10792. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10793. \begin{lstlisting}
  10794. (let ([x 2])
  10795. (let ([y 0])
  10796. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10797. \end{lstlisting}
  10798. Now that we have a clear distinction between reads from mutable and
  10799. immutable variables, we can apply the \code{remove\_complex\_operands}
  10800. pass, where reads from immutable variables are still classified as
  10801. atomic expressions but reads from mutable variables are classified as
  10802. complex. Thus, \code{remove\_complex\_operands} yields the following
  10803. program:\\
  10804. \begin{minipage}{\textwidth}
  10805. \begin{lstlisting}
  10806. (let ([x 2])
  10807. (let ([y 0])
  10808. (let ([t1 x])
  10809. (let ([t2 (begin (set! x 40) x)])
  10810. (let ([t3 (+ t1 t2)])
  10811. (+ y t3))))))
  10812. \end{lstlisting}
  10813. \end{minipage}
  10814. The temporary variable \code{t1} gets the value of \code{x} before the
  10815. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10816. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10817. do not generate a temporary variable for the occurrence of \code{y}
  10818. because it's an immutable variable. We want to avoid such unnecessary
  10819. extra temporaries because they would needlessly increase the number of
  10820. variables, making it more likely for some of them to be spilled. The
  10821. result of this program is \code{42}, the same as the result prior to
  10822. \code{remove\_complex\_operands}.
  10823. The approach that we've sketched requires only a small
  10824. modification to \code{remove\_complex\_operands} to handle
  10825. \code{get!}. However, it requires a new pass, called
  10826. \code{uncover-get!}, that we discuss in
  10827. section~\ref{sec:uncover-get-bang}.
  10828. As an aside, this problematic interaction between \code{set!} and the
  10829. pass \code{remove\_complex\_operands} is particular to Racket and not
  10830. its predecessor, the Scheme language. The key difference is that
  10831. Scheme does not specify an order of evaluation for the arguments of an
  10832. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10833. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10834. would be correct results for the example program. Interestingly,
  10835. Racket is implemented on top of the Chez Scheme
  10836. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10837. presented in this section (using extra \code{let} bindings to control
  10838. the order of evaluation) is used in the translation from Racket to
  10839. Scheme~\citep{Flatt:2019tb}.
  10840. \fi} % racket
  10841. Having discussed the complications that arise from adding support for
  10842. assignment and loops, we turn to discussing the individual compilation
  10843. passes.
  10844. {\if\edition\racketEd
  10845. \section{Uncover \texttt{get!}}
  10846. \label{sec:uncover-get-bang}
  10847. The goal of this pass is to mark uses of mutable variables so that
  10848. \code{remove\_complex\_operands} can treat them as complex expressions
  10849. and thereby preserve their ordering relative to the side effects in
  10850. other operands. So, the first step is to collect all the mutable
  10851. variables. We recommend creating an auxiliary function for this,
  10852. named \code{collect-set!}, that recursively traverses expressions,
  10853. returning the set of all variables that occur on the left-hand side of a
  10854. \code{set!}. Here's an excerpt of its implementation.
  10855. \begin{center}
  10856. \begin{minipage}{\textwidth}
  10857. \begin{lstlisting}
  10858. (define (collect-set! e)
  10859. (match e
  10860. [(Var x) (set)]
  10861. [(Int n) (set)]
  10862. [(Let x rhs body)
  10863. (set-union (collect-set! rhs) (collect-set! body))]
  10864. [(SetBang var rhs)
  10865. (set-union (set var) (collect-set! rhs))]
  10866. ...))
  10867. \end{lstlisting}
  10868. \end{minipage}
  10869. \end{center}
  10870. By placing this pass after \code{uniquify}, we need not worry about
  10871. variable shadowing, and our logic for \code{Let} can remain simple, as
  10872. in this excerpt.
  10873. The second step is to mark the occurrences of the mutable variables
  10874. with the new \code{GetBang} AST node (\code{get!} in concrete
  10875. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10876. function, which takes two parameters: the set of mutable variables
  10877. \code{set!-vars} and the expression \code{e} to be processed. The
  10878. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10879. mutable variable or leaves it alone if not.
  10880. \begin{center}
  10881. \begin{minipage}{\textwidth}
  10882. \begin{lstlisting}
  10883. (define ((uncover-get!-exp set!-vars) e)
  10884. (match e
  10885. [(Var x)
  10886. (if (set-member? set!-vars x)
  10887. (GetBang x)
  10888. (Var x))]
  10889. ...))
  10890. \end{lstlisting}
  10891. \end{minipage}
  10892. \end{center}
  10893. To wrap things up, define the \code{uncover-get!} function for
  10894. processing a whole program, using \code{collect-set!} to obtain the
  10895. set of mutable variables and then \code{uncover-get!-exp} to replace
  10896. their occurrences with \code{GetBang}.
  10897. \fi}
  10898. \section{Remove Complex Operands}
  10899. \label{sec:rco-loop}
  10900. {\if\edition\racketEd
  10901. %
  10902. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10903. \code{while} are all complex expressions. The subexpressions of
  10904. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10905. %
  10906. \fi}
  10907. {\if\edition\pythonEd\pythonColor
  10908. %
  10909. The change needed for this pass is to add a case for the \code{while}
  10910. statement. The condition of a loop is allowed to be a complex
  10911. expression, just like the condition of the \code{if} statement.
  10912. %
  10913. \fi}
  10914. %
  10915. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10916. \LangLoopANF{} of this pass.
  10917. \newcommand{\LwhileMonadASTRacket}{
  10918. \begin{array}{rcl}
  10919. \Atm &::=& \VOID{} \\
  10920. \Exp &::=& \GETBANG{\Var}
  10921. \MID \SETBANG{\Var}{\Exp}
  10922. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10923. &\MID& \WHILE{\Exp}{\Exp}
  10924. \end{array}
  10925. }
  10926. \newcommand{\LwhileMonadASTPython}{
  10927. \begin{array}{rcl}
  10928. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10929. \end{array}
  10930. }
  10931. \begin{figure}[tp]
  10932. \centering
  10933. \begin{tcolorbox}[colback=white]
  10934. \small
  10935. {\if\edition\racketEd
  10936. \[
  10937. \begin{array}{l}
  10938. \gray{\LvarMonadASTRacket} \\ \hline
  10939. \gray{\LifMonadASTRacket} \\ \hline
  10940. \LwhileMonadASTRacket \\
  10941. \begin{array}{rcl}
  10942. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10943. \end{array}
  10944. \end{array}
  10945. \]
  10946. \fi}
  10947. {\if\edition\pythonEd\pythonColor
  10948. \[
  10949. \begin{array}{l}
  10950. \gray{\LvarMonadASTPython} \\ \hline
  10951. \gray{\LifMonadASTPython} \\ \hline
  10952. \LwhileMonadASTPython \\
  10953. \begin{array}{rcl}
  10954. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10955. \end{array}
  10956. \end{array}
  10957. \]
  10958. \fi}
  10959. \end{tcolorbox}
  10960. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10961. \label{fig:Lwhile-anf-syntax}
  10962. \index{subject}{Lwhilemon@\LangLoopANF{} abstract syntax}
  10963. \end{figure}
  10964. {\if\edition\racketEd
  10965. %
  10966. As usual, when a complex expression appears in a grammar position that
  10967. needs to be atomic, such as the argument of a primitive operator, we
  10968. must introduce a temporary variable and bind it to the complex
  10969. expression. This approach applies, unchanged, to handle the new
  10970. language forms. For example, in the following code there are two
  10971. \code{begin} expressions appearing as arguments to the \code{+}
  10972. operator. The output of \code{rco\_exp} is then shown, in which the
  10973. \code{begin} expressions have been bound to temporary
  10974. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10975. allowed to have arbitrary expressions in their right-hand side
  10976. expression, so it is fine to place \code{begin} there.
  10977. %
  10978. \begin{center}
  10979. \begin{tabular}{lcl}
  10980. \begin{minipage}{0.4\textwidth}
  10981. \begin{lstlisting}
  10982. (let ([x2 10])
  10983. (let ([y3 0])
  10984. (+ (+ (begin
  10985. (set! y3 (read))
  10986. (get! x2))
  10987. (begin
  10988. (set! x2 (read))
  10989. (get! y3)))
  10990. (get! x2))))
  10991. \end{lstlisting}
  10992. \end{minipage}
  10993. &
  10994. $\Rightarrow$
  10995. &
  10996. \begin{minipage}{0.4\textwidth}
  10997. \begin{lstlisting}
  10998. (let ([x2 10])
  10999. (let ([y3 0])
  11000. (let ([tmp4 (begin
  11001. (set! y3 (read))
  11002. x2)])
  11003. (let ([tmp5 (begin
  11004. (set! x2 (read))
  11005. y3)])
  11006. (let ([tmp6 (+ tmp4 tmp5)])
  11007. (let ([tmp7 x2])
  11008. (+ tmp6 tmp7)))))))
  11009. \end{lstlisting}
  11010. \end{minipage}
  11011. \end{tabular}
  11012. \end{center}
  11013. \fi}
  11014. \section{Explicate Control \racket{and \LangCLoop{}}}
  11015. \label{sec:explicate-loop}
  11016. \newcommand{\CloopASTRacket}{
  11017. \begin{array}{lcl}
  11018. \Atm &::=& \VOID \\
  11019. \Stmt &::=& \READ{}
  11020. \end{array}
  11021. }
  11022. {\if\edition\racketEd
  11023. Recall that in the \code{explicate\_control} pass we define one helper
  11024. function for each kind of position in the program. For the \LangVarANF{}
  11025. language of integers and variables, we needed assignment and tail
  11026. positions. The \code{if} expressions of \LangIfANF{} introduced predicate
  11027. positions. For \LangLoopANF{}, the \code{begin} expression introduces yet
  11028. another kind of position: effect position. Except for the last
  11029. subexpression, the subexpressions inside a \code{begin} are evaluated
  11030. only for their effect. Their result values are discarded. We can
  11031. generate better code by taking this fact into account.
  11032. The output language of \code{explicate\_control} is \LangCLoop{}
  11033. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  11034. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  11035. and that \code{read} may appear as a statement. The most significant
  11036. difference between the programs generated by \code{explicate\_control}
  11037. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  11038. chapter is that the control-flow graphs of the latter may contain
  11039. cycles.
  11040. \begin{figure}[tp]
  11041. \begin{tcolorbox}[colback=white]
  11042. \small
  11043. \[
  11044. \begin{array}{l}
  11045. \gray{\CvarASTRacket} \\ \hline
  11046. \gray{\CifASTRacket} \\ \hline
  11047. \CloopASTRacket \\
  11048. \begin{array}{lcl}
  11049. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11050. \end{array}
  11051. \end{array}
  11052. \]
  11053. \end{tcolorbox}
  11054. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  11055. \label{fig:c7-syntax}
  11056. \index{subject}{Cwhile@\LangCLoop{} abstract syntax}
  11057. \end{figure}
  11058. The new auxiliary function \code{explicate\_effect} takes an
  11059. expression (in an effect position) and the code for its
  11060. continuation. The function returns a $\Tail$ that includes the
  11061. generated code for the input expression followed by the
  11062. continuation. If the expression is obviously pure, that is, never
  11063. causes side effects, then the expression can be removed, so the result
  11064. is just the continuation.
  11065. %
  11066. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  11067. interesting; the generated code is depicted in the following diagram:
  11068. \begin{center}
  11069. \begin{minipage}{0.3\textwidth}
  11070. \xymatrix{
  11071. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  11072. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  11073. & *+[F]{\txt{\itm{cont}}} \\
  11074. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  11075. }
  11076. \end{minipage}
  11077. \end{center}
  11078. We start by creating a fresh label $\itm{loop}$ for the top of the
  11079. loop. Next, recursively process the \itm{body} (in effect position)
  11080. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  11081. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  11082. \itm{body'} as the \emph{then} branch and the continuation block as the
  11083. \emph{else} branch. The result should be added to the dictionary of
  11084. \code{basic-blocks} with the label \itm{loop}. The result for the
  11085. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  11086. The auxiliary functions for tail, assignment, and predicate positions
  11087. need to be updated. The three new language forms, \code{while},
  11088. \code{set!}, and \code{begin}, can appear in assignment and tail
  11089. positions. Only \code{begin} may appear in predicate positions; the
  11090. other two have result type \code{Void}.
  11091. \fi}
  11092. %
  11093. {\if\edition\pythonEd\pythonColor
  11094. %
  11095. The output of this pass is the language \LangCIf{}. No new language
  11096. features are needed in the output, because a \code{while} loop can be
  11097. expressed in terms of \code{goto} and \code{if} statements, which are
  11098. already in \LangCIf{}.
  11099. %
  11100. Add a case for the \code{while} statement to the
  11101. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  11102. the condition expression.
  11103. %
  11104. \fi}
  11105. {\if\edition\racketEd
  11106. \section{Select Instructions}
  11107. \label{sec:select-instructions-loop}
  11108. \index{subject}{select instructions}
  11109. Only two small additions are needed in the \code{select\_instructions}
  11110. pass to handle the changes to \LangCLoop{}. First, to handle the
  11111. addition of \VOID{} we simply translate it to \code{0}. Second,
  11112. \code{read} may appear as a stand-alone statement instead of
  11113. appearing only on the right-hand side of an assignment statement. The code
  11114. generation is nearly identical to the one for assignment; just leave
  11115. off the instruction for moving the result into the left-hand side.
  11116. \fi}
  11117. \section{Register Allocation}
  11118. \label{sec:register-allocation-loop}
  11119. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11120. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11121. which complicates the liveness analysis needed for register
  11122. allocation.
  11123. %
  11124. We recommend using the generic \code{analyze\_dataflow} function that
  11125. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11126. perform liveness analysis, replacing the code in
  11127. \code{uncover\_live} that processed the basic blocks in topological
  11128. order (section~\ref{sec:liveness-analysis-Lif}).
  11129. The \code{analyze\_dataflow} function has the following four parameters.
  11130. \begin{enumerate}
  11131. \item The first parameter \code{G} should be passed the transpose
  11132. of the control-flow graph.
  11133. \item The second parameter \code{transfer} should be passed a function
  11134. that applies liveness analysis to a basic block. It takes two
  11135. parameters: the label for the block to analyze and the live-after
  11136. set for that block. The transfer function should return the
  11137. live-before set for the block.
  11138. %
  11139. \racket{Also, as a side effect, it should update the block's
  11140. $\itm{info}$ with the liveness information for each instruction.}
  11141. %
  11142. \python{Also, as a side effect, it should update the live-before and
  11143. live-after sets for each instruction.}
  11144. %
  11145. To implement the \code{transfer} function, you should be able to
  11146. reuse the code you already have for analyzing basic blocks.
  11147. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11148. \code{bottom} and \code{join} for the lattice of abstract states,
  11149. that is, sets of locations. For liveness analysis, the bottom of the
  11150. lattice is the empty set, and the join operator is set union.
  11151. \end{enumerate}
  11152. \begin{figure}[tp]
  11153. \begin{tcolorbox}[colback=white]
  11154. {\if\edition\racketEd
  11155. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11156. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11157. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11158. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11159. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11160. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11161. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11162. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11163. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11164. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11165. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11166. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11167. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11168. \path[->,bend left=15] (Lfun) edge [above] node
  11169. {\ttfamily\footnotesize shrink} (Lfun-2);
  11170. \path[->,bend left=15] (Lfun-2) edge [above] node
  11171. {\ttfamily\footnotesize uniquify} (F1-4);
  11172. \path[->,bend left=15] (F1-4) edge [above] node
  11173. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11174. \path[->,bend left=15] (F1-5) edge [left] node
  11175. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11176. \path[->,bend left=10] (F1-6) edge [above] node
  11177. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11178. \path[->,bend left=15] (C3-2) edge [right] node
  11179. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11180. \path[->,bend right=15] (x86-2) edge [right] node
  11181. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11182. \path[->,bend right=15] (x86-2-1) edge [below] node
  11183. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11184. \path[->,bend right=15] (x86-2-2) edge [right] node
  11185. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11186. \path[->,bend left=15] (x86-3) edge [above] node
  11187. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11188. \path[->,bend left=15] (x86-4) edge [right] node
  11189. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11190. \end{tikzpicture}
  11191. \fi}
  11192. {\if\edition\pythonEd\pythonColor
  11193. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11194. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11195. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11196. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11197. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11198. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11199. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11200. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11201. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11202. \path[->,bend left=15] (Lfun) edge [above] node
  11203. {\ttfamily\footnotesize shrink} (Lfun-2);
  11204. \path[->,bend left=15] (Lfun-2) edge [above] node
  11205. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11206. \path[->,bend left=10] (F1-6) edge [right] node
  11207. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11208. \path[->,bend right=15] (C3-2) edge [right] node
  11209. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11210. \path[->,bend right=15] (x86-2) edge [below] node
  11211. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11212. \path[->,bend left=15] (x86-3) edge [above] node
  11213. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11214. \path[->,bend right=15] (x86-4) edge [below] node
  11215. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11216. \end{tikzpicture}
  11217. \fi}
  11218. \end{tcolorbox}
  11219. \caption{Diagram of the passes for \LangLoop{}.}
  11220. \label{fig:Lwhile-passes}
  11221. \end{figure}
  11222. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11223. for the compilation of \LangLoop{}.
  11224. % Further Reading: dataflow analysis
  11225. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11226. \chapter{Tuples and Garbage Collection}
  11227. \label{ch:Lvec}
  11228. \index{subject}{tuple}
  11229. \index{subject}{vector}
  11230. \setcounter{footnote}{0}
  11231. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11232. %% all the IR grammars are spelled out! \\ --Jeremy}
  11233. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11234. %% the root stack. \\ --Jeremy}
  11235. In this chapter we study the implementation of tuples\racket{, called
  11236. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11237. in which each element may have a different type.
  11238. %
  11239. This language feature is the first to use the computer's
  11240. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11241. indefinite; that is, a tuple lives forever from the programmer's
  11242. viewpoint. Of course, from an implementer's viewpoint, it is important
  11243. to reclaim the space associated with a tuple when it is no longer
  11244. needed, which is why we also study \emph{garbage collection}
  11245. \index{subject}{garbage collection} techniques in this chapter.
  11246. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11247. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11248. language (chapter~\ref{ch:Lwhile}) with tuples.
  11249. %
  11250. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11251. copying live tuples back and forth between two halves of the heap. The
  11252. garbage collector requires coordination with the compiler so that it
  11253. can find all the live tuples.
  11254. %
  11255. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11256. discuss the necessary changes and additions to the compiler passes,
  11257. including a new compiler pass named \code{expose\_allocation}.
  11258. \section{The \LangVec{} Language}
  11259. \label{sec:r3}
  11260. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11261. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11262. the definition of the abstract syntax.
  11263. %
  11264. \racket{The \LangVec{} language includes the forms \code{vector} for
  11265. creating a tuple, \code{vector-ref} for reading an element of a
  11266. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11267. \code{vector-length} for obtaining the number of elements of a
  11268. tuple.}
  11269. %
  11270. \python{The \LangVec{} language adds (1) tuple creation via a
  11271. comma-separated list of expressions; (2) accessing an element of a
  11272. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11273. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11274. comparison operator; and (4) obtaining the number of elements (the
  11275. length) of a tuple. In this chapter, we restrict access indices to
  11276. constant integers.}
  11277. %
  11278. The following program shows an example of the use of tuples. It creates a tuple
  11279. \code{t} containing the elements \code{40},
  11280. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11281. contains just \code{2}. The element at index $1$ of \code{t} is
  11282. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11283. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11284. to which we add \code{2}, the element at index $0$ of the tuple.
  11285. The result of the program is \code{42}.
  11286. %
  11287. {\if\edition\racketEd
  11288. \begin{lstlisting}
  11289. (let ([t (vector 40 #t (vector 2))])
  11290. (if (vector-ref t 1)
  11291. (+ (vector-ref t 0)
  11292. (vector-ref (vector-ref t 2) 0))
  11293. 44))
  11294. \end{lstlisting}
  11295. \fi}
  11296. {\if\edition\pythonEd\pythonColor
  11297. \begin{lstlisting}
  11298. t = 40, True, (2,)
  11299. print(t[0] + t[2][0] if t[1] else 44)
  11300. \end{lstlisting}
  11301. \fi}
  11302. \newcommand{\LtupGrammarRacket}{
  11303. \begin{array}{lcl}
  11304. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11305. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11306. \MID \LP\key{vector-length}\;\Exp\RP \\
  11307. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11308. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11309. \end{array}
  11310. }
  11311. \newcommand{\LtupASTRacket}{
  11312. \begin{array}{lcl}
  11313. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11314. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11315. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11316. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11317. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11318. \end{array}
  11319. }
  11320. \newcommand{\LtupGrammarPython}{
  11321. \begin{array}{rcl}
  11322. \itm{cmp} &::= & \key{is} \\
  11323. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11324. \end{array}
  11325. }
  11326. \newcommand{\LtupASTPython}{
  11327. \begin{array}{lcl}
  11328. \itm{cmp} &::= & \code{Is()} \\
  11329. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11330. &\MID& \LEN{\Exp}
  11331. \end{array}
  11332. }
  11333. \begin{figure}[tbp]
  11334. \centering
  11335. \begin{tcolorbox}[colback=white]
  11336. \small
  11337. {\if\edition\racketEd
  11338. \[
  11339. \begin{array}{l}
  11340. \gray{\LintGrammarRacket{}} \\ \hline
  11341. \gray{\LvarGrammarRacket{}} \\ \hline
  11342. \gray{\LifGrammarRacket{}} \\ \hline
  11343. \gray{\LwhileGrammarRacket} \\ \hline
  11344. \LtupGrammarRacket \\
  11345. \begin{array}{lcl}
  11346. \LangVecM{} &::=& \Exp
  11347. \end{array}
  11348. \end{array}
  11349. \]
  11350. \fi}
  11351. {\if\edition\pythonEd\pythonColor
  11352. \[
  11353. \begin{array}{l}
  11354. \gray{\LintGrammarPython{}} \\ \hline
  11355. \gray{\LvarGrammarPython{}} \\ \hline
  11356. \gray{\LifGrammarPython{}} \\ \hline
  11357. \gray{\LwhileGrammarPython} \\ \hline
  11358. \LtupGrammarPython \\
  11359. \begin{array}{rcl}
  11360. \LangVecM{} &::=& \Stmt^{*}
  11361. \end{array}
  11362. \end{array}
  11363. \]
  11364. \fi}
  11365. \end{tcolorbox}
  11366. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11367. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11368. \label{fig:Lvec-concrete-syntax}
  11369. \index{subject}{Ltup@\LangVec{} concrete syntax}
  11370. \end{figure}
  11371. \begin{figure}[tp]
  11372. \centering
  11373. \begin{tcolorbox}[colback=white]
  11374. \small
  11375. {\if\edition\racketEd
  11376. \[
  11377. \begin{array}{l}
  11378. \gray{\LintOpAST} \\ \hline
  11379. \gray{\LvarASTRacket{}} \\ \hline
  11380. \gray{\LifASTRacket{}} \\ \hline
  11381. \gray{\LwhileASTRacket{}} \\ \hline
  11382. \LtupASTRacket{} \\
  11383. \begin{array}{lcl}
  11384. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11385. \end{array}
  11386. \end{array}
  11387. \]
  11388. \fi}
  11389. {\if\edition\pythonEd\pythonColor
  11390. \[
  11391. \begin{array}{l}
  11392. \gray{\LintASTPython} \\ \hline
  11393. \gray{\LvarASTPython} \\ \hline
  11394. \gray{\LifASTPython} \\ \hline
  11395. \gray{\LwhileASTPython} \\ \hline
  11396. \LtupASTPython \\
  11397. \begin{array}{lcl}
  11398. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11399. \end{array}
  11400. \end{array}
  11401. \]
  11402. \fi}
  11403. \end{tcolorbox}
  11404. \caption{The abstract syntax of \LangVec{}.}
  11405. \label{fig:Lvec-syntax}
  11406. \index{subject}{Ltup@\LangVec{} abstract syntax}
  11407. \end{figure}
  11408. Tuples raise several interesting new issues. First, variable binding
  11409. performs a shallow copy in dealing with tuples, which means that
  11410. different variables can refer to the same tuple; that is, two
  11411. variables can be \emph{aliases}\index{subject}{alias} for the same
  11412. entity. Consider the following example, in which \code{t1} and
  11413. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11414. different tuple value with equal elements. The result of the
  11415. program is \code{42}.
  11416. \begin{center}
  11417. \begin{minipage}{0.96\textwidth}
  11418. {\if\edition\racketEd
  11419. \begin{lstlisting}
  11420. (let ([t1 (vector 3 7)])
  11421. (let ([t2 t1])
  11422. (let ([t3 (vector 3 7)])
  11423. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11424. 42
  11425. 0))))
  11426. \end{lstlisting}
  11427. \fi}
  11428. {\if\edition\pythonEd\pythonColor
  11429. \begin{lstlisting}
  11430. t1 = 3, 7
  11431. t2 = t1
  11432. t3 = 3, 7
  11433. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11434. \end{lstlisting}
  11435. \fi}
  11436. \end{minipage}
  11437. \end{center}
  11438. {\if\edition\racketEd
  11439. Whether two variables are aliased or not affects what happens
  11440. when the underlying tuple is mutated\index{subject}{mutation}.
  11441. Consider the following example in which \code{t1} and \code{t2}
  11442. again refer to the same tuple value.
  11443. \begin{center}
  11444. \begin{minipage}{0.96\textwidth}
  11445. \begin{lstlisting}
  11446. (let ([t1 (vector 3 7)])
  11447. (let ([t2 t1])
  11448. (let ([_ (vector-set! t2 0 42)])
  11449. (vector-ref t1 0))))
  11450. \end{lstlisting}
  11451. \end{minipage}
  11452. \end{center}
  11453. The mutation through \code{t2} is visible in referencing the tuple
  11454. from \code{t1}, so the result of this program is \code{42}.
  11455. \fi}
  11456. The next issue concerns the lifetime of tuples. When does a tuple's
  11457. lifetime end? Notice that \LangVec{} does not include an operation
  11458. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11459. to any notion of static scoping.
  11460. %
  11461. {\if\edition\racketEd
  11462. %
  11463. For example, the following program returns \code{42} even though the
  11464. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11465. that reads from the vector to which it was bound.
  11466. \begin{center}
  11467. \begin{minipage}{0.96\textwidth}
  11468. \begin{lstlisting}
  11469. (let ([v (vector (vector 44))])
  11470. (let ([x (let ([w (vector 42)])
  11471. (let ([_ (vector-set! v 0 w)])
  11472. 0))])
  11473. (+ x (vector-ref (vector-ref v 0) 0))))
  11474. \end{lstlisting}
  11475. \end{minipage}
  11476. \end{center}
  11477. \fi}
  11478. %
  11479. {\if\edition\pythonEd\pythonColor
  11480. %
  11481. For example, the following program returns \code{42} even though the
  11482. variable \code{x} goes out of scope when the function returns, prior
  11483. to reading the tuple element at index $0$. (We study the compilation
  11484. of functions in chapter~\ref{ch:Lfun}.)
  11485. %
  11486. \begin{center}
  11487. \begin{minipage}{0.96\textwidth}
  11488. \begin{lstlisting}
  11489. def f():
  11490. x = 42, 43
  11491. return x
  11492. t = f()
  11493. print(t[0])
  11494. \end{lstlisting}
  11495. \end{minipage}
  11496. \end{center}
  11497. \fi}
  11498. %
  11499. From the perspective of programmer-observable behavior, tuples live
  11500. forever. However, if they really lived forever then many long-running
  11501. programs would run out of memory. To solve this problem, the
  11502. language's runtime system performs automatic garbage collection.
  11503. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11504. \LangVec{} language.
  11505. %
  11506. \racket{We define the \code{vector}, \code{vector-ref},
  11507. \code{vector-set!}, and \code{vector-length} operations for
  11508. \LangVec{} in terms of the corresponding operations in Racket. One
  11509. subtle point is that the \code{vector-set!} operation returns the
  11510. \code{\#<void>} value.}
  11511. %
  11512. \python{We represent tuples with Python lists in the interpreter
  11513. because we need to write to them
  11514. (section~\ref{sec:expose-allocation}). (Python tuples are
  11515. immutable.) We define element access, the \code{is} operator, and
  11516. the \code{len} operator for \LangVec{} in terms of the corresponding
  11517. operations in Python.}
  11518. \begin{figure}[tbp]
  11519. \begin{tcolorbox}[colback=white]
  11520. {\if\edition\racketEd
  11521. \begin{lstlisting}
  11522. (define interp-Lvec-class
  11523. (class interp-Lwhile-class
  11524. (super-new)
  11525. (define/override (interp-op op)
  11526. (match op
  11527. ['eq? (lambda (v1 v2)
  11528. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11529. (and (boolean? v1) (boolean? v2))
  11530. (and (vector? v1) (vector? v2))
  11531. (and (void? v1) (void? v2)))
  11532. (eq? v1 v2)]))]
  11533. ['vector vector]
  11534. ['vector-length vector-length]
  11535. ['vector-ref vector-ref]
  11536. ['vector-set! vector-set!]
  11537. [else (super interp-op op)]
  11538. ))
  11539. (define/override ((interp-exp env) e)
  11540. (match e
  11541. [(HasType e t) ((interp-exp env) e)]
  11542. [else ((super interp-exp env) e)]
  11543. ))
  11544. ))
  11545. (define (interp-Lvec p)
  11546. (send (new interp-Lvec-class) interp-program p))
  11547. \end{lstlisting}
  11548. \fi}
  11549. %
  11550. {\if\edition\pythonEd\pythonColor
  11551. \begin{lstlisting}
  11552. class InterpLtup(InterpLwhile):
  11553. def interp_cmp(self, cmp):
  11554. match cmp:
  11555. case Is():
  11556. return lambda x, y: x is y
  11557. case _:
  11558. return super().interp_cmp(cmp)
  11559. def interp_exp(self, e, env):
  11560. match e:
  11561. case Tuple(es, Load()):
  11562. return tuple([self.interp_exp(e, env) for e in es])
  11563. case Subscript(tup, index, Load()):
  11564. t = self.interp_exp(tup, env)
  11565. n = self.interp_exp(index, env)
  11566. return t[n]
  11567. case _:
  11568. return super().interp_exp(e, env)
  11569. \end{lstlisting}
  11570. \fi}
  11571. \end{tcolorbox}
  11572. \caption{Interpreter for the \LangVec{} language.}
  11573. \label{fig:interp-Lvec}
  11574. \end{figure}
  11575. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11576. \LangVec{}.
  11577. %
  11578. The type of a tuple is a
  11579. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11580. type for each of its elements.
  11581. %
  11582. \racket{To create the s-expression for the \code{Vector} type, we use the
  11583. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11584. operator} \code{,@} to insert the list \code{t*} without its usual
  11585. start and end parentheses. \index{subject}{unquote-splicing}}
  11586. %
  11587. The type of accessing the ith element of a tuple is the ith element
  11588. type of the tuple's type, if there is one. If not, an error is
  11589. signaled. Note that the index \code{i} is required to be a constant
  11590. integer (and not, for example, a call to
  11591. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11592. can determine the element's type given the tuple type.
  11593. %
  11594. \racket{
  11595. Regarding writing an element to a tuple, the element's type must
  11596. be equal to the ith element type of the tuple's type.
  11597. The result type is \code{Void}.}
  11598. %% When allocating a tuple,
  11599. %% we need to know which elements of the tuple are themselves tuples for
  11600. %% the purposes of garbage collection. We can obtain this information
  11601. %% during type checking. The type checker shown in
  11602. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11603. %% expression; it also
  11604. %% %
  11605. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11606. %% where $T$ is the tuple's type.
  11607. %
  11608. %records the type of each tuple expression in a new field named \code{has\_type}.
  11609. \begin{figure}[tp]
  11610. \begin{tcolorbox}[colback=white]
  11611. {\if\edition\racketEd
  11612. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11613. (define type-check-Lvec-class
  11614. (class type-check-Lif-class
  11615. (super-new)
  11616. (inherit check-type-equal?)
  11617. (define/override (type-check-exp env)
  11618. (lambda (e)
  11619. (define recur (type-check-exp env))
  11620. (match e
  11621. [(Prim 'vector es)
  11622. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11623. (define t `(Vector ,@t*))
  11624. (values (Prim 'vector e*) t)]
  11625. [(Prim 'vector-ref (list e1 (Int i)))
  11626. (define-values (e1^ t) (recur e1))
  11627. (match t
  11628. [`(Vector ,ts ...)
  11629. (unless (and (0 . <= . i) (i . < . (length ts)))
  11630. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11631. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11632. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11633. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11634. (define-values (e-vec t-vec) (recur e1))
  11635. (define-values (e-elt^ t-elt) (recur elt))
  11636. (match t-vec
  11637. [`(Vector ,ts ...)
  11638. (unless (and (0 . <= . i) (i . < . (length ts)))
  11639. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11640. (check-type-equal? (list-ref ts i) t-elt e)
  11641. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11642. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11643. [(Prim 'vector-length (list e))
  11644. (define-values (e^ t) (recur e))
  11645. (match t
  11646. [`(Vector ,ts ...)
  11647. (values (Prim 'vector-length (list e^)) 'Integer)]
  11648. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11649. [(Prim 'eq? (list arg1 arg2))
  11650. (define-values (e1 t1) (recur arg1))
  11651. (define-values (e2 t2) (recur arg2))
  11652. (match* (t1 t2)
  11653. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11654. [(other wise) (check-type-equal? t1 t2 e)])
  11655. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11656. [else ((super type-check-exp env) e)]
  11657. )))
  11658. ))
  11659. (define (type-check-Lvec p)
  11660. (send (new type-check-Lvec-class) type-check-program p))
  11661. \end{lstlisting}
  11662. \fi}
  11663. {\if\edition\pythonEd\pythonColor
  11664. \begin{lstlisting}
  11665. class TypeCheckLtup(TypeCheckLwhile):
  11666. def type_check_exp(self, e, env):
  11667. match e:
  11668. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11669. l = self.type_check_exp(left, env)
  11670. r = self.type_check_exp(right, env)
  11671. check_type_equal(l, r, e)
  11672. return bool
  11673. case Tuple(es, Load()):
  11674. ts = [self.type_check_exp(e, env) for e in es]
  11675. e.has_type = TupleType(ts)
  11676. return e.has_type
  11677. case Subscript(tup, Constant(i), Load()):
  11678. tup_ty = self.type_check_exp(tup, env)
  11679. i_ty = self.type_check_exp(Constant(i), env)
  11680. check_type_equal(i_ty, int, i)
  11681. match tup_ty:
  11682. case TupleType(ts):
  11683. return ts[i]
  11684. case _:
  11685. raise Exception('expected a tuple, not ' + repr(tup_ty))
  11686. case _:
  11687. return super().type_check_exp(e, env)
  11688. \end{lstlisting}
  11689. \fi}
  11690. \end{tcolorbox}
  11691. \caption{Type checker for the \LangVec{} language.}
  11692. \label{fig:type-check-Lvec}
  11693. \end{figure}
  11694. \section{Garbage Collection}
  11695. \label{sec:GC}
  11696. Garbage collection is a runtime technique for reclaiming space on the
  11697. heap that will not be used in the future of the running program. We
  11698. use the term \emph{object}\index{subject}{object} to refer to any
  11699. value that is stored in the heap, which for now includes only
  11700. tuples.%
  11701. %
  11702. \footnote{The term \emph{object} as it is used in the context of
  11703. object-oriented programming has a more specific meaning than the
  11704. way in which we use the term here.}
  11705. %
  11706. Unfortunately, it is impossible to know precisely which objects will
  11707. be accessed in the future and which will not. Instead, garbage
  11708. collectors overapproximate the set of objects that will be accessed by
  11709. identifying which objects can possibly be accessed. The running
  11710. program can directly access objects that are in registers and on the
  11711. procedure call stack. It can also transitively access the elements of
  11712. tuples, starting with a tuple whose address is in a register or on the
  11713. procedure call stack. We define the \emph{root
  11714. set}\index{subject}{root set} to be all the tuple addresses that are
  11715. in registers or on the procedure call stack. We define the \emph{live
  11716. objects}\index{subject}{live objects} to be the objects that are
  11717. reachable from the root set. Garbage collectors reclaim the space that
  11718. is allocated to objects that are no longer live. \index{subject}{allocate}
  11719. That means that some objects may not get reclaimed as soon as they could be,
  11720. but at least
  11721. garbage collectors do not reclaim the space dedicated to objects that
  11722. will be accessed in the future! The programmer can influence which
  11723. objects get reclaimed by causing them to become unreachable.
  11724. So the goal of the garbage collector is twofold:
  11725. \begin{enumerate}
  11726. \item to preserve all the live objects, and
  11727. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11728. \end{enumerate}
  11729. \subsection{Two-Space Copying Collector}
  11730. Here we study a relatively simple algorithm for garbage collection
  11731. that is the basis of many state-of-the-art garbage
  11732. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11733. particular, we describe a two-space copying
  11734. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11735. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11736. collector} \index{subject}{two-space copying collector}
  11737. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11738. what happens in a two-space collector, showing two time steps, prior
  11739. to garbage collection (on the top) and after garbage collection (on
  11740. the bottom). In a two-space collector, the heap is divided into two
  11741. parts named the FromSpace\index{subject}{FromSpace} and the
  11742. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11743. FromSpace until there is not enough room for the next allocation
  11744. request. At that point, the garbage collector goes to work to make
  11745. room for the next allocation.
  11746. A copying collector makes more room by copying all the live objects
  11747. from the FromSpace into the ToSpace and then performs a sleight of
  11748. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11749. as the new ToSpace. In the example shown in
  11750. figure~\ref{fig:copying-collector}, the root set consists of three
  11751. pointers, one in a register and two on the stack. All the live
  11752. objects have been copied to the ToSpace (the right-hand side of
  11753. figure~\ref{fig:copying-collector}) in a way that preserves the
  11754. pointer relationships. For example, the pointer in the register still
  11755. points to a tuple that in turn points to two other tuples. There are
  11756. four tuples that are not reachable from the root set and therefore do
  11757. not get copied into the ToSpace.
  11758. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11759. created by a well-typed program in \LangVec{} because it contains a
  11760. cycle. However, creating cycles will be possible once we get to
  11761. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11762. to deal with cycles to begin with, so we will not need to revisit this
  11763. issue.
  11764. \begin{figure}[tbp]
  11765. \centering
  11766. \begin{tcolorbox}[colback=white]
  11767. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11768. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11769. \\[5ex]
  11770. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11771. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11772. \end{tcolorbox}
  11773. \caption{A copying collector in action.}
  11774. \label{fig:copying-collector}
  11775. \end{figure}
  11776. \subsection{Graph Copying via Cheney's Algorithm}
  11777. \label{sec:cheney}
  11778. \index{subject}{Cheney's algorithm}
  11779. Let us take a closer look at the copying of the live objects. The
  11780. allocated\index{subject}{allocate} objects and pointers can be viewed
  11781. as a graph, and we need to copy the part of the graph that is
  11782. reachable from the root set. To make sure that we copy all the
  11783. reachable vertices in the graph, we need an exhaustive graph traversal
  11784. algorithm, such as depth-first search or breadth-first
  11785. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11786. take into account the possibility of cycles by marking which vertices
  11787. have already been visited, so to ensure termination of the
  11788. algorithm. These search algorithms also use a data structure such as a
  11789. stack or queue as a to-do list to keep track of the vertices that need
  11790. to be visited. We use breadth-first search and a trick due to
  11791. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11792. copying tuples into the ToSpace.
  11793. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11794. copy progresses. The queue is represented by a chunk of contiguous
  11795. memory at the beginning of the ToSpace, using two pointers to track
  11796. the front and the back of the queue, called the \emph{scan pointer}
  11797. and the \emph{free pointer}, respectively. The algorithm starts by
  11798. copying all tuples that are immediately reachable from the root set
  11799. into the ToSpace to form the initial queue. When we copy a tuple, we
  11800. mark the old tuple to indicate that it has been visited. We discuss
  11801. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11802. that any pointers inside the copied tuples in the queue still point
  11803. back to the FromSpace. Once the initial queue has been created, the
  11804. algorithm enters a loop in which it repeatedly processes the tuple at
  11805. the front of the queue and pops it off the queue. To process a tuple,
  11806. the algorithm copies all the objects that are directly reachable from it
  11807. to the ToSpace, placing them at the back of the queue. The algorithm
  11808. then updates the pointers in the popped tuple so that they point to the
  11809. newly copied objects.
  11810. \begin{figure}[tbp]
  11811. \centering
  11812. \begin{tcolorbox}[colback=white]
  11813. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11814. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11815. \end{tcolorbox}
  11816. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11817. \label{fig:cheney}
  11818. \end{figure}
  11819. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11820. tuple whose second element is $42$ to the back of the queue. The other
  11821. pointer goes to a tuple that has already been copied, so we do not
  11822. need to copy it again, but we do need to update the pointer to the new
  11823. location. This can be accomplished by storing a \emph{forwarding
  11824. pointer}\index{subject}{forwarding pointer} to the new location in the
  11825. old tuple, when we initially copied the tuple into the
  11826. ToSpace. This completes one step of the algorithm. The algorithm
  11827. continues in this way until the queue is empty; that is, when the scan
  11828. pointer catches up with the free pointer.
  11829. \subsection{Data Representation}
  11830. \label{sec:data-rep-gc}
  11831. The garbage collector places some requirements on the data
  11832. representations used by our compiler. First, the garbage collector
  11833. needs to distinguish between pointers and other kinds of data such as
  11834. integers. The following are three ways to accomplish this:
  11835. \begin{enumerate}
  11836. \item Attach a tag to each object that identifies what type of
  11837. object it is~\citep{McCarthy:1960dz}.
  11838. \item Store different types of objects in different
  11839. regions~\citep{Steele:1977ab}.
  11840. \item Use type information from the program to either (a) generate
  11841. type-specific code for collecting, or (b) generate tables that
  11842. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11843. \end{enumerate}
  11844. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11845. need to tag objects in any case, so option 1 is a natural choice for those
  11846. languages. However, \LangVec{} is a statically typed language, so it
  11847. would be unfortunate to require tags on every object, especially small
  11848. and pervasive objects like integers and Booleans. Option 3 is the
  11849. best-performing choice for statically typed languages, but it comes with
  11850. a relatively high implementation complexity. To keep this chapter
  11851. within a reasonable scope of complexity, we recommend a combination of options
  11852. 1 and 2, using separate strategies for the stack and the heap.
  11853. Regarding the stack, we recommend using a separate stack for pointers,
  11854. which we call the \emph{root stack}\index{subject}{root stack}
  11855. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11856. That is, when a local variable needs to be spilled and is of type
  11857. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11858. root stack instead of putting it on the procedure call
  11859. stack. Furthermore, we always spill tuple-typed variables if they are
  11860. live during a call to the collector, thereby ensuring that no pointers
  11861. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11862. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11863. contrasts it with the data layout using a root stack. The root stack
  11864. contains the two pointers from the regular stack and also the pointer
  11865. in the second register.
  11866. \begin{figure}[tbp]
  11867. \centering
  11868. \begin{tcolorbox}[colback=white]
  11869. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11870. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11871. \end{tcolorbox}
  11872. \caption{Maintaining a root stack to facilitate garbage collection.}
  11873. \label{fig:shadow-stack}
  11874. \end{figure}
  11875. The problem of distinguishing between pointers and other kinds of data
  11876. also arises inside each tuple on the heap. We solve this problem by
  11877. attaching a tag, an extra 64 bits, to each
  11878. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11879. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11880. Note that we have drawn the bits in a big-endian way, from right to left,
  11881. with bit location 0 (the least significant bit) on the far right,
  11882. which corresponds to the direction of the x86 shifting instructions
  11883. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11884. is dedicated to specifying which elements of the tuple are pointers,
  11885. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11886. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11887. data. The pointer mask starts at bit location 7. We limit tuples to a
  11888. maximum size of fifty elements, so we need 50 bits for the pointer
  11889. mask.%
  11890. %
  11891. \footnote{A production-quality compiler would handle
  11892. arbitrarily sized tuples and use a more complex approach.}
  11893. %
  11894. The tag also contains two other pieces of information. The length of
  11895. the tuple (number of elements) is stored in bits at locations 1 through
  11896. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11897. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11898. has not yet been copied. If the bit has value 0, then the entire tag
  11899. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11900. zero in any case, because our tuples are 8-byte aligned.)
  11901. \begin{figure}[tbp]
  11902. \centering
  11903. \begin{tcolorbox}[colback=white]
  11904. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11905. \end{tcolorbox}
  11906. \caption{Representation of tuples in the heap.}
  11907. \label{fig:tuple-rep}
  11908. \end{figure}
  11909. \subsection{Implementation of the Garbage Collector}
  11910. \label{sec:organize-gz}
  11911. \index{subject}{prelude}
  11912. An implementation of the copying collector is provided in the
  11913. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11914. interface to the garbage collector that is used by the compiler. The
  11915. \code{initialize} function creates the FromSpace, ToSpace, and root
  11916. stack and should be called in the prelude of the \code{main}
  11917. function. The arguments of \code{initialize} are the root stack size
  11918. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11919. good choice for both. The \code{initialize} function puts the address
  11920. of the beginning of the FromSpace into the global variable
  11921. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11922. the address that is one past the last element of the FromSpace. We use
  11923. half-open intervals to represent chunks of
  11924. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11925. points to the first element of the root stack.
  11926. As long as there is room left in the FromSpace, your generated code
  11927. can allocate\index{subject}{allocate} tuples simply by moving the
  11928. \code{free\_ptr} forward.
  11929. %
  11930. The amount of room left in the FromSpace is the difference between the
  11931. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11932. function should be called when there is not enough room left in the
  11933. FromSpace for the next allocation. The \code{collect} function takes
  11934. a pointer to the current top of the root stack (one past the last item
  11935. that was pushed) and the number of bytes that need to be
  11936. allocated. The \code{collect} function performs the copying collection
  11937. and leaves the heap in a state such that there is enough room for the
  11938. next allocation.
  11939. \begin{figure}[tbp]
  11940. \begin{tcolorbox}[colback=white]
  11941. \begin{lstlisting}
  11942. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11943. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11944. int64_t* free_ptr;
  11945. int64_t* fromspace_begin;
  11946. int64_t* fromspace_end;
  11947. int64_t** rootstack_begin;
  11948. \end{lstlisting}
  11949. \end{tcolorbox}
  11950. \caption{The compiler's interface to the garbage collector.}
  11951. \label{fig:gc-header}
  11952. \end{figure}
  11953. %% \begin{exercise}
  11954. %% In the file \code{runtime.c} you will find the implementation of
  11955. %% \code{initialize} and a partial implementation of \code{collect}.
  11956. %% The \code{collect} function calls another function, \code{cheney},
  11957. %% to perform the actual copy, and that function is left to the reader
  11958. %% to implement. The following is the prototype for \code{cheney}.
  11959. %% \begin{lstlisting}
  11960. %% static void cheney(int64_t** rootstack_ptr);
  11961. %% \end{lstlisting}
  11962. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11963. %% rootstack (which is an array of pointers). The \code{cheney} function
  11964. %% also communicates with \code{collect} through the global
  11965. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11966. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11967. %% the ToSpace:
  11968. %% \begin{lstlisting}
  11969. %% static int64_t* tospace_begin;
  11970. %% static int64_t* tospace_end;
  11971. %% \end{lstlisting}
  11972. %% The job of the \code{cheney} function is to copy all the live
  11973. %% objects (reachable from the root stack) into the ToSpace, update
  11974. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11975. %% update the root stack so that it points to the objects in the
  11976. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11977. %% and ToSpace.
  11978. %% \end{exercise}
  11979. The introduction of garbage collection has a nontrivial impact on our
  11980. compiler passes. We introduce a new compiler pass named
  11981. \code{expose\_allocation} that elaborates the code for allocating
  11982. tuples. We also make significant changes to
  11983. \code{select\_instructions}, \code{build\_interference},
  11984. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11985. make minor changes in several more passes.
  11986. The following program serves as our running example. It creates
  11987. two tuples, one nested inside the other. Both tuples have length
  11988. one. The program accesses the element in the inner tuple.
  11989. % tests/vectors_test_17.rkt
  11990. {\if\edition\racketEd
  11991. \begin{lstlisting}
  11992. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11993. \end{lstlisting}
  11994. \fi}
  11995. % tests/tuple/get_get.py
  11996. {\if\edition\pythonEd\pythonColor
  11997. \begin{lstlisting}
  11998. v1 = (42,)
  11999. v2 = (v1,)
  12000. print(v2[0][0])
  12001. \end{lstlisting}
  12002. \fi}
  12003. %% {\if\edition\racketEd
  12004. %% \section{Shrink}
  12005. %% \label{sec:shrink-Lvec}
  12006. %% Recall that the \code{shrink} pass translates the primitives operators
  12007. %% into a smaller set of primitives.
  12008. %% %
  12009. %% This pass comes after type checking, and the type checker adds a
  12010. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  12011. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  12012. %% \fi}
  12013. \section{Expose Allocation}
  12014. \label{sec:expose-allocation}
  12015. The pass \code{expose\_allocation} lowers tuple creation into making a
  12016. conditional call to the collector followed by allocating the
  12017. appropriate amount of memory and initializing it. We choose to place
  12018. the \code{expose\_allocation} pass before
  12019. \code{remove\_complex\_operands} because it generates code that
  12020. contains complex operands. However, with some care it can also be
  12021. placed after \code{remove\_complex\_operands}, which would simplify
  12022. tuple creation by removing the need to assign the initializing
  12023. expressions to temporary variables (see below).
  12024. The output of \code{expose\_allocation} is a language \LangAlloc{}
  12025. that replaces tuple creation with new forms that we use in the
  12026. translation of tuple creation\index{subject}{Lalloc@\LangAlloc{}}.
  12027. %
  12028. {\if\edition\racketEd
  12029. \[
  12030. \begin{array}{lcl}
  12031. \Exp &::=& (\key{collect} \,\itm{int})
  12032. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  12033. \MID (\key{global-value} \,\itm{name})
  12034. \end{array}
  12035. \]
  12036. \fi}
  12037. {\if\edition\pythonEd\pythonColor
  12038. \[
  12039. %% \begin{array}{lcl}
  12040. %% \Exp &::=& \key{collect}(\itm{int})
  12041. %% \MID \key{allocate}(\itm{int},\itm{type})
  12042. %% \MID \key{global\_value}(\itm{name}) \\
  12043. %% \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  12044. %% \end{array}
  12045. \begin{array}{rcl}
  12046. \Exp &::=& \COLLECT{\Int} \MID \ALLOCATE{\Int}{\Type} \\
  12047. &\MID& \GLOBALVALUE{\Var} \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  12048. \Stmt{} &::=& \ASSIGN{\PUT{\Exp}{\itm{int}}}{\Exp}
  12049. \end{array}
  12050. \]
  12051. \fi}
  12052. %
  12053. The \COLLECT{$n$} form runs the garbage collector, requesting that
  12054. there be $n$ bytes ready to be allocated. During instruction
  12055. selection\index{subject}{instruction selection}, the \COLLECT{$n$}
  12056. form will become a call to the \code{collect} function in
  12057. \code{runtime.c}.
  12058. %
  12059. The \ALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  12060. space at the front for the 64-bit tag), but the elements are not
  12061. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  12062. of the tuple:
  12063. %
  12064. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  12065. %
  12066. where $\Type_i$ is the type of the $i$th element.
  12067. %
  12068. The \GLOBALVALUE{\itm{name}} form reads the value of a global
  12069. variable, such as \code{free\_ptr}.
  12070. %
  12071. \python{We have already seen the \BEGIN{\itm{stmt}$^{*}$}{\itm{exp}} form
  12072. in section~\ref{sec:remove-complex-opera-Lif}.}
  12073. \racket{
  12074. The type information that you need for \ALLOCATE{$n$}{$\itm{type}$}
  12075. can be obtained by running the
  12076. \code{type-check-Lvec-has-type} type checker immediately before the
  12077. \code{expose\_allocation} pass. This version of the type checker
  12078. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  12079. around each tuple creation. The concrete syntax
  12080. for \code{HasType} is \code{has-type}.}
  12081. The following shows the transformation of tuple creation into (1) a
  12082. sequence of temporary variable bindings for the initializing
  12083. expressions, (2) a conditional call to \code{collect}, (3) a call to
  12084. \code{allocate}, and (4) the initialization of the tuple. The
  12085. \itm{len} placeholder refers to the length of the tuple, and
  12086. \itm{bytes} is the total number of bytes that need to be allocated for
  12087. the tuple, which is 8 for the tag plus \itm{len} times 8.
  12088. %
  12089. \python{The \itm{type} needed for the second argument of the
  12090. \code{allocate} form can be obtained from the \code{has\_type} field
  12091. of the tuple AST node, which is stored there by running the type
  12092. checker for \LangVec{} immediately before this pass.}
  12093. %
  12094. \begin{center}
  12095. \begin{minipage}{\textwidth}
  12096. {\if\edition\racketEd
  12097. \begin{lstlisting}
  12098. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  12099. |$\Longrightarrow$|
  12100. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  12101. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  12102. (global-value fromspace_end))
  12103. (void)
  12104. (collect |\itm{bytes}|))])
  12105. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  12106. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  12107. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  12108. |$v$|) ... )))) ...)
  12109. \end{lstlisting}
  12110. \fi}
  12111. {\if\edition\pythonEd\pythonColor
  12112. \begin{lstlisting}
  12113. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  12114. |$\Longrightarrow$|
  12115. begin:
  12116. |$x_0$| = |$e_0$|
  12117. |$\vdots$|
  12118. |$x_{n-1}$| = |$e_{n-1}$|
  12119. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12120. 0
  12121. else:
  12122. collect(|\itm{bytes}|)
  12123. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12124. |$v$|[0] = |$x_0$|
  12125. |$\vdots$|
  12126. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12127. |$v$|
  12128. \end{lstlisting}
  12129. \fi}
  12130. \end{minipage}
  12131. \end{center}
  12132. %
  12133. \noindent The sequencing of the initializing expressions
  12134. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12135. they may trigger garbage collection and we cannot have an allocated
  12136. but uninitialized tuple on the heap during a collection.
  12137. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12138. \code{expose\_allocation} pass on our running example.
  12139. \begin{figure}[tbp]
  12140. \begin{tcolorbox}[colback=white]
  12141. % tests/s2_17.rkt
  12142. {\if\edition\racketEd
  12143. \begin{lstlisting}
  12144. (vector-ref
  12145. (vector-ref
  12146. (let ([vecinit6
  12147. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12148. (global-value fromspace_end))
  12149. (void)
  12150. (collect 16))])
  12151. (let ([alloc2 (allocate 1 (Vector Integer))])
  12152. (let ([_3 (vector-set! alloc2 0 42)])
  12153. alloc2)))])
  12154. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12155. (global-value fromspace_end))
  12156. (void)
  12157. (collect 16))])
  12158. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12159. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12160. alloc5))))
  12161. 0)
  12162. 0)
  12163. \end{lstlisting}
  12164. \fi}
  12165. {\if\edition\pythonEd\pythonColor
  12166. \begin{lstlisting}
  12167. v1 = begin:
  12168. init.514 = 42
  12169. if (free_ptr + 16) < fromspace_end:
  12170. else:
  12171. collect(16)
  12172. alloc.513 = allocate(1,tuple[int])
  12173. alloc.513[0] = init.514
  12174. alloc.513
  12175. v2 = begin:
  12176. init.516 = v1
  12177. if (free_ptr + 16) < fromspace_end:
  12178. else:
  12179. collect(16)
  12180. alloc.515 = allocate(1,tuple[tuple[int]])
  12181. alloc.515[0] = init.516
  12182. alloc.515
  12183. print(v2[0][0])
  12184. \end{lstlisting}
  12185. \fi}
  12186. \end{tcolorbox}
  12187. \caption{Output of the \code{expose\_allocation} pass.}
  12188. \label{fig:expose-alloc-output}
  12189. \end{figure}
  12190. \section{Remove Complex Operands}
  12191. \label{sec:remove-complex-opera-Lvec}
  12192. {\if\edition\racketEd
  12193. %
  12194. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12195. should be treated as complex operands.
  12196. %
  12197. \fi}
  12198. %
  12199. {\if\edition\pythonEd\pythonColor
  12200. %
  12201. The expressions \code{allocate}, \code{begin},
  12202. and tuple access should be treated as complex operands. The
  12203. subexpressions of tuple access must be atomic.
  12204. The \code{global\_value} AST node is atomic.
  12205. %
  12206. \fi}
  12207. %% A new case for
  12208. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12209. %% handled carefully to prevent the \code{Prim} node from being separated
  12210. %% from its enclosing \code{HasType}.
  12211. Figure~\ref{fig:Lvec-anf-syntax}
  12212. shows the grammar for the output language \LangAllocANF{} of this
  12213. pass, which is \LangAlloc{} in monadic normal form.
  12214. \newcommand{\LtupMonadASTRacket}{
  12215. \begin{array}{rcl}
  12216. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12217. \MID \GLOBALVALUE{\Var}
  12218. \end{array}
  12219. }
  12220. \newcommand{\LtupMonadASTPython}{
  12221. \begin{array}{rcl}
  12222. \Atm &::=& \GLOBALVALUE{\Var} \\
  12223. \Exp &::=& \GET{\Atm}{\Atm}
  12224. \MID \LEN{\Atm}\\
  12225. &\MID& \ALLOCATE{\Int}{\Type}\\
  12226. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12227. &\MID& \COLLECT{\Int}
  12228. \end{array}
  12229. }
  12230. \begin{figure}[tp]
  12231. \centering
  12232. \begin{tcolorbox}[colback=white]
  12233. \small
  12234. {\if\edition\racketEd
  12235. \[
  12236. \begin{array}{l}
  12237. \gray{\LvarMonadASTRacket} \\ \hline
  12238. \gray{\LifMonadASTRacket} \\ \hline
  12239. \gray{\LwhileMonadASTRacket} \\ \hline
  12240. \LtupMonadASTRacket \\
  12241. \begin{array}{rcl}
  12242. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12243. \end{array}
  12244. \end{array}
  12245. \]
  12246. \fi}
  12247. {\if\edition\pythonEd\pythonColor
  12248. \[
  12249. \begin{array}{l}
  12250. \gray{\LvarMonadASTPython} \\ \hline
  12251. \gray{\LifMonadASTPython} \\ \hline
  12252. \gray{\LwhileMonadASTPython} \\ \hline
  12253. \LtupMonadASTPython \\
  12254. \begin{array}{rcl}
  12255. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12256. \end{array}
  12257. \end{array}
  12258. \]
  12259. \fi}
  12260. \end{tcolorbox}
  12261. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12262. \label{fig:Lvec-anf-syntax}
  12263. \index{subject}{Ltupmon@\LangAllocANF{} abstract syntax}
  12264. \end{figure}
  12265. \section{Explicate Control and the \LangCVec{} Language}
  12266. \label{sec:explicate-control-r3}
  12267. \newcommand{\CtupASTRacket}{
  12268. \begin{array}{lcl}
  12269. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12270. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12271. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12272. &\MID& \VECLEN{\Atm} \\
  12273. &\MID& \GLOBALVALUE{\Var} \\
  12274. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12275. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12276. \end{array}
  12277. }
  12278. \newcommand{\CtupASTPython}{
  12279. \begin{array}{lcl}
  12280. \Atm &::=& \GLOBALVALUE{\Var} \\
  12281. \Exp &::=& \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12282. &\MID& \LEN{\Atm} \\
  12283. \Stmt &::=& \COLLECT{\Int}
  12284. \MID \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12285. \end{array}
  12286. }
  12287. \begin{figure}[tp]
  12288. \begin{tcolorbox}[colback=white]
  12289. \small
  12290. {\if\edition\racketEd
  12291. \[
  12292. \begin{array}{l}
  12293. \gray{\CvarASTRacket} \\ \hline
  12294. \gray{\CifASTRacket} \\ \hline
  12295. \gray{\CloopASTRacket} \\ \hline
  12296. \CtupASTRacket \\
  12297. \begin{array}{lcl}
  12298. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12299. \end{array}
  12300. \end{array}
  12301. \]
  12302. \fi}
  12303. {\if\edition\pythonEd\pythonColor
  12304. \[
  12305. \begin{array}{l}
  12306. \gray{\CifASTPython} \\ \hline
  12307. \CtupASTPython \\
  12308. \begin{array}{lcl}
  12309. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12310. \end{array}
  12311. \end{array}
  12312. \]
  12313. \fi}
  12314. \end{tcolorbox}
  12315. \caption{The abstract syntax of \LangCVec{}, extending
  12316. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12317. (figure~\ref{fig:c1-syntax})}.}
  12318. \label{fig:c2-syntax}
  12319. \index{subject}{Cvec@\LangCVec{} abstract syntax}
  12320. \end{figure}
  12321. The output of \code{explicate\_control} is a program in the
  12322. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12323. shows the definition of the abstract syntax.
  12324. %
  12325. %% \racket{(The concrete syntax is defined in
  12326. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12327. %
  12328. The new expressions of \LangCVec{} include \key{allocate},
  12329. %
  12330. \racket{\key{vector-ref}, and \key{vector-set!},}
  12331. %
  12332. \python{accessing tuple elements,}
  12333. %
  12334. and \key{global\_value}.
  12335. %
  12336. \python{\LangCVec{} also includes the \code{collect} statement and
  12337. assignment to a tuple element.}
  12338. %
  12339. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12340. %
  12341. The \code{explicate\_control} pass can treat these new forms much like
  12342. the other forms that we've already encountered. The output of the
  12343. \code{explicate\_control} pass on the running example is shown on the
  12344. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12345. section.
  12346. \section{Select Instructions and the \LangXGlobal{} Language}
  12347. \label{sec:select-instructions-gc}
  12348. \index{subject}{select instructions}
  12349. %% void (rep as zero)
  12350. %% allocate
  12351. %% collect (callq collect)
  12352. %% vector-ref
  12353. %% vector-set!
  12354. %% vector-length
  12355. %% global (postpone)
  12356. In this pass we generate x86 code for most of the new operations that
  12357. are needed to compile tuples, including \code{Allocate},
  12358. \code{Collect}, accessing tuple elements, and the \code{Is}
  12359. comparison.
  12360. %
  12361. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12362. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12363. \ref{fig:x86-2}). \index{subject}{x86}
  12364. The tuple read and write forms translate into \code{movq}
  12365. instructions. (The $+1$ in the offset serves to move past the tag at the
  12366. beginning of the tuple representation.)
  12367. %
  12368. \begin{center}
  12369. \begin{minipage}{\textwidth}
  12370. {\if\edition\racketEd
  12371. \begin{lstlisting}
  12372. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12373. |$\Longrightarrow$|
  12374. movq |$\itm{tup}'$|, %r11
  12375. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12376. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12377. |$\Longrightarrow$|
  12378. movq |$\itm{tup}'$|, %r11
  12379. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12380. movq $0, |$\itm{lhs'}$|
  12381. \end{lstlisting}
  12382. \fi}
  12383. {\if\edition\pythonEd\pythonColor
  12384. \begin{lstlisting}
  12385. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12386. |$\Longrightarrow$|
  12387. movq |$\itm{tup}'$|, %r11
  12388. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12389. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12390. |$\Longrightarrow$|
  12391. movq |$\itm{tup}'$|, %r11
  12392. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12393. \end{lstlisting}
  12394. \fi}
  12395. \end{minipage}
  12396. \end{center}
  12397. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12398. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12399. are obtained by translating from \LangCVec{} to x86.
  12400. %
  12401. The move of $\itm{tup}'$ to
  12402. register \code{r11} ensures that the offset expression
  12403. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12404. removing \code{r11} from consideration by the register allocator.
  12405. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12406. \code{rax}. Then the generated code for tuple assignment would be
  12407. \begin{lstlisting}
  12408. movq |$\itm{tup}'$|, %rax
  12409. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12410. \end{lstlisting}
  12411. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12412. \code{patch\_instructions} would insert a move through \code{rax}
  12413. as follows:
  12414. \begin{lstlisting}
  12415. movq |$\itm{tup}'$|, %rax
  12416. movq |$\itm{rhs}'$|, %rax
  12417. movq %rax, |$8(n+1)$|(%rax)
  12418. \end{lstlisting}
  12419. However, this sequence of instructions does not work because we're
  12420. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12421. $\itm{rhs}'$) at the same time!
  12422. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12423. be translated into a sequence of instructions that read the tag of the
  12424. tuple and extract the 6 bits that represent the tuple length, which
  12425. are the bits starting at index 1 and going up to and including bit 6.
  12426. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12427. (shift right) can be used to accomplish this.
  12428. We compile the \code{allocate} form to operations on the
  12429. \code{free\_ptr}, as shown next. This approach is called
  12430. \emph{inline allocation} because it implements allocation without a
  12431. function call by simply incrementing the allocation pointer. It is much
  12432. more efficient than calling a function for each allocation. The
  12433. address in the \code{free\_ptr} is the next free address in the
  12434. FromSpace, so we copy it into \code{r11} and then move it forward by
  12435. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12436. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12437. the tag. We then initialize the \itm{tag} and finally copy the
  12438. address in \code{r11} to the left-hand side. Refer to
  12439. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12440. %
  12441. \racket{We recommend using the Racket operations
  12442. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12443. during compilation.}
  12444. %
  12445. \python{We recommend using the bitwise-or operator \code{|} and the
  12446. shift-left operator \code{<<} to compute the tag during
  12447. compilation.}
  12448. %
  12449. The type annotation in the \code{allocate} form is used to determine
  12450. the pointer mask region of the tag.
  12451. %
  12452. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12453. address of the \code{free\_ptr} global variable using a special
  12454. instruction-pointer-relative addressing mode of the x86-64 processor.
  12455. In particular, the assembler computes the distance $d$ between the
  12456. address of \code{free\_ptr} and where the \code{rip} would be at that
  12457. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12458. \code{$d$(\%rip)}, which at runtime will compute the address of
  12459. \code{free\_ptr}.
  12460. %
  12461. {\if\edition\racketEd
  12462. \begin{lstlisting}
  12463. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12464. |$\Longrightarrow$|
  12465. movq free_ptr(%rip), %r11
  12466. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12467. movq $|$\itm{tag}$|, 0(%r11)
  12468. movq %r11, |$\itm{lhs}'$|
  12469. \end{lstlisting}
  12470. \fi}
  12471. {\if\edition\pythonEd\pythonColor
  12472. \begin{lstlisting}
  12473. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12474. |$\Longrightarrow$|
  12475. movq free_ptr(%rip), %r11
  12476. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12477. movq $|$\itm{tag}$|, 0(%r11)
  12478. movq %r11, |$\itm{lhs}'$|
  12479. \end{lstlisting}
  12480. \fi}
  12481. %
  12482. The \code{collect} form is compiled to a call to the \code{collect}
  12483. function in the runtime. The arguments to \code{collect} are (1) the
  12484. top of the root stack, and (2) the number of bytes that need to be
  12485. allocated. We use another dedicated register, \code{r15}, to store
  12486. the pointer to the top of the root stack. Therefore \code{r15} is not
  12487. available for use by the register allocator.
  12488. %
  12489. {\if\edition\racketEd
  12490. \begin{lstlisting}
  12491. (collect |$\itm{bytes}$|)
  12492. |$\Longrightarrow$|
  12493. movq %r15, %rdi
  12494. movq $|\itm{bytes}|, %rsi
  12495. callq collect
  12496. \end{lstlisting}
  12497. \fi}
  12498. {\if\edition\pythonEd\pythonColor
  12499. \begin{lstlisting}
  12500. collect(|$\itm{bytes}$|)
  12501. |$\Longrightarrow$|
  12502. movq %r15, %rdi
  12503. movq $|\itm{bytes}|, %rsi
  12504. callq collect
  12505. \end{lstlisting}
  12506. \fi}
  12507. {\if\edition\pythonEd\pythonColor
  12508. The \code{is} comparison is compiled similarly to the other comparison
  12509. operators, using the \code{cmpq} instruction. Because the value of a
  12510. tuple is its address, we can translate \code{is} into a simple check
  12511. for equality using the \code{e} condition code. \\
  12512. \begin{tabular}{lll}
  12513. \begin{minipage}{0.4\textwidth}
  12514. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12515. \end{minipage}
  12516. &
  12517. $\Rightarrow$
  12518. &
  12519. \begin{minipage}{0.4\textwidth}
  12520. \begin{lstlisting}
  12521. cmpq |$\Arg_2$|, |$\Arg_1$|
  12522. sete %al
  12523. movzbq %al, |$\Var$|
  12524. \end{lstlisting}
  12525. \end{minipage}
  12526. \end{tabular}
  12527. \fi}
  12528. \newcommand{\GrammarXGlobal}{
  12529. \begin{array}{lcl}
  12530. \Arg &::=& \itm{label} \key{(\%rip)}
  12531. \end{array}
  12532. }
  12533. \newcommand{\ASTXGlobalRacket}{
  12534. \begin{array}{lcl}
  12535. \Arg &::=& \GLOBAL{\itm{label}}
  12536. \end{array}
  12537. }
  12538. \begin{figure}[tp]
  12539. \begin{tcolorbox}[colback=white]
  12540. {\if\edition\racketEd
  12541. \[
  12542. \begin{array}{l}
  12543. \gray{\GrammarXIntRacket} \\ \hline
  12544. \gray{\GrammarXIfRacket} \\ \hline
  12545. \GrammarXGlobal \\
  12546. \begin{array}{lcl}
  12547. \LangXGlobalM{} &::= & \key{.globl main} \\
  12548. & & \key{main:} \; \Instr^{*}
  12549. \end{array}
  12550. \end{array}
  12551. \]
  12552. \fi}
  12553. {\if\edition\pythonEd\pythonColor
  12554. \[
  12555. \begin{array}{l}
  12556. \gray{\GrammarXIntPython} \\ \hline
  12557. \gray{\GrammarXIfPython} \\ \hline
  12558. \GrammarXGlobal \\
  12559. \begin{array}{lcl}
  12560. \LangXGlobalM{} &::= & \key{.globl main} \\
  12561. & & \key{main:} \; \Instr^{*}
  12562. \end{array}
  12563. \end{array}
  12564. \]
  12565. \fi}
  12566. \end{tcolorbox}
  12567. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12568. \label{fig:x86-2-concrete}
  12569. \end{figure}
  12570. \begin{figure}[tp]
  12571. \begin{tcolorbox}[colback=white]
  12572. \small
  12573. {\if\edition\racketEd
  12574. \[
  12575. \begin{array}{l}
  12576. \gray{\ASTXIntRacket} \\ \hline
  12577. \gray{\ASTXIfRacket} \\ \hline
  12578. \ASTXGlobalRacket \\
  12579. \begin{array}{lcl}
  12580. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12581. \end{array}
  12582. \end{array}
  12583. \]
  12584. \fi}
  12585. {\if\edition\pythonEd\pythonColor
  12586. \[
  12587. \begin{array}{l}
  12588. \gray{\ASTXIntPython} \\ \hline
  12589. \gray{\ASTXIfPython} \\ \hline
  12590. \ASTXGlobalRacket \\
  12591. \begin{array}{lcl}
  12592. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12593. \end{array}
  12594. \end{array}
  12595. \]
  12596. \fi}
  12597. \end{tcolorbox}
  12598. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12599. \label{fig:x86-2}
  12600. \end{figure}
  12601. The definitions of the concrete and abstract syntax of the
  12602. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12603. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12604. of global variables.
  12605. %
  12606. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12607. \code{select\_instructions} pass on the running example.
  12608. \begin{figure}[tbp]
  12609. \centering
  12610. \begin{tcolorbox}[colback=white]
  12611. {\if\edition\racketEd
  12612. % tests/s2_17.rkt
  12613. \begin{tabular}{lll}
  12614. \begin{minipage}{0.5\textwidth}
  12615. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12616. start:
  12617. tmp9 = (global-value free_ptr);
  12618. tmp0 = (+ tmp9 16);
  12619. tmp1 = (global-value fromspace_end);
  12620. if (< tmp0 tmp1)
  12621. goto block0;
  12622. else
  12623. goto block1;
  12624. block0:
  12625. _4 = (void);
  12626. goto block9;
  12627. block1:
  12628. (collect 16)
  12629. goto block9;
  12630. block9:
  12631. alloc2 = (allocate 1 (Vector Integer));
  12632. _3 = (vector-set! alloc2 0 42);
  12633. vecinit6 = alloc2;
  12634. tmp2 = (global-value free_ptr);
  12635. tmp3 = (+ tmp2 16);
  12636. tmp4 = (global-value fromspace_end);
  12637. if (< tmp3 tmp4)
  12638. goto block7;
  12639. else
  12640. goto block8;
  12641. block7:
  12642. _8 = (void);
  12643. goto block6;
  12644. block8:
  12645. (collect 16)
  12646. goto block6;
  12647. block6:
  12648. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12649. _7 = (vector-set! alloc5 0 vecinit6);
  12650. tmp5 = (vector-ref alloc5 0);
  12651. return (vector-ref tmp5 0);
  12652. \end{lstlisting}
  12653. \end{minipage}
  12654. &$\Rightarrow$&
  12655. \begin{minipage}{0.4\textwidth}
  12656. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12657. start:
  12658. movq free_ptr(%rip), tmp9
  12659. movq tmp9, tmp0
  12660. addq $16, tmp0
  12661. movq fromspace_end(%rip), tmp1
  12662. cmpq tmp1, tmp0
  12663. jl block0
  12664. jmp block1
  12665. block0:
  12666. movq $0, _4
  12667. jmp block9
  12668. block1:
  12669. movq %r15, %rdi
  12670. movq $16, %rsi
  12671. callq collect
  12672. jmp block9
  12673. block9:
  12674. movq free_ptr(%rip), %r11
  12675. addq $16, free_ptr(%rip)
  12676. movq $3, 0(%r11)
  12677. movq %r11, alloc2
  12678. movq alloc2, %r11
  12679. movq $42, 8(%r11)
  12680. movq $0, _3
  12681. movq alloc2, vecinit6
  12682. movq free_ptr(%rip), tmp2
  12683. movq tmp2, tmp3
  12684. addq $16, tmp3
  12685. movq fromspace_end(%rip), tmp4
  12686. cmpq tmp4, tmp3
  12687. jl block7
  12688. jmp block8
  12689. block7:
  12690. movq $0, _8
  12691. jmp block6
  12692. block8:
  12693. movq %r15, %rdi
  12694. movq $16, %rsi
  12695. callq collect
  12696. jmp block6
  12697. block6:
  12698. movq free_ptr(%rip), %r11
  12699. addq $16, free_ptr(%rip)
  12700. movq $131, 0(%r11)
  12701. movq %r11, alloc5
  12702. movq alloc5, %r11
  12703. movq vecinit6, 8(%r11)
  12704. movq $0, _7
  12705. movq alloc5, %r11
  12706. movq 8(%r11), tmp5
  12707. movq tmp5, %r11
  12708. movq 8(%r11), %rax
  12709. jmp conclusion
  12710. \end{lstlisting}
  12711. \end{minipage}
  12712. \end{tabular}
  12713. \fi}
  12714. {\if\edition\pythonEd
  12715. % tests/tuple/get_get.py
  12716. \begin{tabular}{lll}
  12717. \begin{minipage}{0.5\textwidth}
  12718. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12719. start:
  12720. init.514 = 42
  12721. tmp.517 = free_ptr
  12722. tmp.518 = (tmp.517 + 16)
  12723. tmp.519 = fromspace_end
  12724. if tmp.518 < tmp.519:
  12725. goto block.529
  12726. else:
  12727. goto block.530
  12728. block.529:
  12729. goto block.528
  12730. block.530:
  12731. collect(16)
  12732. goto block.528
  12733. block.528:
  12734. alloc.513 = allocate(1,tuple[int])
  12735. alloc.513:tuple[int][0] = init.514
  12736. v1 = alloc.513
  12737. init.516 = v1
  12738. tmp.520 = free_ptr
  12739. tmp.521 = (tmp.520 + 16)
  12740. tmp.522 = fromspace_end
  12741. if tmp.521 < tmp.522:
  12742. goto block.526
  12743. else:
  12744. goto block.527
  12745. block.526:
  12746. goto block.525
  12747. block.527:
  12748. collect(16)
  12749. goto block.525
  12750. block.525:
  12751. alloc.515 = allocate(1,tuple[tuple[int]])
  12752. alloc.515:tuple[tuple[int]][0] = init.516
  12753. v2 = alloc.515
  12754. tmp.523 = v2[0]
  12755. tmp.524 = tmp.523[0]
  12756. print(tmp.524)
  12757. return 0
  12758. \end{lstlisting}
  12759. \end{minipage}
  12760. &$\Rightarrow$&
  12761. \begin{minipage}{0.4\textwidth}
  12762. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12763. start:
  12764. movq $42, init.514
  12765. movq free_ptr(%rip), tmp.517
  12766. movq tmp.517, tmp.518
  12767. addq $16, tmp.518
  12768. movq fromspace_end(%rip), tmp.519
  12769. cmpq tmp.519, tmp.518
  12770. jl block.529
  12771. jmp block.530
  12772. block.529:
  12773. jmp block.528
  12774. block.530:
  12775. movq %r15, %rdi
  12776. movq $16, %rsi
  12777. callq collect
  12778. jmp block.528
  12779. block.528:
  12780. movq free_ptr(%rip), %r11
  12781. addq $16, free_ptr(%rip)
  12782. movq $3, 0(%r11)
  12783. movq %r11, alloc.513
  12784. movq alloc.513, %r11
  12785. movq init.514, 8(%r11)
  12786. movq alloc.513, v1
  12787. movq v1, init.516
  12788. movq free_ptr(%rip), tmp.520
  12789. movq tmp.520, tmp.521
  12790. addq $16, tmp.521
  12791. movq fromspace_end(%rip), tmp.522
  12792. cmpq tmp.522, tmp.521
  12793. jl block.526
  12794. jmp block.527
  12795. block.526:
  12796. jmp block.525
  12797. block.527:
  12798. movq %r15, %rdi
  12799. movq $16, %rsi
  12800. callq collect
  12801. jmp block.525
  12802. block.525:
  12803. movq free_ptr(%rip), %r11
  12804. addq $16, free_ptr(%rip)
  12805. movq $131, 0(%r11)
  12806. movq %r11, alloc.515
  12807. movq alloc.515, %r11
  12808. movq init.516, 8(%r11)
  12809. movq alloc.515, v2
  12810. movq v2, %r11
  12811. movq 8(%r11), %r11
  12812. movq %r11, tmp.523
  12813. movq tmp.523, %r11
  12814. movq 8(%r11), %r11
  12815. movq %r11, tmp.524
  12816. movq tmp.524, %rdi
  12817. callq print_int
  12818. movq $0, %rax
  12819. jmp conclusion
  12820. \end{lstlisting}
  12821. \end{minipage}
  12822. \end{tabular}
  12823. \fi}
  12824. \end{tcolorbox}
  12825. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12826. \code{select\_instructions} (\emph{right}) on the running example.}
  12827. \label{fig:select-instr-output-gc}
  12828. \end{figure}
  12829. \clearpage
  12830. \section{Register Allocation}
  12831. \label{sec:reg-alloc-gc}
  12832. \index{subject}{register allocation}
  12833. As discussed previously in this chapter, the garbage collector needs to
  12834. access all the pointers in the root set, that is, all variables that
  12835. are tuples. It will be the responsibility of the register allocator
  12836. to make sure that
  12837. \begin{enumerate}
  12838. \item the root stack is used for spilling tuple-typed variables, and
  12839. \item if a tuple-typed variable is live during a call to the
  12840. collector, it must be spilled to ensure that it is visible to the
  12841. collector.
  12842. \end{enumerate}
  12843. The latter responsibility can be handled during construction of the
  12844. interference graph, by adding interference edges between the call-live
  12845. tuple-typed variables and all the callee-saved registers. (They
  12846. already interfere with the caller-saved registers.)
  12847. %
  12848. \racket{The type information for variables is in the \code{Program}
  12849. form, so we recommend adding another parameter to the
  12850. \code{build\_interference} function to communicate this alist.}
  12851. %
  12852. \python{The type information for variables is generated by the type
  12853. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12854. the \code{CProgram} AST mode. You'll need to propagate that
  12855. information so that it is available in this pass.}
  12856. The spilling of tuple-typed variables to the root stack can be handled
  12857. after graph coloring, in choosing how to assign the colors
  12858. (integers) to registers and stack locations. The
  12859. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12860. changes to also record the number of spills to the root stack.
  12861. % build-interference
  12862. %
  12863. % callq
  12864. % extra parameter for var->type assoc. list
  12865. % update 'program' and 'if'
  12866. % allocate-registers
  12867. % allocate spilled vectors to the rootstack
  12868. % don't change color-graph
  12869. % TODO:
  12870. %\section{Patch Instructions}
  12871. %[mention that global variables are memory references]
  12872. \section{Generate Prelude and Conclusion}
  12873. \label{sec:print-x86-gc}
  12874. \label{sec:prelude-conclusion-x86-gc}
  12875. \index{subject}{prelude}\index{subject}{conclusion}
  12876. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12877. \code{prelude\_and\_conclusion} pass on the running example. In the
  12878. prelude of the \code{main} function, we allocate space
  12879. on the root stack to make room for the spills of tuple-typed
  12880. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12881. taking care that the root stack grows up instead of down. For the
  12882. running example, there was just one spill, so we increment \code{r15}
  12883. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12884. One issue that deserves special care is that there may be a call to
  12885. \code{collect} prior to the initializing assignments for all the
  12886. variables in the root stack. We do not want the garbage collector to
  12887. mistakenly determine that some uninitialized variable is a pointer that
  12888. needs to be followed. Thus, we zero out all locations on the root
  12889. stack in the prelude of \code{main}. In
  12890. figure~\ref{fig:print-x86-output-gc}, the instruction
  12891. %
  12892. \lstinline{movq $0, 0(%r15)}
  12893. %
  12894. is sufficient to accomplish this task because there is only one spill.
  12895. In general, we have to clear as many words as there are spills of
  12896. tuple-typed variables. The garbage collector tests each root to see
  12897. if it is null prior to dereferencing it.
  12898. \begin{figure}[htbp]
  12899. \begin{tcolorbox}[colback=white]
  12900. {\if\edition\racketEd
  12901. \begin{minipage}[t]{0.5\textwidth}
  12902. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12903. .globl main
  12904. main:
  12905. pushq %rbp
  12906. movq %rsp, %rbp
  12907. subq $0, %rsp
  12908. movq $65536, %rdi
  12909. movq $65536, %rsi
  12910. callq initialize
  12911. movq rootstack_begin(%rip), %r15
  12912. movq $0, 0(%r15)
  12913. addq $8, %r15
  12914. jmp start
  12915. conclusion:
  12916. subq $8, %r15
  12917. addq $0, %rsp
  12918. popq %rbp
  12919. retq
  12920. \end{lstlisting}
  12921. \end{minipage}
  12922. \fi}
  12923. {\if\edition\pythonEd
  12924. \begin{minipage}[t]{0.5\textwidth}
  12925. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12926. .globl main
  12927. main:
  12928. pushq %rbp
  12929. movq %rsp, %rbp
  12930. pushq %rbx
  12931. subq $8, %rsp
  12932. movq $65536, %rdi
  12933. movq $16, %rsi
  12934. callq initialize
  12935. movq rootstack_begin(%rip), %r15
  12936. movq $0, 0(%r15)
  12937. addq $8, %r15
  12938. jmp start
  12939. conclusion:
  12940. subq $8, %r15
  12941. addq $8, %rsp
  12942. popq %rbx
  12943. popq %rbp
  12944. retq
  12945. \end{lstlisting}
  12946. \end{minipage}
  12947. \fi}
  12948. \end{tcolorbox}
  12949. \caption{The prelude and conclusion for the running example.}
  12950. \label{fig:print-x86-output-gc}
  12951. \end{figure}
  12952. \begin{figure}[tbp]
  12953. \begin{tcolorbox}[colback=white]
  12954. {\if\edition\racketEd
  12955. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12956. \node (Lvec) at (0,2) {\large \LangVec{}};
  12957. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12958. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12959. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12960. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12961. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12962. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12963. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12964. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12965. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12966. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12967. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12968. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12969. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12970. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12971. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12972. \path[->,bend left=15] (Lvec-4) edge [right] node
  12973. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12974. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12975. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12976. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12977. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12978. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12979. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12980. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12981. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12982. \end{tikzpicture}
  12983. \fi}
  12984. {\if\edition\pythonEd\pythonColor
  12985. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12986. \node (Lvec) at (0,2) {\large \LangVec{}};
  12987. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12988. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12989. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12990. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12991. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12992. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12993. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12994. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12995. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12996. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12997. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12998. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12999. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  13000. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  13001. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  13002. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  13003. \end{tikzpicture}
  13004. \fi}
  13005. \end{tcolorbox}
  13006. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  13007. \label{fig:Lvec-passes}
  13008. \end{figure}
  13009. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  13010. for the compilation of \LangVec{}.
  13011. \clearpage
  13012. {\if\edition\racketEd
  13013. \section{Challenge: Simple Structures}
  13014. \label{sec:simple-structures}
  13015. \index{subject}{struct}
  13016. \index{subject}{structure}
  13017. The language \LangStruct{} extends \LangVec{} with support for simple
  13018. structures. The definition of its concrete syntax is shown in
  13019. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  13020. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  13021. in Typed Racket is a user-defined data type that contains named fields
  13022. and that is heap allocated\index{subject}{heap allocated},
  13023. similarly to a vector. The following is an
  13024. example of a structure definition, in this case the definition of a
  13025. \code{point} type:
  13026. \begin{lstlisting}
  13027. (struct point ([x : Integer] [y : Integer]) #:mutable)
  13028. \end{lstlisting}
  13029. \newcommand{\LstructGrammarRacket}{
  13030. \begin{array}{lcl}
  13031. \Type &::=& \Var \\
  13032. \Exp &::=& (\Var\;\Exp \ldots)\\
  13033. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  13034. \end{array}
  13035. }
  13036. \newcommand{\LstructASTRacket}{
  13037. \begin{array}{lcl}
  13038. \Type &::=& \VAR{\Var} \\
  13039. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  13040. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  13041. \end{array}
  13042. }
  13043. \begin{figure}[tbp]
  13044. \centering
  13045. \begin{tcolorbox}[colback=white]
  13046. \[
  13047. \begin{array}{l}
  13048. \gray{\LintGrammarRacket{}} \\ \hline
  13049. \gray{\LvarGrammarRacket{}} \\ \hline
  13050. \gray{\LifGrammarRacket{}} \\ \hline
  13051. \gray{\LwhileGrammarRacket} \\ \hline
  13052. \gray{\LtupGrammarRacket} \\ \hline
  13053. \LstructGrammarRacket \\
  13054. \begin{array}{lcl}
  13055. \LangStruct{} &::=& \Def \ldots \; \Exp
  13056. \end{array}
  13057. \end{array}
  13058. \]
  13059. \end{tcolorbox}
  13060. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  13061. (figure~\ref{fig:Lvec-concrete-syntax}).}
  13062. \label{fig:Lstruct-concrete-syntax}
  13063. \index{subject}{Lstruct@\LangStruct{} concrete syntax}
  13064. \end{figure}
  13065. \begin{figure}[tbp]
  13066. \centering
  13067. \begin{tcolorbox}[colback=white]
  13068. \small
  13069. \[
  13070. \begin{array}{l}
  13071. \gray{\LintASTRacket{}} \\ \hline
  13072. \gray{\LvarASTRacket{}} \\ \hline
  13073. \gray{\LifASTRacket{}} \\ \hline
  13074. \gray{\LwhileASTRacket} \\ \hline
  13075. \gray{\LtupASTRacket} \\ \hline
  13076. \LstructASTRacket \\
  13077. \begin{array}{lcl}
  13078. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13079. \end{array}
  13080. \end{array}
  13081. \]
  13082. \end{tcolorbox}
  13083. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  13084. (figure~\ref{fig:Lvec-syntax}).}
  13085. \label{fig:Lstruct-syntax}
  13086. \index{subject}{Lstruct@\LangStruct{} abstract syntax}
  13087. \end{figure}
  13088. An instance of a structure is created using function-call syntax, with
  13089. the name of the structure in the function position, as follows:
  13090. \begin{lstlisting}
  13091. (point 7 12)
  13092. \end{lstlisting}
  13093. Function-call syntax is also used to read a field of a structure. The
  13094. function name is formed by the structure name, a dash, and the field
  13095. name. The following example uses \code{point-x} and \code{point-y} to
  13096. access the \code{x} and \code{y} fields of two point instances:
  13097. \begin{center}
  13098. \begin{lstlisting}
  13099. (let ([pt1 (point 7 12)])
  13100. (let ([pt2 (point 4 3)])
  13101. (+ (- (point-x pt1) (point-x pt2))
  13102. (- (point-y pt1) (point-y pt2)))))
  13103. \end{lstlisting}
  13104. \end{center}
  13105. Similarly, to write to a field of a structure, use its set function,
  13106. whose name starts with \code{set-}, followed by the structure name,
  13107. then a dash, then the field name, and finally with an exclamation
  13108. mark. The following example uses \code{set-point-x!} to change the
  13109. \code{x} field from \code{7} to \code{42}:
  13110. \begin{center}
  13111. \begin{lstlisting}
  13112. (let ([pt (point 7 12)])
  13113. (let ([_ (set-point-x! pt 42)])
  13114. (point-x pt)))
  13115. \end{lstlisting}
  13116. \end{center}
  13117. \begin{exercise}\normalfont\normalsize
  13118. Create a type checker for \LangStruct{} by extending the type
  13119. checker for \LangVec{}. Extend your compiler with support for simple
  13120. structures, compiling \LangStruct{} to x86 assembly code. Create
  13121. five new test cases that use structures, and test your compiler.
  13122. \end{exercise}
  13123. % TODO: create an interpreter for L_struct
  13124. \clearpage
  13125. \fi}
  13126. \section{Challenge: Arrays}
  13127. \label{sec:arrays}
  13128. % TODO mention trapped-error
  13129. In this chapter we have studied tuples, that is, heterogeneous
  13130. sequences of elements whose length is determined at compile time. This
  13131. challenge is also about sequences, but this time the length is
  13132. determined at runtime and all the elements have the same type (they
  13133. are homogeneous). We use the traditional term \emph{array} for this
  13134. latter kind of sequence.
  13135. %
  13136. \racket{
  13137. The Racket language does not distinguish between tuples and arrays;
  13138. they are both represented by vectors. However, Typed Racket
  13139. distinguishes between tuples and arrays: the \code{Vector} type is for
  13140. tuples, and the \code{Vectorof} type is for arrays.}%
  13141. \python{Arrays correspond to the \code{list} type in the Python language.}
  13142. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13143. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13144. presents the definition of the abstract syntax, extending \LangVec{}
  13145. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13146. \racket{\code{make-vector} primitive operator for creating an array,
  13147. whose arguments are the length of the array and an initial value for
  13148. all the elements in the array.}%
  13149. \python{bracket notation for creating an array literal.}
  13150. \racket{The \code{vector-length},
  13151. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13152. for tuples become overloaded for use with arrays.}
  13153. \python{
  13154. The subscript operator becomes overloaded for use with arrays and tuples
  13155. and now may appear on the left-hand side of an assignment.
  13156. Note that the index of the subscript, when applied to an array, may be an
  13157. arbitrary expression and not exclusively a constant integer.
  13158. The \code{len} function is also applicable to arrays.
  13159. }
  13160. %
  13161. We include integer multiplication in \LangArray{} because it is
  13162. useful in many examples involving arrays such as computing the
  13163. inner product of two arrays (figure~\ref{fig:inner_product}).
  13164. \newcommand{\LarrayGrammarRacket}{
  13165. \begin{array}{lcl}
  13166. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13167. \Exp &::=& \CMUL{\Exp}{\Exp}
  13168. \MID \CMAKEVEC{\Exp}{\Exp}
  13169. \end{array}
  13170. }
  13171. \newcommand{\LarrayASTRacket}{
  13172. \begin{array}{lcl}
  13173. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13174. \Exp &::=& \MUL{\Exp}{\Exp}
  13175. \MID \MAKEVEC{\Exp}{\Exp}
  13176. \end{array}
  13177. }
  13178. \newcommand{\LarrayGrammarPython}{
  13179. \begin{array}{lcl}
  13180. \Type &::=& \key{list}\LS\Type\RS \\
  13181. \Exp &::=& \CMUL{\Exp}{\Exp}
  13182. \MID \CGET{\Exp}{\Exp}
  13183. \MID \LS \Exp \code{,} \ldots \RS \\
  13184. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13185. \end{array}
  13186. }
  13187. \newcommand{\LarrayASTPython}{
  13188. \begin{array}{lcl}
  13189. \Type &::=& \key{ListType}\LP\Type\RP \\
  13190. \Exp &::=& \MUL{\Exp}{\Exp}
  13191. \MID \GET{\Exp}{\Exp} \\
  13192. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13193. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13194. \end{array}
  13195. }
  13196. \begin{figure}[tp]
  13197. \centering
  13198. \begin{tcolorbox}[colback=white]
  13199. \small
  13200. {\if\edition\racketEd
  13201. \[
  13202. \begin{array}{l}
  13203. \gray{\LintGrammarRacket{}} \\ \hline
  13204. \gray{\LvarGrammarRacket{}} \\ \hline
  13205. \gray{\LifGrammarRacket{}} \\ \hline
  13206. \gray{\LwhileGrammarRacket} \\ \hline
  13207. \gray{\LtupGrammarRacket} \\ \hline
  13208. \LarrayGrammarRacket \\
  13209. \begin{array}{lcl}
  13210. \LangArray{} &::=& \Exp
  13211. \end{array}
  13212. \end{array}
  13213. \]
  13214. \fi}
  13215. {\if\edition\pythonEd\pythonColor
  13216. \[
  13217. \begin{array}{l}
  13218. \gray{\LintGrammarPython{}} \\ \hline
  13219. \gray{\LvarGrammarPython{}} \\ \hline
  13220. \gray{\LifGrammarPython{}} \\ \hline
  13221. \gray{\LwhileGrammarPython} \\ \hline
  13222. \gray{\LtupGrammarPython} \\ \hline
  13223. \LarrayGrammarPython \\
  13224. \begin{array}{rcl}
  13225. \LangArrayM{} &::=& \Stmt^{*}
  13226. \end{array}
  13227. \end{array}
  13228. \]
  13229. \fi}
  13230. \end{tcolorbox}
  13231. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13232. \label{fig:Lvecof-concrete-syntax}
  13233. \index{subject}{Larray@\LangArray{} concrete syntax}
  13234. \end{figure}
  13235. \begin{figure}[tp]
  13236. \centering
  13237. \begin{tcolorbox}[colback=white]
  13238. \small
  13239. {\if\edition\racketEd
  13240. \[
  13241. \begin{array}{l}
  13242. \gray{\LintASTRacket{}} \\ \hline
  13243. \gray{\LvarASTRacket{}} \\ \hline
  13244. \gray{\LifASTRacket{}} \\ \hline
  13245. \gray{\LwhileASTRacket} \\ \hline
  13246. \gray{\LtupASTRacket} \\ \hline
  13247. \LarrayASTRacket \\
  13248. \begin{array}{lcl}
  13249. \LangArray{} &::=& \Exp
  13250. \end{array}
  13251. \end{array}
  13252. \]
  13253. \fi}
  13254. {\if\edition\pythonEd\pythonColor
  13255. \[
  13256. \begin{array}{l}
  13257. \gray{\LintASTPython{}} \\ \hline
  13258. \gray{\LvarASTPython{}} \\ \hline
  13259. \gray{\LifASTPython{}} \\ \hline
  13260. \gray{\LwhileASTPython} \\ \hline
  13261. \gray{\LtupASTPython} \\ \hline
  13262. \LarrayASTPython \\
  13263. \begin{array}{rcl}
  13264. \LangArrayM{} &::=& \Stmt^{*}
  13265. \end{array}
  13266. \end{array}
  13267. \]
  13268. \fi}
  13269. \end{tcolorbox}
  13270. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13271. \label{fig:Lvecof-syntax}
  13272. \index{subject}{Larray@\LangArray{} abstract syntax}
  13273. \end{figure}
  13274. \begin{figure}[tp]
  13275. \begin{tcolorbox}[colback=white]
  13276. {\if\edition\racketEd
  13277. \begin{lstlisting}
  13278. (let ([A (make-vector 2 2)])
  13279. (let ([B (make-vector 2 3)])
  13280. (let ([i 0])
  13281. (let ([prod 0])
  13282. (begin
  13283. (while (< i (vector-length A))
  13284. (begin
  13285. (set! prod (+ prod (* (vector-ref A i)
  13286. (vector-ref B i))))
  13287. (set! i (+ i 1))))
  13288. prod)))))
  13289. \end{lstlisting}
  13290. \fi}
  13291. {\if\edition\pythonEd\pythonColor
  13292. \begin{lstlisting}
  13293. A = [2, 2]
  13294. B = [3, 3]
  13295. i = 0
  13296. prod = 0
  13297. while i != len(A):
  13298. prod = prod + A[i] * B[i]
  13299. i = i + 1
  13300. print(prod)
  13301. \end{lstlisting}
  13302. \fi}
  13303. \end{tcolorbox}
  13304. \caption{Example program that computes the inner product.}
  13305. \label{fig:inner_product}
  13306. \end{figure}
  13307. {\if\edition\racketEd
  13308. %
  13309. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13310. checker for \LangArray{}. The result type of
  13311. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13312. of the initializing expression. The length expression is required to
  13313. have type \code{Integer}. The type checking of the operators
  13314. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13315. updated to handle the situation in which the vector has type
  13316. \code{Vectorof}. In these cases we translate the operators to their
  13317. \code{vectorof} form so that later passes can easily distinguish
  13318. between operations on tuples versus arrays. We override the
  13319. \code{operator-types} method to provide the type signature for
  13320. multiplication: it takes two integers and returns an integer.
  13321. \fi}
  13322. %
  13323. {\if\edition\pythonEd\pythonColor
  13324. %
  13325. The type checker for \LangArray{} is defined in
  13326. figures~\ref{fig:type-check-Lvecof} and
  13327. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13328. is \code{list[T]}, where \code{T} is the type of the initializing
  13329. expressions. The type checking of the \code{len} function and the
  13330. subscript operator are updated to handle lists. The type checker now
  13331. also handles a subscript on the left-hand side of an assignment.
  13332. Regarding multiplication, it takes two integers and returns an
  13333. integer.
  13334. %
  13335. \fi}
  13336. \begin{figure}[tbp]
  13337. \begin{tcolorbox}[colback=white]
  13338. {\if\edition\racketEd
  13339. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13340. (define type-check-Lvecof-class
  13341. (class type-check-Lvec-class
  13342. (super-new)
  13343. (inherit check-type-equal?)
  13344. (define/override (operator-types)
  13345. (append '((* . ((Integer Integer) . Integer)))
  13346. (super operator-types)))
  13347. (define/override (type-check-exp env)
  13348. (lambda (e)
  13349. (define recur (type-check-exp env))
  13350. (match e
  13351. [(Prim 'make-vector (list e1 e2))
  13352. (define-values (e1^ t1) (recur e1))
  13353. (define-values (e2^ elt-type) (recur e2))
  13354. (define vec-type `(Vectorof ,elt-type))
  13355. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13356. [(Prim 'vector-ref (list e1 e2))
  13357. (define-values (e1^ t1) (recur e1))
  13358. (define-values (e2^ t2) (recur e2))
  13359. (match* (t1 t2)
  13360. [(`(Vectorof ,elt-type) 'Integer)
  13361. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13362. [(other wise) ((super type-check-exp env) e)])]
  13363. [(Prim 'vector-set! (list e1 e2 e3) )
  13364. (define-values (e-vec t-vec) (recur e1))
  13365. (define-values (e2^ t2) (recur e2))
  13366. (define-values (e-arg^ t-arg) (recur e3))
  13367. (match t-vec
  13368. [`(Vectorof ,elt-type)
  13369. (check-type-equal? elt-type t-arg e)
  13370. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13371. [else ((super type-check-exp env) e)])]
  13372. [(Prim 'vector-length (list e1))
  13373. (define-values (e1^ t1) (recur e1))
  13374. (match t1
  13375. [`(Vectorof ,t)
  13376. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13377. [else ((super type-check-exp env) e)])]
  13378. [else ((super type-check-exp env) e)])))
  13379. ))
  13380. (define (type-check-Lvecof p)
  13381. (send (new type-check-Lvecof-class) type-check-program p))
  13382. \end{lstlisting}
  13383. \fi}
  13384. {\if\edition\pythonEd\pythonColor
  13385. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13386. class TypeCheckLarray(TypeCheckLtup):
  13387. def type_check_exp(self, e, env):
  13388. match e:
  13389. case ast.List(es, Load()):
  13390. ts = [self.type_check_exp(e, env) for e in es]
  13391. elt_ty = ts[0]
  13392. for (ty, elt) in zip(ts, es):
  13393. self.check_type_equal(elt_ty, ty, elt)
  13394. e.has_type = ListType(elt_ty)
  13395. return e.has_type
  13396. case Call(Name('len'), [tup]):
  13397. tup_t = self.type_check_exp(tup, env)
  13398. tup.has_type = tup_t
  13399. match tup_t:
  13400. case TupleType(ts):
  13401. return IntType()
  13402. case ListType(ty):
  13403. return IntType()
  13404. case _:
  13405. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13406. case Subscript(tup, index, Load()):
  13407. tup_ty = self.type_check_exp(tup, env)
  13408. tup.has_type = tup_ty
  13409. index_ty = self.type_check_exp(index, env)
  13410. self.check_type_equal(index_ty, IntType(), index)
  13411. match tup_ty:
  13412. case TupleType(ts):
  13413. match index:
  13414. case Constant(i):
  13415. return ts[i]
  13416. case _:
  13417. raise Exception('subscript required constant integer index')
  13418. case ListType(ty):
  13419. return ty
  13420. case _:
  13421. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13422. case BinOp(left, Mult(), right):
  13423. l = self.type_check_exp(left, env)
  13424. self.check_type_equal(l, IntType(), left)
  13425. r = self.type_check_exp(right, env)
  13426. self.check_type_equal(r, IntType(), right)
  13427. return IntType()
  13428. case _:
  13429. return super().type_check_exp(e, env)
  13430. \end{lstlisting}
  13431. \fi}
  13432. \end{tcolorbox}
  13433. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13434. \label{fig:type-check-Lvecof}
  13435. \end{figure}
  13436. {\if\edition\pythonEd
  13437. \begin{figure}[tbp]
  13438. \begin{tcolorbox}[colback=white]
  13439. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13440. def type_check_stmts(self, ss, env):
  13441. if len(ss) == 0:
  13442. return VoidType()
  13443. match ss[0]:
  13444. case Assign([Subscript(tup, index, Store())], value):
  13445. tup_t = self.type_check_exp(tup, env)
  13446. tup.has_type = tup_t
  13447. value_t = self.type_check_exp(value, env)
  13448. index_ty = self.type_check_exp(index, env)
  13449. self.check_type_equal(index_ty, IntType(), index)
  13450. match tup_t:
  13451. case ListType(ty):
  13452. self.check_type_equal(ty, value_t, ss[0])
  13453. case TupleType(ts):
  13454. return self.type_check_stmts(ss, env)
  13455. case _:
  13456. raise Exception('type_check_stmts: '
  13457. 'expected tuple or list, not ' + repr(tup_t))
  13458. return self.type_check_stmts(ss[1:], env)
  13459. case _:
  13460. return super().type_check_stmts(ss, env)
  13461. \end{lstlisting}
  13462. \end{tcolorbox}
  13463. \caption{Type checker for the \LangArray{} language, part 2.}
  13464. \label{fig:type-check-Lvecof-part2}
  13465. \end{figure}
  13466. \fi}
  13467. The definition of the interpreter for \LangArray{} is shown in
  13468. \racket{figure~\ref{fig:interp-Lvecof}}
  13469. \python{figure~\ref{fig:interp-Lvecof}}.
  13470. \racket{The \code{make-vector} operator is
  13471. interpreted using Racket's \code{make-vector} function,
  13472. and multiplication is interpreted using \code{fx*},
  13473. which is multiplication for \code{fixnum} integers.
  13474. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13475. we translate array access operations
  13476. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13477. which we interpret using \code{vector} operations with additional
  13478. bounds checks that signal a \code{trapped-error}.
  13479. }
  13480. %
  13481. \python{We implement array creation with a Python list comprehension,
  13482. and multiplication is implemented with 64-bit multiplication. We
  13483. add a case for a subscript on the left-hand side of
  13484. assignment. Other uses of subscript can be handled by the existing
  13485. code for tuples.}
  13486. \begin{figure}[tbp]
  13487. \begin{tcolorbox}[colback=white]
  13488. {\if\edition\racketEd
  13489. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13490. (define interp-Lvecof-class
  13491. (class interp-Lvec-class
  13492. (super-new)
  13493. (define/override (interp-op op)
  13494. (match op
  13495. ['make-vector make-vector]
  13496. ['vectorof-length vector-length]
  13497. ['vectorof-ref
  13498. (lambda (v i)
  13499. (if (< i (vector-length v))
  13500. (vector-ref v i)
  13501. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13502. ['vectorof-set!
  13503. (lambda (v i e)
  13504. (if (< i (vector-length v))
  13505. (vector-set! v i e)
  13506. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13507. [else (super interp-op op)]))
  13508. ))
  13509. (define (interp-Lvecof p)
  13510. (send (new interp-Lvecof-class) interp-program p))
  13511. \end{lstlisting}
  13512. \fi}
  13513. {\if\edition\pythonEd\pythonColor
  13514. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13515. class InterpLarray(InterpLtup):
  13516. def interp_exp(self, e, env):
  13517. match e:
  13518. case ast.List(es, Load()):
  13519. return [self.interp_exp(e, env) for e in es]
  13520. case BinOp(left, Mult(), right):
  13521. l = self.interp_exp(left, env)
  13522. r = self.interp_exp(right, env)
  13523. return mul64(l, r)
  13524. case Subscript(tup, index, Load()):
  13525. t = self.interp_exp(tup, env)
  13526. n = self.interp_exp(index, env)
  13527. if n < len(t):
  13528. return t[n]
  13529. else:
  13530. raise TrappedError('array index out of bounds')
  13531. case _:
  13532. return super().interp_exp(e, env)
  13533. def interp_stmt(self, s, env, cont):
  13534. match s:
  13535. case Assign([Subscript(tup, index)], value):
  13536. t = self.interp_exp(tup, env)
  13537. n = self.interp_exp(index, env)
  13538. if n < len(t):
  13539. t[n] = self.interp_exp(value, env)
  13540. else:
  13541. raise TrappedError('array index out of bounds')
  13542. return self.interp_stmts(cont, env)
  13543. case _:
  13544. return super().interp_stmt(s, env, cont)
  13545. \end{lstlisting}
  13546. \fi}
  13547. \end{tcolorbox}
  13548. \caption{Interpreter for \LangArray{}.}
  13549. \label{fig:interp-Lvecof}
  13550. \end{figure}
  13551. \subsection{Data Representation}
  13552. \label{sec:array-rep}
  13553. Just as with tuples, we store arrays on the heap, which means that the
  13554. garbage collector will need to inspect arrays. An immediate thought is
  13555. to use the same representation for arrays that we use for tuples.
  13556. However, we limit tuples to a length of fifty so that their length and
  13557. pointer mask can fit into the 64-bit tag at the beginning of each
  13558. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13559. millions of elements, so we need more bits to store the length.
  13560. However, because arrays are homogeneous, we need only 1 bit for the
  13561. pointer mask instead of 1 bit per array element. Finally, the
  13562. garbage collector must be able to distinguish between tuples
  13563. and arrays, so we need to reserve one bit for that purpose. We
  13564. arrive at the following layout for the 64-bit tag at the beginning of
  13565. an array:
  13566. \begin{itemize}
  13567. \item The right-most bit is the forwarding bit, just as in a tuple.
  13568. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13569. that it is not.
  13570. \item The next bit to the left is the pointer mask. A $0$ indicates
  13571. that none of the elements are pointers, and a $1$ indicates that all
  13572. the elements are pointers.
  13573. \item The next $60$ bits store the length of the array.
  13574. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13575. and an array ($1$).
  13576. \item The left-most bit is reserved as explained in
  13577. chapter~\ref{ch:Lgrad}.
  13578. \end{itemize}
  13579. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13580. %% differentiate the kinds of values that have been injected into the
  13581. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13582. %% to indicate that the value is an array.
  13583. In the following subsections we provide hints regarding how to update
  13584. the passes to handle arrays.
  13585. \subsection{Overload Resolution}
  13586. \label{sec:array-resolution}
  13587. As noted previously, with the addition of arrays, several operators
  13588. have become \emph{overloaded}; that is, they can be applied to values
  13589. of more than one type. In this case, the element access and length
  13590. operators can be applied to both tuples and arrays. This kind of
  13591. overloading is quite common in programming languages, so many
  13592. compilers perform \emph{overload resolution}\index{subject}{overload
  13593. resolution} to handle it. The idea is to translate each overloaded
  13594. operator into different operators for the different types.
  13595. Implement a new pass named \code{resolve}.
  13596. Translate the reading of an array element to
  13597. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13598. and the writing of an array element to
  13599. \racket{\code{vectorof-set!}}\python{\code{array\_store}}.
  13600. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13601. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13602. When these operators are applied to tuples, leave them as is.
  13603. %
  13604. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13605. field, which can be inspected to determine whether the operator
  13606. is applied to a tuple or an array.}
  13607. \subsection{Bounds Checking}
  13608. Recall that the interpreter for \LangArray{} signals a
  13609. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13610. when there is an array access that is out of
  13611. bounds. Therefore your compiler is obliged to also catch these errors
  13612. during execution and halt, signaling an error. We recommend inserting
  13613. a new pass named \code{check\_bounds} that inserts code around each
  13614. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13615. \python{subscript} operation to ensure that the index is greater than
  13616. or equal to zero and less than the array's length. If not, the program
  13617. should halt, for which we recommend using a new primitive operation
  13618. named \code{exit}.
  13619. %% \subsection{Reveal Casts}
  13620. %% The array-access operators \code{vectorof-ref} and
  13621. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13622. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13623. %% that the type checker cannot tell whether the index will be in bounds,
  13624. %% so the bounds check must be performed at run time. Recall that the
  13625. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13626. %% an \code{If} around a vector reference for update to check whether
  13627. %% the index is less than the length. You should do the same for
  13628. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13629. %% In addition, the handling of the \code{any-vector} operators in
  13630. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13631. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13632. %% generated code should test whether the tag is for tuples (\code{010})
  13633. %% or arrays (\code{110}) and then dispatch to either
  13634. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13635. %% we add a case in \code{select\_instructions} to generate the
  13636. %% appropriate instructions for accessing the array length from the
  13637. %% header of an array.
  13638. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13639. %% the generated code needs to check that the index is less than the
  13640. %% vector length, so like the code for \code{any-vector-length}, check
  13641. %% the tag to determine whether to use \code{any-vector-length} or
  13642. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13643. %% is complete, the generated code can use \code{any-vector-ref} and
  13644. %% \code{any-vector-set!} for both tuples and arrays because the
  13645. %% instructions used for those operators do not look at the tag at the
  13646. %% front of the tuple or array.
  13647. \subsection{Expose Allocation}
  13648. % TODO: add figure for C_array
  13649. This pass should translate array creation into lower-level
  13650. operations. In particular, the new AST node \ALLOCARRAY{\Int}{\Type}
  13651. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13652. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13653. array. The \code{AllocateArray} AST node allocates an array of the
  13654. length specified by the $\Exp$ (of type \INTTY), but does not
  13655. initialize the elements of the array. Generate code in this pass to
  13656. initialize the elements analogous to the case for tuples.
  13657. {\if\edition\racketEd
  13658. \subsection{Uncover \texttt{get!}}
  13659. \label{sec:uncover-get-bang-vecof}
  13660. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13661. \code{uncover-get!-exp}.
  13662. \fi}
  13663. \subsection{Remove Complex Operands}
  13664. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13665. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13666. complex, and its subexpression must be atomic.
  13667. \subsection{Explicate Control}
  13668. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13669. \code{explicate\_assign}.
  13670. \subsection{Select Instructions}
  13671. \index{subject}{select instructions}
  13672. Generate instructions for \code{AllocateArray} similar to those for
  13673. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13674. except that the tag at the front of the array should instead use the
  13675. representation discussed in section~\ref{sec:array-rep}.
  13676. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13677. extract the length from the tag.
  13678. The instructions generated for accessing an element of an array differ
  13679. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13680. that the index is not a constant so you need to generate instructions
  13681. that compute the offset at runtime.
  13682. Compile the \code{exit} primitive into a call to the \code{exit}
  13683. function of the C standard library, with an argument of $255$.
  13684. %% Also, note that assignment to an array element may appear in
  13685. %% as a stand-alone statement, so make sure to handle that situation in
  13686. %% this pass.
  13687. %% Finally, the instructions for \code{any-vectorof-length} should be
  13688. %% similar to those for \code{vectorof-length}, except that one must
  13689. %% first project the array by writing zeroes into the $3$-bit tag
  13690. \begin{exercise}\normalfont\normalsize
  13691. Implement a compiler for the \LangArray{} language by extending your
  13692. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13693. programs, including the one shown in figure~\ref{fig:inner_product}
  13694. and also a program that multiplies two matrices. Note that although
  13695. matrices are two-dimensional arrays, they can be encoded into
  13696. one-dimensional arrays by laying out each row in the array, one after
  13697. the next.
  13698. \end{exercise}
  13699. {\if\edition\racketEd
  13700. \section{Challenge: Generational Collection}
  13701. The copying collector described in section~\ref{sec:GC} can incur
  13702. significant runtime overhead because the call to \code{collect} takes
  13703. time proportional to all the live data. One way to reduce this
  13704. overhead is to reduce how much data is inspected in each call to
  13705. \code{collect}. In particular, researchers have observed that recently
  13706. allocated data is more likely to become garbage than data that has
  13707. survived one or more previous calls to \code{collect}. This insight
  13708. motivated the creation of \emph{generational garbage collectors}
  13709. \index{subject}{generational garbage collector} that
  13710. (1) segregate data according to its age into two or more generations;
  13711. (2) allocate less space for younger generations, so collecting them is
  13712. faster, and more space for the older generations; and (3) perform
  13713. collection on the younger generations more frequently than on older
  13714. generations~\citep{Wilson:1992fk}.
  13715. For this challenge assignment, the goal is to adapt the copying
  13716. collector implemented in \code{runtime.c} to use two generations, one
  13717. for young data and one for old data. Each generation consists of a
  13718. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13719. \code{collect} function to use the two generations:
  13720. \begin{enumerate}
  13721. \item Copy the young generation's FromSpace to its ToSpace and then
  13722. switch the role of the ToSpace and FromSpace.
  13723. \item If there is enough space for the requested number of bytes in
  13724. the young FromSpace, then return from \code{collect}.
  13725. \item If there is not enough space in the young FromSpace for the
  13726. requested bytes, then move the data from the young generation to the
  13727. old one with the following steps:
  13728. \begin{enumerate}
  13729. \item[a.] If there is enough room in the old FromSpace, copy the young
  13730. FromSpace to the old FromSpace and then return.
  13731. \item[b.] If there is not enough room in the old FromSpace, then collect
  13732. the old generation by copying the old FromSpace to the old ToSpace
  13733. and swap the roles of the old FromSpace and ToSpace.
  13734. \item[c.] If there is enough room now, copy the young FromSpace to the
  13735. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13736. and ToSpace for the old generation. Copy the young FromSpace and
  13737. the old FromSpace into the larger FromSpace for the old
  13738. generation and then return.
  13739. \end{enumerate}
  13740. \end{enumerate}
  13741. We recommend that you generalize the \code{cheney} function so that it
  13742. can be used for all the copies mentioned: between the young FromSpace
  13743. and ToSpace, between the old FromSpace and ToSpace, and between the
  13744. young FromSpace and old FromSpace. This can be accomplished by adding
  13745. parameters to \code{cheney} that replace its use of the global
  13746. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13747. \code{tospace\_begin}, and \code{tospace\_end}.
  13748. Note that the collection of the young generation does not traverse the
  13749. old generation. This introduces a potential problem: there may be
  13750. young data that is reachable only through pointers in the old
  13751. generation. If these pointers are not taken into account, the
  13752. collector could throw away young data that is live! One solution,
  13753. called \emph{pointer recording}, is to maintain a set of all the
  13754. pointers from the old generation into the new generation and consider
  13755. this set as part of the root set. To maintain this set, the compiler
  13756. must insert extra instructions around every \code{vector-set!}. If the
  13757. vector being modified is in the old generation, and if the value being
  13758. written is a pointer into the new generation, then that pointer must
  13759. be added to the set. Also, if the value being overwritten was a
  13760. pointer into the new generation, then that pointer should be removed
  13761. from the set.
  13762. \begin{exercise}\normalfont\normalsize
  13763. Adapt the \code{collect} function in \code{runtime.c} to implement
  13764. generational garbage collection, as outlined in this section.
  13765. Update the code generation for \code{vector-set!} to implement
  13766. pointer recording. Make sure that your new compiler and runtime
  13767. execute without error on your test suite.
  13768. \end{exercise}
  13769. \fi}
  13770. \section{Further Reading}
  13771. \citet{Appel90} describes many data representation approaches
  13772. including the ones used in the compilation of Standard ML.
  13773. There are many alternatives to copying collectors (and their bigger
  13774. siblings, the generational collectors) with regard to garbage
  13775. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13776. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13777. collectors are that allocation is fast (just a comparison and pointer
  13778. increment), there is no fragmentation, cyclic garbage is collected,
  13779. and the time complexity of collection depends only on the amount of
  13780. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13781. main disadvantages of a two-space copying collector is that it uses a
  13782. lot of extra space and takes a long time to perform the copy, though
  13783. these problems are ameliorated in generational collectors.
  13784. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13785. small objects and generate a lot of garbage, so copying and
  13786. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13787. Garbage collection is an active research topic, especially concurrent
  13788. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13789. developing new techniques and revisiting old
  13790. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13791. meet every year at the International Symposium on Memory Management to
  13792. present these findings.
  13793. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13794. \chapter{Functions}
  13795. \label{ch:Lfun}
  13796. \index{subject}{function}
  13797. \setcounter{footnote}{0}
  13798. This chapter studies the compilation of a subset of \racket{Typed
  13799. Racket}\python{Python} in which only top-level function definitions
  13800. are allowed. This kind of function appears in the C programming
  13801. language, and it serves as an important stepping-stone to implementing
  13802. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13803. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13804. \section{The \LangFun{} Language}
  13805. The concrete syntax and abstract syntax for function definitions and
  13806. function application are shown in
  13807. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13808. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13809. with zero or more function definitions. The function names from these
  13810. definitions are in scope for the entire program, including all the
  13811. function definitions, and therefore the ordering of function
  13812. definitions does not matter.
  13813. %
  13814. \python{The abstract syntax for function parameters in
  13815. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13816. consists of a parameter name and its type. This design differs from
  13817. Python's \code{ast} module, which has a more complex structure for
  13818. function parameters to handle keyword parameters,
  13819. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13820. complex Python abstract syntax into the simpler syntax shown in
  13821. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13822. \code{FunctionDef} constructor are for decorators and a type
  13823. comment, neither of which are used by our compiler. We recommend
  13824. replacing them with \code{None} in the \code{shrink} pass.
  13825. }
  13826. %
  13827. The concrete syntax for function application
  13828. \index{subject}{function application}
  13829. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13830. where the first expression
  13831. must evaluate to a function and the remaining expressions are the arguments. The
  13832. abstract syntax for function application is
  13833. $\APPLY{\Exp}{\Exp^*}$.
  13834. %% The syntax for function application does not include an explicit
  13835. %% keyword, which is error prone when using \code{match}. To alleviate
  13836. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13837. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13838. Functions are first-class in the sense that a function pointer
  13839. \index{subject}{function pointer} is data and can be stored in memory or passed
  13840. as a parameter to another function. Thus, there is a function
  13841. type, written
  13842. {\if\edition\racketEd
  13843. \begin{lstlisting}
  13844. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13845. \end{lstlisting}
  13846. \fi}
  13847. {\if\edition\pythonEd\pythonColor
  13848. \begin{lstlisting}
  13849. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13850. \end{lstlisting}
  13851. \fi}
  13852. %
  13853. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13854. through $\Type_n$ and whose return type is $\Type_R$. The main
  13855. limitation of these functions (with respect to
  13856. \racket{Racket}\python{Python} functions) is that they are not
  13857. lexically scoped. That is, the only external entities that can be
  13858. referenced from inside a function body are other globally defined
  13859. functions. The syntax of \LangFun{} prevents function definitions from
  13860. being nested inside each other.
  13861. \newcommand{\LfunGrammarRacket}{
  13862. \begin{array}{lcl}
  13863. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13864. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13865. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13866. \end{array}
  13867. }
  13868. \newcommand{\LfunASTRacket}{
  13869. \begin{array}{lcl}
  13870. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13871. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13872. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13873. \end{array}
  13874. }
  13875. \newcommand{\LfunGrammarPython}{
  13876. \begin{array}{lcl}
  13877. \Type &::=& \key{int}
  13878. \MID \key{bool} \MID \key{void}
  13879. \MID \key{tuple}\LS \Type^+ \RS
  13880. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13881. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13882. \Stmt &::=& \CRETURN{\Exp} \\
  13883. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13884. \end{array}
  13885. }
  13886. \newcommand{\LfunASTPython}{
  13887. \begin{array}{lcl}
  13888. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13889. \MID \key{TupleType}\LS\Type^+\RS\\
  13890. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13891. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13892. \Stmt &::=& \RETURN{\Exp} \\
  13893. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13894. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13895. \end{array}
  13896. }
  13897. \begin{figure}[tp]
  13898. \centering
  13899. \begin{tcolorbox}[colback=white]
  13900. \small
  13901. {\if\edition\racketEd
  13902. \[
  13903. \begin{array}{l}
  13904. \gray{\LintGrammarRacket{}} \\ \hline
  13905. \gray{\LvarGrammarRacket{}} \\ \hline
  13906. \gray{\LifGrammarRacket{}} \\ \hline
  13907. \gray{\LwhileGrammarRacket} \\ \hline
  13908. \gray{\LtupGrammarRacket} \\ \hline
  13909. \LfunGrammarRacket \\
  13910. \begin{array}{lcl}
  13911. \LangFunM{} &::=& \Def \ldots \; \Exp
  13912. \end{array}
  13913. \end{array}
  13914. \]
  13915. \fi}
  13916. {\if\edition\pythonEd\pythonColor
  13917. \[
  13918. \begin{array}{l}
  13919. \gray{\LintGrammarPython{}} \\ \hline
  13920. \gray{\LvarGrammarPython{}} \\ \hline
  13921. \gray{\LifGrammarPython{}} \\ \hline
  13922. \gray{\LwhileGrammarPython} \\ \hline
  13923. \gray{\LtupGrammarPython} \\ \hline
  13924. \LfunGrammarPython \\
  13925. \begin{array}{rcl}
  13926. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13927. \end{array}
  13928. \end{array}
  13929. \]
  13930. \fi}
  13931. \end{tcolorbox}
  13932. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13933. \label{fig:Lfun-concrete-syntax}
  13934. \index{subject}{Lfun@\LangFun{} concrete syntax}
  13935. \end{figure}
  13936. \begin{figure}[tp]
  13937. \centering
  13938. \begin{tcolorbox}[colback=white]
  13939. \small
  13940. {\if\edition\racketEd
  13941. \[
  13942. \begin{array}{l}
  13943. \gray{\LintOpAST} \\ \hline
  13944. \gray{\LvarASTRacket{}} \\ \hline
  13945. \gray{\LifASTRacket{}} \\ \hline
  13946. \gray{\LwhileASTRacket{}} \\ \hline
  13947. \gray{\LtupASTRacket{}} \\ \hline
  13948. \LfunASTRacket \\
  13949. \begin{array}{lcl}
  13950. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13951. \end{array}
  13952. \end{array}
  13953. \]
  13954. \fi}
  13955. {\if\edition\pythonEd\pythonColor
  13956. \[
  13957. \begin{array}{l}
  13958. \gray{\LintASTPython{}} \\ \hline
  13959. \gray{\LvarASTPython{}} \\ \hline
  13960. \gray{\LifASTPython{}} \\ \hline
  13961. \gray{\LwhileASTPython} \\ \hline
  13962. \gray{\LtupASTPython} \\ \hline
  13963. \LfunASTPython \\
  13964. \begin{array}{rcl}
  13965. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13966. \end{array}
  13967. \end{array}
  13968. \]
  13969. \fi}
  13970. \end{tcolorbox}
  13971. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13972. \label{fig:Lfun-syntax}
  13973. \index{subject}{Lfun@\LangFun{} abstract syntax}
  13974. \end{figure}
  13975. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13976. representative example of defining and using functions in \LangFun{}.
  13977. We define a function \code{map} that applies some other function
  13978. \code{f} to both elements of a tuple and returns a new tuple
  13979. containing the results. We also define a function \code{inc}. The
  13980. program applies \code{map} to \code{inc} and
  13981. %
  13982. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13983. %
  13984. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13985. %
  13986. from which we return \code{42}.
  13987. \begin{figure}[tbp]
  13988. \begin{tcolorbox}[colback=white]
  13989. {\if\edition\racketEd
  13990. \begin{lstlisting}
  13991. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13992. : (Vector Integer Integer)
  13993. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13994. (define (inc [x : Integer]) : Integer
  13995. (+ x 1))
  13996. (vector-ref (map inc (vector 0 41)) 1)
  13997. \end{lstlisting}
  13998. \fi}
  13999. {\if\edition\pythonEd\pythonColor
  14000. \begin{lstlisting}
  14001. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  14002. return f(v[0]), f(v[1])
  14003. def inc(x : int) -> int:
  14004. return x + 1
  14005. print(map(inc, (0, 41))[1])
  14006. \end{lstlisting}
  14007. \fi}
  14008. \end{tcolorbox}
  14009. \caption{Example of using functions in \LangFun{}.}
  14010. \label{fig:Lfun-function-example}
  14011. \end{figure}
  14012. The definitional interpreter for \LangFun{} is shown in
  14013. figure~\ref{fig:interp-Lfun}. The case for the
  14014. %
  14015. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14016. %
  14017. AST is responsible for setting up the mutual recursion between the
  14018. top-level function definitions.
  14019. %
  14020. \racket{We use the classic back-patching
  14021. \index{subject}{back-patching} approach that uses mutable variables
  14022. and makes two passes over the function
  14023. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  14024. top-level environment using a mutable cons cell for each function
  14025. definition. Note that the \code{lambda}\index{subject}{lambda} value
  14026. for each function is incomplete; it does not yet include the environment.
  14027. Once the top-level environment has been constructed, we iterate over it and
  14028. update the \code{lambda} values to use the top-level environment.}
  14029. %
  14030. \python{We create a dictionary named \code{env} and fill it in
  14031. by mapping each function name to a new \code{Function} value,
  14032. each of which stores a reference to the \code{env}.
  14033. (We define the class \code{Function} for this purpose.)}
  14034. %
  14035. To interpret a function \racket{application}\python{call}, we match
  14036. the result of the function expression to obtain a function value. We
  14037. then extend the function's environment with the mapping of parameters to
  14038. argument values. Finally, we interpret the body of the function in
  14039. this extended environment.
  14040. \begin{figure}[tp]
  14041. \begin{tcolorbox}[colback=white]
  14042. {\if\edition\racketEd
  14043. \begin{lstlisting}
  14044. (define interp-Lfun-class
  14045. (class interp-Lvec-class
  14046. (super-new)
  14047. (define/override ((interp-exp env) e)
  14048. (define recur (interp-exp env))
  14049. (match e
  14050. [(Apply fun args)
  14051. (define fun-val (recur fun))
  14052. (define arg-vals (for/list ([e args]) (recur e)))
  14053. (match fun-val
  14054. [`(function (,xs ...) ,body ,fun-env)
  14055. (define params-args (for/list ([x xs] [arg arg-vals])
  14056. (cons x (box arg))))
  14057. (define new-env (append params-args fun-env))
  14058. ((interp-exp new-env) body)]
  14059. [else
  14060. (error 'interp-exp "expected function, not ~a" fun-val)])]
  14061. [else ((super interp-exp env) e)]
  14062. ))
  14063. (define/public (interp-def d)
  14064. (match d
  14065. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  14066. (cons f (box `(function ,xs ,body ())))]))
  14067. (define/override (interp-program p)
  14068. (match p
  14069. [(ProgramDefsExp info ds body)
  14070. (let ([top-level (for/list ([d ds]) (interp-def d))])
  14071. (for/list ([f (in-dict-values top-level)])
  14072. (set-box! f (match (unbox f)
  14073. [`(function ,xs ,body ())
  14074. `(function ,xs ,body ,top-level)])))
  14075. ((interp-exp top-level) body))]))
  14076. ))
  14077. (define (interp-Lfun p)
  14078. (send (new interp-Lfun-class) interp-program p))
  14079. \end{lstlisting}
  14080. \fi}
  14081. {\if\edition\pythonEd\pythonColor
  14082. \begin{lstlisting}
  14083. class InterpLfun(InterpLtup):
  14084. def apply_fun(self, fun, args, e):
  14085. match fun:
  14086. case Function(name, xs, body, env):
  14087. new_env = env.copy().update(zip(xs, args))
  14088. return self.interp_stmts(body, new_env)
  14089. case _:
  14090. raise Exception('apply_fun: unexpected: ' + repr(fun))
  14091. def interp_exp(self, e, env):
  14092. match e:
  14093. case Call(Name('input_int'), []):
  14094. return super().interp_exp(e, env)
  14095. case Call(func, args):
  14096. f = self.interp_exp(func, env)
  14097. vs = [self.interp_exp(arg, env) for arg in args]
  14098. return self.apply_fun(f, vs, e)
  14099. case _:
  14100. return super().interp_exp(e, env)
  14101. def interp_stmt(self, s, env, cont):
  14102. match s:
  14103. case Return(value):
  14104. return self.interp_exp(value, env)
  14105. case FunctionDef(name, params, bod, dl, returns, comment):
  14106. if isinstance(params, ast.arguments):
  14107. ps = [p.arg for p in params.args]
  14108. else:
  14109. ps = [x for (x,t) in params]
  14110. env[name] = Function(name, ps, bod, env)
  14111. return self.interp_stmts(cont, env)
  14112. case _:
  14113. return super().interp_stmt(s, env, cont)
  14114. def interp(self, p):
  14115. match p:
  14116. case Module(ss):
  14117. env = {}
  14118. self.interp_stmts(ss, env)
  14119. if 'main' in env.keys():
  14120. self.apply_fun(env['main'], [], None)
  14121. case _:
  14122. raise Exception('interp: unexpected ' + repr(p))
  14123. \end{lstlisting}
  14124. \fi}
  14125. \end{tcolorbox}
  14126. \caption{Interpreter for the \LangFun{} language.}
  14127. \label{fig:interp-Lfun}
  14128. \end{figure}
  14129. %\margincomment{TODO: explain type checker}
  14130. The type checker for \LangFun{} is shown in
  14131. figure~\ref{fig:type-check-Lfun}.
  14132. %
  14133. \python{(We omit the code that parses function parameters into the
  14134. simpler abstract syntax.)}
  14135. %
  14136. Similarly to the interpreter, the case for the
  14137. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  14138. %
  14139. AST is responsible for setting up the mutual recursion between the
  14140. top-level function definitions. We begin by creating a mapping
  14141. \code{env} from every function name to its type. We then type check
  14142. the program using this mapping.
  14143. %
  14144. \python{To check a function definition, we copy and extend the
  14145. \code{env} with the parameters of the function. We then type check
  14146. the body of the function and obtain the actual return type
  14147. \code{rt}, which is either the type of the expression in a
  14148. \code{return} statement or the \code{VoidType} if control reaches
  14149. the end of the function without a \code{return} statement. (If
  14150. there are multiple \code{return} statements, the types of their
  14151. expressions must agree.) Finally, we check that the actual return
  14152. type \code{rt} is equal to the declared return type \code{returns}.}
  14153. %
  14154. To check a function \racket{application}\python{call}, we match
  14155. the type of the function expression to a function type and check that
  14156. the types of the argument expressions are equal to the function's
  14157. parameter types. The type of the \racket{application}\python{call} as
  14158. a whole is the return type from the function type.
  14159. \begin{figure}[tp]
  14160. \begin{tcolorbox}[colback=white]
  14161. {\if\edition\racketEd
  14162. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14163. (define type-check-Lfun-class
  14164. (class type-check-Lvec-class
  14165. (super-new)
  14166. (inherit check-type-equal?)
  14167. (define/public (type-check-apply env e es)
  14168. (define-values (e^ ty) ((type-check-exp env) e))
  14169. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14170. ((type-check-exp env) e)))
  14171. (match ty
  14172. [`(,ty^* ... -> ,rt)
  14173. (for ([arg-ty ty*] [param-ty ty^*])
  14174. (check-type-equal? arg-ty param-ty (Apply e es)))
  14175. (values e^ e* rt)]))
  14176. (define/override (type-check-exp env)
  14177. (lambda (e)
  14178. (match e
  14179. [(FunRef f n)
  14180. (values (FunRef f n) (dict-ref env f))]
  14181. [(Apply e es)
  14182. (define-values (e^ es^ rt) (type-check-apply env e es))
  14183. (values (Apply e^ es^) rt)]
  14184. [(Call e es)
  14185. (define-values (e^ es^ rt) (type-check-apply env e es))
  14186. (values (Call e^ es^) rt)]
  14187. [else ((super type-check-exp env) e)])))
  14188. (define/public (type-check-def env)
  14189. (lambda (e)
  14190. (match e
  14191. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14192. (define new-env (append (map cons xs ps) env))
  14193. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14194. (check-type-equal? ty^ rt body)
  14195. (Def f p:t* rt info body^)])))
  14196. (define/public (fun-def-type d)
  14197. (match d
  14198. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14199. (define/override (type-check-program e)
  14200. (match e
  14201. [(ProgramDefsExp info ds body)
  14202. (define env (for/list ([d ds])
  14203. (cons (Def-name d) (fun-def-type d))))
  14204. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14205. (define-values (body^ ty) ((type-check-exp env) body))
  14206. (check-type-equal? ty 'Integer body)
  14207. (ProgramDefsExp info ds^ body^)]))))
  14208. (define (type-check-Lfun p)
  14209. (send (new type-check-Lfun-class) type-check-program p))
  14210. \end{lstlisting}
  14211. \fi}
  14212. {\if\edition\pythonEd\pythonColor
  14213. \begin{lstlisting}
  14214. class TypeCheckLfun(TypeCheckLtup):
  14215. def type_check_exp(self, e, env):
  14216. match e:
  14217. case Call(Name('input_int'), []):
  14218. return super().type_check_exp(e, env)
  14219. case Call(func, args):
  14220. func_t = self.type_check_exp(func, env)
  14221. args_t = [self.type_check_exp(arg, env) for arg in args]
  14222. match func_t:
  14223. case FunctionType(params_t, return_t):
  14224. for (arg_t, param_t) in zip(args_t, params_t):
  14225. check_type_equal(param_t, arg_t, e)
  14226. return return_t
  14227. case _:
  14228. raise Exception('type_check_exp: in call, unexpected ' +
  14229. repr(func_t))
  14230. case _:
  14231. return super().type_check_exp(e, env)
  14232. def type_check_stmts(self, ss, env):
  14233. if len(ss) == 0:
  14234. return VoidType()
  14235. match ss[0]:
  14236. case FunctionDef(name, params, body, dl, returns, comment):
  14237. new_env = env.copy().update(params)
  14238. rt = self.type_check_stmts(body, new_env)
  14239. check_type_equal(returns, rt, ss[0])
  14240. return self.type_check_stmts(ss[1:], env)
  14241. case Return(value):
  14242. return self.type_check_exp(value, env)
  14243. case _:
  14244. return super().type_check_stmts(ss, env)
  14245. def type_check(self, p):
  14246. match p:
  14247. case Module(body):
  14248. env = {}
  14249. for s in body:
  14250. match s:
  14251. case FunctionDef(name, params, bod, dl, returns, comment):
  14252. if name in env:
  14253. raise Exception('type_check: function ' +
  14254. repr(name) + ' defined twice')
  14255. params_t = [t for (x,t) in params]
  14256. env[name] = FunctionType(params_t, returns)
  14257. self.type_check_stmts(body, env)
  14258. case _:
  14259. raise Exception('type_check: unexpected ' + repr(p))
  14260. \end{lstlisting}
  14261. \fi}
  14262. \end{tcolorbox}
  14263. \caption{Type checker for the \LangFun{} language.}
  14264. \label{fig:type-check-Lfun}
  14265. \end{figure}
  14266. \clearpage
  14267. \section{Functions in x86}
  14268. \label{sec:fun-x86}
  14269. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14270. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14271. %% \margincomment{\tiny Talk about the return address on the
  14272. %% stack and what callq and retq does.\\ --Jeremy }
  14273. The x86 architecture provides a few features to support the
  14274. implementation of functions. We have already seen that there are
  14275. labels in x86 so that one can refer to the location of an instruction,
  14276. as is needed for jump instructions. Labels can also be used to mark
  14277. the beginning of the instructions for a function. Going further, we
  14278. can obtain the address of a label by using the \key{leaq}
  14279. instruction. For example, the following puts the address of the
  14280. \code{inc} label into the \code{rbx} register:
  14281. \begin{lstlisting}
  14282. leaq inc(%rip), %rbx
  14283. \end{lstlisting}
  14284. Recall from section~\ref{sec:select-instructions-gc} that
  14285. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14286. addressing.
  14287. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14288. to functions whose locations were given by a label, such as
  14289. \code{read\_int}. To support function calls in this chapter we instead
  14290. jump to functions whose location are given by an address in
  14291. a register; that is, we use \emph{indirect function calls}. The
  14292. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14293. before the register name.\index{subject}{indirect function call}
  14294. \begin{lstlisting}
  14295. callq *%rbx
  14296. \end{lstlisting}
  14297. \subsection{Calling Conventions}
  14298. \label{sec:calling-conventions-fun}
  14299. \index{subject}{calling conventions}
  14300. The \code{callq} instruction provides partial support for implementing
  14301. functions: it pushes the return address on the stack and it jumps to
  14302. the target. However, \code{callq} does not handle
  14303. \begin{enumerate}
  14304. \item parameter passing,
  14305. \item pushing frames on the procedure call stack and popping them off,
  14306. or
  14307. \item determining how registers are shared by different functions.
  14308. \end{enumerate}
  14309. Regarding parameter passing, recall that the x86-64 calling
  14310. convention for Unix-based systems uses the following six registers to
  14311. pass arguments to a function, in the given order:
  14312. \begin{lstlisting}
  14313. rdi rsi rdx rcx r8 r9
  14314. \end{lstlisting}
  14315. If there are more than six arguments, then the calling convention
  14316. mandates using space on the frame of the caller for the rest of the
  14317. arguments. However, to ease the implementation of efficient tail calls
  14318. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14319. arguments.
  14320. %
  14321. The return value of the function is stored in register \code{rax}.
  14322. Regarding frames \index{subject}{frame} and the procedure call stack,
  14323. \index{subject}{procedure call stack} recall from
  14324. section~\ref{sec:x86} that the stack grows down and each function call
  14325. uses a chunk of space on the stack called a frame. The caller sets the
  14326. stack pointer, register \code{rsp}, to the last data item in its
  14327. frame. The callee must not change anything in the caller's frame, that
  14328. is, anything that is at or above the stack pointer. The callee is free
  14329. to use locations that are below the stack pointer.
  14330. Recall that we store variables of tuple type on the root stack. So,
  14331. the prelude\index{subject}{prelude} of a function needs to move the
  14332. root stack pointer \code{r15} up according to the number of variables
  14333. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14334. move the root stack pointer back down. Also, the prelude must
  14335. initialize to \code{0} this frame's slots in the root stack to signal
  14336. to the garbage collector that those slots do not yet contain a valid
  14337. pointer. Otherwise the garbage collector will interpret the garbage
  14338. bits in those slots as memory addresses and try to traverse them,
  14339. causing serious mayhem!
  14340. Regarding the sharing of registers between different functions, recall
  14341. from section~\ref{sec:calling-conventions} that the registers are
  14342. divided into two groups, the caller-saved registers and the
  14343. callee-saved registers. The caller should assume that all the
  14344. caller-saved registers are overwritten with arbitrary values by the
  14345. callee. For that reason we recommend in
  14346. section~\ref{sec:calling-conventions} that variables that are live
  14347. during a function call should not be assigned to caller-saved
  14348. registers.
  14349. On the flip side, if the callee wants to use a callee-saved register,
  14350. the callee must save the contents of those registers on their stack
  14351. frame and then put them back prior to returning to the caller. For
  14352. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14353. the register allocator assigns a variable to a callee-saved register,
  14354. then the prelude of the \code{main} function must save that register
  14355. to the stack and the conclusion of \code{main} must restore it. This
  14356. recommendation now generalizes to all functions.
  14357. Recall that the base pointer, register \code{rbp}, is used as a
  14358. point of reference within a frame, so that each local variable can be
  14359. accessed at a fixed offset from the base pointer
  14360. (section~\ref{sec:x86}).
  14361. %
  14362. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14363. frames.
  14364. \begin{figure}[tbp]
  14365. \centering
  14366. \begin{tcolorbox}[colback=white]
  14367. \begin{tabular}{r|r|l|l} \hline
  14368. Caller View & Callee View & Contents & Frame \\ \hline
  14369. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14370. 0(\key{\%rbp}) & & old \key{rbp} \\
  14371. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14372. \ldots & & \ldots \\
  14373. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14374. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14375. \ldots & & \ldots \\
  14376. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14377. %% & & \\
  14378. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14379. %% & \ldots & \ldots \\
  14380. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14381. \hline
  14382. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14383. & 0(\key{\%rbp}) & old \key{rbp} \\
  14384. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14385. & \ldots & \ldots \\
  14386. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14387. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14388. & \ldots & \ldots \\
  14389. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14390. \end{tabular}
  14391. \end{tcolorbox}
  14392. \caption{Memory layout of caller and callee frames.}
  14393. \label{fig:call-frames}
  14394. \end{figure}
  14395. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14396. %% local variables and for storing the values of callee-saved registers
  14397. %% (we shall refer to all of these collectively as ``locals''), and that
  14398. %% at the beginning of a function we move the stack pointer \code{rsp}
  14399. %% down to make room for them.
  14400. %% We recommend storing the local variables
  14401. %% first and then the callee-saved registers, so that the local variables
  14402. %% can be accessed using \code{rbp} the same as before the addition of
  14403. %% functions.
  14404. %% To make additional room for passing arguments, we shall
  14405. %% move the stack pointer even further down. We count how many stack
  14406. %% arguments are needed for each function call that occurs inside the
  14407. %% body of the function and find their maximum. Adding this number to the
  14408. %% number of locals gives us how much the \code{rsp} should be moved at
  14409. %% the beginning of the function. In preparation for a function call, we
  14410. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14411. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14412. %% so on.
  14413. %% Upon calling the function, the stack arguments are retrieved by the
  14414. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14415. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14416. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14417. %% the layout of the caller and callee frames. Notice how important it is
  14418. %% that we correctly compute the maximum number of arguments needed for
  14419. %% function calls; if that number is too small then the arguments and
  14420. %% local variables will smash into each other!
  14421. \subsection{Efficient Tail Calls}
  14422. \label{sec:tail-call}
  14423. In general, the amount of stack space used by a program is determined
  14424. by the longest chain of nested function calls. That is, if function
  14425. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14426. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14427. large if functions are recursive. However, in some cases we can
  14428. arrange to use only a constant amount of space for a long chain of
  14429. nested function calls.
  14430. A \emph{tail call}\index{subject}{tail call} is a function call that
  14431. happens as the last action in a function body. For example, in the
  14432. following program, the recursive call to \code{tail\_sum} is a tail
  14433. call:
  14434. \begin{center}
  14435. {\if\edition\racketEd
  14436. \begin{lstlisting}
  14437. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14438. (if (eq? n 0)
  14439. r
  14440. (tail_sum (- n 1) (+ n r))))
  14441. (+ (tail_sum 3 0) 36)
  14442. \end{lstlisting}
  14443. \fi}
  14444. {\if\edition\pythonEd\pythonColor
  14445. \begin{lstlisting}
  14446. def tail_sum(n : int, r : int) -> int:
  14447. if n == 0:
  14448. return r
  14449. else:
  14450. return tail_sum(n - 1, n + r)
  14451. print(tail_sum(3, 0) + 36)
  14452. \end{lstlisting}
  14453. \fi}
  14454. \end{center}
  14455. At a tail call, the frame of the caller is no longer needed, so we can
  14456. pop the caller's frame before making the tail
  14457. call. \index{subject}{frame} With this approach, a recursive function
  14458. that makes only tail calls ends up using a constant amount of stack
  14459. space. \racket{Functional languages like Racket rely heavily on
  14460. recursive functions, so the definition of Racket \emph{requires}
  14461. that all tail calls be optimized in this way.}
  14462. Some care is needed with regard to argument passing in tail calls. As
  14463. mentioned, for arguments beyond the sixth, the convention is to use
  14464. space in the caller's frame for passing arguments. However, for a
  14465. tail call we pop the caller's frame and can no longer use it. An
  14466. alternative is to use space in the callee's frame for passing
  14467. arguments. However, this option is also problematic because the caller
  14468. and callee's frames overlap in memory. As we begin to copy the
  14469. arguments from their sources in the caller's frame, the target
  14470. locations in the callee's frame might collide with the sources for
  14471. later arguments! We solve this problem by using the heap instead of
  14472. the stack for passing more than six arguments
  14473. (section~\ref{sec:limit-functions-r4}).
  14474. As mentioned, for a tail call we pop the caller's frame prior to
  14475. making the tail call. The instructions for popping a frame are the
  14476. instructions that we usually place in the conclusion of a
  14477. function. Thus, we also need to place such code immediately before
  14478. each tail call. These instructions include restoring the callee-saved
  14479. registers, so it is fortunate that the argument passing registers are
  14480. all caller-saved registers.
  14481. One note remains regarding which instruction to use to make the tail
  14482. call. When the callee is finished, it should not return to the current
  14483. function but instead return to the function that called the current
  14484. one. Thus, the return address that is already on the stack is the
  14485. right one, and we should not use \key{callq} to make the tail call
  14486. because that would overwrite the return address. Instead we simply use
  14487. the \key{jmp} instruction. As with the indirect function call, we write
  14488. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14489. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14490. jump target because the conclusion can overwrite just about everything
  14491. else.
  14492. \begin{lstlisting}
  14493. jmp *%rax
  14494. \end{lstlisting}
  14495. \section{Shrink \LangFun{}}
  14496. \label{sec:shrink-r4}
  14497. The \code{shrink} pass performs a minor modification to ease the
  14498. later passes. This pass introduces an explicit \code{main} function
  14499. that gobbles up all the top-level statements of the module.
  14500. %
  14501. \racket{It also changes the top \code{ProgramDefsExp} form to
  14502. \code{ProgramDefs}.}
  14503. {\if\edition\racketEd
  14504. \begin{lstlisting}
  14505. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14506. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14507. \end{lstlisting}
  14508. where $\itm{mainDef}$ is
  14509. \begin{lstlisting}
  14510. (Def 'main '() 'Integer '() |$\Exp'$|)
  14511. \end{lstlisting}
  14512. \fi}
  14513. {\if\edition\pythonEd\pythonColor
  14514. \begin{lstlisting}
  14515. Module(|$\Def\ldots\Stmt\ldots$|)
  14516. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14517. \end{lstlisting}
  14518. where $\itm{mainDef}$ is
  14519. \begin{lstlisting}
  14520. FunctionDef('main', [], [|$\Stmt\ldots$|Return(Constant(0))], None, IntType(), None)
  14521. \end{lstlisting}
  14522. \fi}
  14523. \section{Reveal Functions and the \LangFunRef{} Language}
  14524. \label{sec:reveal-functions-r4}
  14525. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14526. in that it conflates the use of function names and local
  14527. variables. This is a problem because we need to compile the use of a
  14528. function name differently from the use of a local variable. In
  14529. particular, we use \code{leaq} to convert the function name (a label
  14530. in x86) to an address in a register. Thus, we create a new pass that
  14531. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14532. $n$ is the arity of the function.\python{\footnote{The arity is not
  14533. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14534. This pass is named \code{reveal\_functions} and the output language
  14535. is \LangFunRef{}\index{subject}{Lfunref@\LangFunRef{}}.
  14536. %is defined in figure~\ref{fig:f1-syntax}.
  14537. %% The concrete syntax for a
  14538. %% function reference is $\CFUNREF{f}$.
  14539. %% \begin{figure}[tp]
  14540. %% \centering
  14541. %% \fbox{
  14542. %% \begin{minipage}{0.96\textwidth}
  14543. %% {\if\edition\racketEd
  14544. %% \[
  14545. %% \begin{array}{lcl}
  14546. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14547. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14548. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14549. %% \end{array}
  14550. %% \]
  14551. %% \fi}
  14552. %% {\if\edition\pythonEd\pythonColor
  14553. %% \[
  14554. %% \begin{array}{lcl}
  14555. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14556. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14557. %% \end{array}
  14558. %% \]
  14559. %% \fi}
  14560. %% \end{minipage}
  14561. %% }
  14562. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14563. %% (figure~\ref{fig:Lfun-syntax}).}
  14564. %% \label{fig:f1-syntax}
  14565. %% \end{figure}
  14566. %% Distinguishing between calls in tail position and non-tail position
  14567. %% requires the pass to have some notion of context. We recommend using
  14568. %% two mutually recursive functions, one for processing expressions in
  14569. %% tail position and another for the rest.
  14570. \racket{Placing this pass after \code{uniquify} will make sure that
  14571. there are no local variables and functions that share the same
  14572. name.}
  14573. %
  14574. The \code{reveal\_functions} pass should come before the
  14575. \code{remove\_complex\_operands} pass because function references
  14576. should be categorized as complex expressions.
  14577. \section{Limit Functions}
  14578. \label{sec:limit-functions-r4}
  14579. Recall that we wish to limit the number of function parameters to six
  14580. so that we do not need to use the stack for argument passing, which
  14581. makes it easier to implement efficient tail calls. However, because
  14582. the input language \LangFun{} supports arbitrary numbers of function
  14583. arguments, we have some work to do! The \code{limit\_functions} pass
  14584. transforms functions and function calls that involve more than six
  14585. arguments to pass the first five arguments as usual, but it packs the
  14586. rest of the arguments into a tuple and passes it as the sixth
  14587. argument.\footnote{The implementation this pass can be postponed to
  14588. last because you can test the rest of the passes on functions with
  14589. six or fewer parameters.}
  14590. Each function definition with seven or more parameters is transformed as
  14591. follows:
  14592. {\if\edition\racketEd
  14593. \begin{lstlisting}
  14594. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14595. |$\Rightarrow$|
  14596. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14597. \end{lstlisting}
  14598. \fi}
  14599. {\if\edition\pythonEd\pythonColor
  14600. \begin{lstlisting}
  14601. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14602. |$\Rightarrow$|
  14603. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14604. |$T_r$|, None, |$\itm{body}'$|, None)
  14605. \end{lstlisting}
  14606. \fi}
  14607. %
  14608. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14609. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14610. the $k$th element of the tuple, where $k = i - 6$.
  14611. %
  14612. {\if\edition\racketEd
  14613. \begin{lstlisting}
  14614. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14615. \end{lstlisting}
  14616. \fi}
  14617. {\if\edition\pythonEd\pythonColor
  14618. \begin{lstlisting}
  14619. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14620. \end{lstlisting}
  14621. \fi}
  14622. For function calls with too many arguments, the \code{limit\_functions}
  14623. pass transforms them in the following way:
  14624. \begin{tabular}{lll}
  14625. \begin{minipage}{0.3\textwidth}
  14626. {\if\edition\racketEd
  14627. \begin{lstlisting}
  14628. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14629. \end{lstlisting}
  14630. \fi}
  14631. {\if\edition\pythonEd\pythonColor
  14632. \begin{lstlisting}
  14633. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14634. \end{lstlisting}
  14635. \fi}
  14636. \end{minipage}
  14637. &
  14638. $\Rightarrow$
  14639. &
  14640. \begin{minipage}{0.5\textwidth}
  14641. {\if\edition\racketEd
  14642. \begin{lstlisting}
  14643. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14644. \end{lstlisting}
  14645. \fi}
  14646. {\if\edition\pythonEd\pythonColor
  14647. \begin{lstlisting}
  14648. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14649. \end{lstlisting}
  14650. \fi}
  14651. \end{minipage}
  14652. \end{tabular}
  14653. \section{Remove Complex Operands}
  14654. \label{sec:rco-r4}
  14655. The primary decisions to make for this pass are whether to classify
  14656. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14657. atomic or complex expressions. Recall that an atomic expression
  14658. ends up as an immediate argument of an x86 instruction. Function
  14659. application translates to a sequence of instructions, so
  14660. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14661. a complex expression. On the other hand, the arguments of
  14662. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14663. expressions.
  14664. %
  14665. Regarding \code{FunRef}, as discussed previously, the function label
  14666. needs to be converted to an address using the \code{leaq}
  14667. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14668. needs to be classified as a complex expression so that we generate an
  14669. assignment statement with a left-hand side that can serve as the
  14670. target of the \code{leaq}.
  14671. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14672. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14673. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14674. and augments programs to include a list of function definitions.
  14675. %
  14676. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14677. \newcommand{\LfunMonadASTRacket}{
  14678. \begin{array}{lcl}
  14679. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14680. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14681. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14682. \end{array}
  14683. }
  14684. \newcommand{\LfunMonadASTPython}{
  14685. \begin{array}{lcl}
  14686. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14687. \MID \key{TupleType}\LS\Type^+\RS\\
  14688. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14689. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14690. \Stmt &::=& \RETURN{\Exp} \\
  14691. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14692. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14693. \end{array}
  14694. }
  14695. \begin{figure}[tp]
  14696. \centering
  14697. \begin{tcolorbox}[colback=white]
  14698. \footnotesize
  14699. {\if\edition\racketEd
  14700. \[
  14701. \begin{array}{l}
  14702. \gray{\LvarMonadASTRacket} \\ \hline
  14703. \gray{\LifMonadASTRacket} \\ \hline
  14704. \gray{\LwhileMonadASTRacket} \\ \hline
  14705. \gray{\LtupMonadASTRacket} \\ \hline
  14706. \LfunMonadASTRacket \\
  14707. \begin{array}{rcl}
  14708. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14709. \end{array}
  14710. \end{array}
  14711. \]
  14712. \fi}
  14713. {\if\edition\pythonEd\pythonColor
  14714. \[
  14715. \begin{array}{l}
  14716. \gray{\LvarMonadASTPython} \\ \hline
  14717. \gray{\LifMonadASTPython} \\ \hline
  14718. \gray{\LwhileMonadASTPython} \\ \hline
  14719. \gray{\LtupMonadASTPython} \\ \hline
  14720. \LfunMonadASTPython \\
  14721. \begin{array}{rcl}
  14722. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14723. \end{array}
  14724. \end{array}
  14725. \]
  14726. \fi}
  14727. \end{tcolorbox}
  14728. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14729. \label{fig:Lfun-anf-syntax}
  14730. \index{subject}{Lfunmon@\LangFunANF{} abstract syntax}
  14731. \end{figure}
  14732. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14733. %% \LangFunANF{} of this pass.
  14734. %% \begin{figure}[tp]
  14735. %% \centering
  14736. %% \fbox{
  14737. %% \begin{minipage}{0.96\textwidth}
  14738. %% \small
  14739. %% \[
  14740. %% \begin{array}{rcl}
  14741. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14742. %% \MID \VOID{} } \\
  14743. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14744. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14745. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14746. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14747. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14748. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14749. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14750. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14751. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14752. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14753. %% \end{array}
  14754. %% \]
  14755. %% \end{minipage}
  14756. %% }
  14757. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14758. %% \label{fig:Lfun-anf-syntax}
  14759. %% \end{figure}
  14760. \section{Explicate Control and the \LangCFun{} Language}
  14761. \label{sec:explicate-control-r4}
  14762. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14763. output of \code{explicate\_control}.
  14764. %
  14765. %% \racket{(The concrete syntax is given in
  14766. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14767. %
  14768. \racket{The auxiliary functions for assignment and tail contexts should
  14769. be updated with cases for \code{Apply} and \code{FunRef}.}
  14770. The auxiliary function for predicate context should be updated for
  14771. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14772. \code{FunRef} cannot be a Boolean.)
  14773. %
  14774. \racket{In assignment and predicate contexts,
  14775. \code{Apply} becomes \code{Call}, whereas
  14776. in tail position \code{Apply} becomes \code{TailCall}.}
  14777. %
  14778. We recommend defining a new auxiliary function for processing function
  14779. definitions. This code is similar to the case for \code{Program} in
  14780. \LangVecANF{}. The top-level \code{explicate\_control} function that
  14781. handles the \code{ProgramDefs} form of \LangFunANF{} can apply this
  14782. new function to all function definitions.
  14783. {\if\edition\pythonEd\pythonColor
  14784. The translation of \code{Return} statements requires a new auxiliary
  14785. function to handle expressions in tail context, called
  14786. \code{explicate\_tail}. The function should take an expression and the
  14787. dictionary of basic blocks and produce a list of statements in the
  14788. \LangCFun{} language. The \code{explicate\_tail} function should
  14789. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14790. and a default case for other kinds of expressions. The default case
  14791. should produce a \code{Return} statement. The case for \code{Call}
  14792. should change it into \code{TailCall}. The other cases should
  14793. recursively process their subexpressions and statements, choosing the
  14794. appropriate explicate functions for the various contexts.
  14795. \fi}
  14796. \newcommand{\CfunASTRacket}{
  14797. \begin{array}{lcl}
  14798. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14799. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14800. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14801. \end{array}
  14802. }
  14803. \newcommand{\CfunASTPython}{
  14804. \begin{array}{lcl}
  14805. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14806. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14807. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14808. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14809. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14810. \end{array}
  14811. }
  14812. \begin{figure}[tp]
  14813. \begin{tcolorbox}[colback=white]
  14814. \footnotesize
  14815. {\if\edition\racketEd
  14816. \[
  14817. \begin{array}{l}
  14818. \gray{\CvarASTRacket} \\ \hline
  14819. \gray{\CifASTRacket} \\ \hline
  14820. \gray{\CloopASTRacket} \\ \hline
  14821. \gray{\CtupASTRacket} \\ \hline
  14822. \CfunASTRacket \\
  14823. \begin{array}{lcl}
  14824. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14825. \end{array}
  14826. \end{array}
  14827. \]
  14828. \fi}
  14829. {\if\edition\pythonEd\pythonColor
  14830. \[
  14831. \begin{array}{l}
  14832. \gray{\CifASTPython} \\ \hline
  14833. \gray{\CtupASTPython} \\ \hline
  14834. \CfunASTPython \\
  14835. \begin{array}{lcl}
  14836. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14837. \end{array}
  14838. \end{array}
  14839. \]
  14840. \fi}
  14841. \end{tcolorbox}
  14842. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14843. \label{fig:c3-syntax}
  14844. \index{subject}{Cfun@\LangCFun{} abstract syntax}
  14845. \end{figure}
  14846. \clearpage
  14847. \section{Select Instructions and the \LangXIndCall{} Language}
  14848. \label{sec:select-r4}
  14849. \index{subject}{select instructions}
  14850. The output of select instructions is a program in the \LangXIndCall{}
  14851. language; the definition of its concrete syntax is shown in
  14852. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14853. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14854. directive on the labels of function definitions to make sure the
  14855. bottom three bits are zero, which we put to use in
  14856. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14857. this section. \index{subject}{x86}
  14858. \newcommand{\GrammarXIndCall}{
  14859. \begin{array}{lcl}
  14860. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14861. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14862. \Block &::= & \Instr^{+} \\
  14863. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14864. \end{array}
  14865. }
  14866. \newcommand{\ASTXIndCallRacket}{
  14867. \begin{array}{lcl}
  14868. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14869. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14870. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14871. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14872. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14873. \end{array}
  14874. }
  14875. \begin{figure}[tp]
  14876. \begin{tcolorbox}[colback=white]
  14877. \small
  14878. {\if\edition\racketEd
  14879. \[
  14880. \begin{array}{l}
  14881. \gray{\GrammarXIntRacket} \\ \hline
  14882. \gray{\GrammarXIfRacket} \\ \hline
  14883. \gray{\GrammarXGlobal} \\ \hline
  14884. \GrammarXIndCall \\
  14885. \begin{array}{lcl}
  14886. \LangXIndCallM{} &::= & \Def^{*}
  14887. \end{array}
  14888. \end{array}
  14889. \]
  14890. \fi}
  14891. {\if\edition\pythonEd
  14892. \[
  14893. \begin{array}{l}
  14894. \gray{\GrammarXIntPython} \\ \hline
  14895. \gray{\GrammarXIfPython} \\ \hline
  14896. \gray{\GrammarXGlobal} \\ \hline
  14897. \GrammarXIndCall \\
  14898. \begin{array}{lcl}
  14899. \LangXIndCallM{} &::= & \Def^{*}
  14900. \end{array}
  14901. \end{array}
  14902. \]
  14903. \fi}
  14904. \end{tcolorbox}
  14905. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14906. \label{fig:x86-3-concrete}
  14907. \end{figure}
  14908. \begin{figure}[tp]
  14909. \begin{tcolorbox}[colback=white]
  14910. \small
  14911. {\if\edition\racketEd
  14912. \[\arraycolsep=3pt
  14913. \begin{array}{l}
  14914. \gray{\ASTXIntRacket} \\ \hline
  14915. \gray{\ASTXIfRacket} \\ \hline
  14916. \gray{\ASTXGlobalRacket} \\ \hline
  14917. \ASTXIndCallRacket \\
  14918. \begin{array}{lcl}
  14919. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14920. \end{array}
  14921. \end{array}
  14922. \]
  14923. \fi}
  14924. {\if\edition\pythonEd\pythonColor
  14925. \[
  14926. \begin{array}{lcl}
  14927. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14928. \MID \BYTEREG{\Reg} } \\
  14929. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14930. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14931. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14932. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14933. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14934. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14935. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14936. \end{array}
  14937. \]
  14938. \fi}
  14939. \end{tcolorbox}
  14940. \caption{The abstract syntax of \LangXIndCall{} (extends
  14941. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14942. \label{fig:x86-3}
  14943. \end{figure}
  14944. An assignment of a function reference to a variable becomes a
  14945. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14946. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14947. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14948. node, whose concrete syntax is instruction-pointer-relative
  14949. addressing.
  14950. \begin{center}
  14951. \begin{tabular}{lcl}
  14952. \begin{minipage}{0.35\textwidth}
  14953. {\if\edition\racketEd
  14954. \begin{lstlisting}
  14955. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14956. \end{lstlisting}
  14957. \fi}
  14958. {\if\edition\pythonEd\pythonColor
  14959. \begin{lstlisting}
  14960. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14961. \end{lstlisting}
  14962. \fi}
  14963. \end{minipage}
  14964. &
  14965. $\Rightarrow$\qquad\qquad
  14966. &
  14967. \begin{minipage}{0.3\textwidth}
  14968. \begin{lstlisting}
  14969. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14970. \end{lstlisting}
  14971. \end{minipage}
  14972. \end{tabular}
  14973. \end{center}
  14974. Regarding function definitions, we need to remove the parameters and
  14975. instead perform parameter passing using the conventions discussed in
  14976. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14977. registers. We recommend turning the parameters into local variables
  14978. and generating instructions at the beginning of the function to move
  14979. from the argument-passing registers
  14980. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14981. {\if\edition\racketEd
  14982. \begin{lstlisting}
  14983. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14984. |$\Rightarrow$|
  14985. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14986. \end{lstlisting}
  14987. \fi}
  14988. {\if\edition\pythonEd\pythonColor
  14989. \begin{lstlisting}
  14990. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14991. |$\Rightarrow$|
  14992. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14993. \end{lstlisting}
  14994. \fi}
  14995. The basic blocks $B'$ are the same as $B$ except that the
  14996. \code{start} block is modified to add the instructions for moving from
  14997. the argument registers to the parameter variables. So the \code{start}
  14998. block of $B$ shown on the left of the following is changed to the code
  14999. on the right:
  15000. \begin{center}
  15001. \begin{minipage}{0.3\textwidth}
  15002. \begin{lstlisting}
  15003. start:
  15004. |$\itm{instr}_1$|
  15005. |$\cdots$|
  15006. |$\itm{instr}_n$|
  15007. \end{lstlisting}
  15008. \end{minipage}
  15009. $\Rightarrow$
  15010. \begin{minipage}{0.3\textwidth}
  15011. \begin{lstlisting}
  15012. |$f$|start:
  15013. movq %rdi, |$x_1$|
  15014. movq %rsi, |$x_2$|
  15015. |$\cdots$|
  15016. |$\itm{instr}_1$|
  15017. |$\cdots$|
  15018. |$\itm{instr}_n$|
  15019. \end{lstlisting}
  15020. \end{minipage}
  15021. \end{center}
  15022. Recall that we use the label \code{start} for the initial block of a
  15023. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  15024. the conclusion of the program with \code{conclusion}, so that
  15025. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  15026. by a jump to \code{conclusion}. With the addition of function
  15027. definitions, there is a start block and conclusion for each function,
  15028. but their labels need to be unique. We recommend prepending the
  15029. function's name to \code{start} and \code{conclusion}, respectively,
  15030. to obtain unique labels.
  15031. \racket{The interpreter for \LangXIndCall{} needs to be given the
  15032. number of parameters the function expects, but the parameters are no
  15033. longer in the syntax of function definitions. Instead, add an entry
  15034. to $\itm{info}$ that maps \code{num-params} to the number of
  15035. parameters to construct $\itm{info}'$.}
  15036. By changing the parameters to local variables, we are giving the
  15037. register allocator control over which registers or stack locations to
  15038. use for them. If you implement the move-biasing challenge
  15039. (section~\ref{sec:move-biasing}), the register allocator will try to
  15040. assign the parameter variables to the corresponding argument register,
  15041. in which case the \code{patch\_instructions} pass will remove the
  15042. \code{movq} instruction. This happens in the example translation given
  15043. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  15044. the \code{add} function.
  15045. %
  15046. Also, note that the register allocator will perform liveness analysis
  15047. on this sequence of move instructions and build the interference
  15048. graph. So, for example, $x_1$ will be marked as interfering with
  15049. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  15050. which is good because otherwise the first \code{movq} would overwrite
  15051. the argument in \code{rsi} that is needed for $x_2$.
  15052. Next, consider the compilation of function calls. In the mirror image
  15053. of the handling of parameters in function definitions, the arguments
  15054. are moved to the argument-passing registers. Note that the function
  15055. is not given as a label, but its address is produced by the argument
  15056. $\itm{arg}_0$. So, we translate the call into an indirect function
  15057. call. The return value from the function is stored in \code{rax}, so
  15058. it needs to be moved into the \itm{lhs}.
  15059. \begin{lstlisting}
  15060. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  15061. |$\Rightarrow$|
  15062. movq |$\itm{arg}_1$|, %rdi
  15063. movq |$\itm{arg}_2$|, %rsi
  15064. |$\vdots$|
  15065. callq *|$\itm{arg}_0$|
  15066. movq %rax, |$\itm{lhs}$|
  15067. \end{lstlisting}
  15068. The \code{IndirectCallq} AST node includes an integer for the arity of
  15069. the function, that is, the number of parameters. That information is
  15070. useful in the \code{uncover\_live} pass for determining which
  15071. argument-passing registers are potentially read during the call.
  15072. For tail calls, the parameter passing is the same as non-tail calls:
  15073. generate instructions to move the arguments into the argument-passing
  15074. registers. After that we need to pop the frame from the procedure
  15075. call stack. However, we do not yet know how big the frame is; that
  15076. gets determined during register allocation. So, instead of generating
  15077. those instructions here, we invent a new instruction that means ``pop
  15078. the frame and then do an indirect jump,'' which we name
  15079. \code{TailJmp}. The abstract syntax for this instruction includes an
  15080. argument that specifies where to jump and an integer that represents
  15081. the arity of the function being called.
  15082. \section{Register Allocation}
  15083. \label{sec:register-allocation-r4}
  15084. The addition of functions requires some changes to all three aspects
  15085. of register allocation, which we discuss in the following subsections.
  15086. \subsection{Liveness Analysis}
  15087. \label{sec:liveness-analysis-r4}
  15088. \index{subject}{liveness analysis}
  15089. %% The rest of the passes need only minor modifications to handle the new
  15090. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  15091. %% \code{leaq}.
  15092. The \code{IndirectCallq} instruction should be treated like
  15093. \code{Callq} regarding its written locations $W$, in that they should
  15094. include all the caller-saved registers. Recall that the reason for
  15095. that is to force variables that are live across a function call to be assigned to callee-saved
  15096. registers or to be spilled to the stack.
  15097. Regarding the set of read locations $R$, the arity fields of
  15098. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  15099. argument-passing registers should be considered as read by those
  15100. instructions. Also, the target field of \code{TailJmp} and
  15101. \code{IndirectCallq} should be included in the set of read locations
  15102. $R$.
  15103. \subsection{Build Interference Graph}
  15104. \label{sec:build-interference-r4}
  15105. With the addition of function definitions, we compute a separate interference
  15106. graph for each function (not just one for the whole program).
  15107. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  15108. spill tuple-typed variables that are live during a call to
  15109. \code{collect}, the garbage collector. With the addition of functions
  15110. to our language, we need to revisit this issue. Functions that perform
  15111. allocation contain calls to the collector. Thus, we should not only
  15112. spill a tuple-typed variable when it is live during a call to
  15113. \code{collect}, but we should spill the variable if it is live during
  15114. a call to any user-defined function. Thus, in the
  15115. \code{build\_interference} pass, we recommend adding interference
  15116. edges between call-live tuple-typed variables and the callee-saved
  15117. registers (in addition to creating edges between
  15118. call-live variables and the caller-saved registers).
  15119. \subsection{Allocate Registers}
  15120. The primary change to the \code{allocate\_registers} pass is adding an
  15121. auxiliary function for handling definitions (the \Def{} nonterminal
  15122. shown in figure~\ref{fig:x86-3}) with one case for function
  15123. definitions. The logic is the same as described in
  15124. chapter~\ref{ch:register-allocation-Lvar} except that now register
  15125. allocation is performed many times, once for each function definition,
  15126. instead of just once for the whole program.
  15127. \section{Patch Instructions}
  15128. In \code{patch\_instructions}, you should deal with the x86
  15129. idiosyncrasy that the destination argument of \code{leaq} must be a
  15130. register. Additionally, you should ensure that the argument of
  15131. \code{TailJmp} is \itm{rax}, our reserved register---because we
  15132. trample many other registers before the tail call, as explained in the
  15133. next section.
  15134. \section{Generate Prelude and Conclusion}
  15135. Now that register allocation is complete, we can translate the
  15136. \code{TailJmp} into a sequence of instructions. A naive translation of
  15137. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  15138. before the jump we need to pop the current frame to achieve efficient
  15139. tail calls. This sequence of instructions is the same as the code for
  15140. the conclusion of a function, except that the \code{retq} is replaced with
  15141. \code{jmp *$\itm{arg}$}.
  15142. Regarding function definitions, we generate a prelude and conclusion
  15143. for each one. This code is similar to the prelude and conclusion
  15144. generated for the \code{main} function presented in
  15145. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  15146. carry out the following steps:
  15147. % TODO: .align the functions!
  15148. \begin{enumerate}
  15149. %% \item Start with \code{.global} and \code{.align} directives followed
  15150. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  15151. %% example.)
  15152. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  15153. pointer.
  15154. \item Push to the stack all the callee-saved registers that were
  15155. used for register allocation.
  15156. \item Move the stack pointer \code{rsp} down to make room for the
  15157. regular spills (aligned to 16 bytes).
  15158. \item Move the root stack pointer \code{r15} up by the size of the
  15159. root-stack frame for this function, which depends on the number of
  15160. spilled tuple-typed variables. \label{root-stack-init}
  15161. \item Initialize to zero all new entries in the root-stack frame.
  15162. \item Jump to the start block.
  15163. \end{enumerate}
  15164. The prelude of the \code{main} function has an additional task: call
  15165. the \code{initialize} function to set up the garbage collector, and
  15166. then move the value of the global \code{rootstack\_begin} in
  15167. \code{r15}. This initialization should happen before step
  15168. \ref{root-stack-init}, which depends on \code{r15}.
  15169. The conclusion of every function should do the following:
  15170. \begin{enumerate}
  15171. \item Move the stack pointer back up past the regular spills.
  15172. \item Restore the callee-saved registers by popping them from the
  15173. stack.
  15174. \item Move the root stack pointer back down by the size of the
  15175. root-stack frame for this function.
  15176. \item Restore \code{rbp} by popping it from the stack.
  15177. \item Return to the caller with the \code{retq} instruction.
  15178. \end{enumerate}
  15179. The output of this pass is \LangXIndCallFlat{}, which differs from
  15180. \LangXIndCall{} in that there is no longer an AST node for function
  15181. definitions. Instead, a program is just
  15182. \racket{an association list}\python{a dictionary}
  15183. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15184. {\if\edition\racketEd
  15185. \[
  15186. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15187. \]
  15188. \fi}
  15189. {\if\edition\pythonEd
  15190. \[
  15191. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15192. \]
  15193. \fi}
  15194. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15195. compiling \LangFun{} to x86.
  15196. \begin{exercise}\normalfont\normalsize
  15197. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15198. Create eight new programs that use functions including examples that
  15199. pass functions and return functions from other functions, recursive
  15200. functions, functions that create tuples, and functions that make tail
  15201. calls. Test your compiler on these new programs and all your
  15202. previously created test programs.
  15203. \end{exercise}
  15204. \begin{figure}[tbp]
  15205. \begin{tcolorbox}[colback=white]
  15206. {\if\edition\racketEd
  15207. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15208. \node (Lfun) at (0,2) {\large \LangFun{}};
  15209. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15210. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15211. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15212. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15213. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15214. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15215. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15216. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15217. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15218. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15219. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15220. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15221. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15222. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15223. \path[->,bend left=15] (Lfun) edge [above] node
  15224. {\ttfamily\footnotesize shrink} (Lfun-1);
  15225. \path[->,bend left=15] (Lfun-1) edge [above] node
  15226. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15227. \path[->,bend left=15] (Lfun-2) edge [above] node
  15228. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15229. \path[->,bend left=15] (F1-1) edge [left] node
  15230. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15231. \path[->,bend left=15] (F1-2) edge [below] node
  15232. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15233. \path[->,bend left=15] (F1-3) edge [below] node
  15234. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15235. \path[->,bend right=15] (F1-4) edge [above] node
  15236. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15237. \path[->,bend right=15] (F1-5) edge [right] node
  15238. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15239. \path[->,bend right=15] (C3-2) edge [right] node
  15240. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15241. \path[->,bend left=15] (x86-2) edge [right] node
  15242. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15243. \path[->,bend right=15] (x86-2-1) edge [below] node
  15244. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15245. \path[->,bend right=15] (x86-2-2) edge [right] node
  15246. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15247. \path[->,bend left=15] (x86-3) edge [above] node
  15248. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15249. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15250. \end{tikzpicture}
  15251. \fi}
  15252. {\if\edition\pythonEd\pythonColor
  15253. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15254. \node (Lfun) at (0,2) {\large \LangFun{}};
  15255. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15256. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15257. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15258. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15259. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15260. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15261. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15262. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15263. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15264. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15265. \path[->,bend left=15] (Lfun) edge [above] node
  15266. {\ttfamily\footnotesize shrink} (Lfun-2);
  15267. \path[->,bend left=15] (Lfun-2) edge [above] node
  15268. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15269. \path[->,bend left=15] (F1-1) edge [above] node
  15270. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15271. \path[->,bend left=15] (F1-2) edge [right] node
  15272. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15273. \path[->,bend right=15] (F1-4) edge [above] node
  15274. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15275. \path[->,bend right=15] (F1-5) edge [right] node
  15276. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15277. \path[->,bend left=15] (C3-2) edge [right] node
  15278. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15279. \path[->,bend right=15] (x86-2) edge [below] node
  15280. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15281. \path[->,bend left=15] (x86-3) edge [above] node
  15282. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15283. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15284. \end{tikzpicture}
  15285. \fi}
  15286. \end{tcolorbox}
  15287. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15288. \label{fig:Lfun-passes}
  15289. \end{figure}
  15290. \section{An Example Translation}
  15291. \label{sec:functions-example}
  15292. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15293. function in \LangFun{} to x86. The figure includes the results of
  15294. \code{explicate\_control} and \code{select\_instructions}.
  15295. \begin{figure}[hbtp]
  15296. \begin{tcolorbox}[colback=white]
  15297. \begin{tabular}{ll}
  15298. \begin{minipage}{0.4\textwidth}
  15299. % s3_2.rkt
  15300. {\if\edition\racketEd
  15301. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15302. (define (add [x : Integer]
  15303. [y : Integer])
  15304. : Integer
  15305. (+ x y))
  15306. (add 40 2)
  15307. \end{lstlisting}
  15308. \fi}
  15309. {\if\edition\pythonEd\pythonColor
  15310. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15311. def add(x:int, y:int) -> int:
  15312. return x + y
  15313. print(add(40, 2))
  15314. \end{lstlisting}
  15315. \fi}
  15316. $\Downarrow$
  15317. {\if\edition\racketEd
  15318. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15319. (define (add86 [x87 : Integer]
  15320. [y88 : Integer])
  15321. : Integer
  15322. add86start:
  15323. return (+ x87 y88);
  15324. )
  15325. (define (main) : Integer ()
  15326. mainstart:
  15327. tmp89 = (fun-ref add86 2);
  15328. (tail-call tmp89 40 2)
  15329. )
  15330. \end{lstlisting}
  15331. \fi}
  15332. {\if\edition\pythonEd\pythonColor
  15333. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15334. def add(x:int, y:int) -> int:
  15335. addstart:
  15336. return x + y
  15337. def main() -> int:
  15338. mainstart:
  15339. fun.0 = add
  15340. tmp.1 = fun.0(40, 2)
  15341. print(tmp.1)
  15342. return 0
  15343. \end{lstlisting}
  15344. \fi}
  15345. \end{minipage}
  15346. &
  15347. $\Rightarrow$
  15348. \begin{minipage}{0.5\textwidth}
  15349. {\if\edition\racketEd
  15350. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15351. (define (add86) : Integer
  15352. add86start:
  15353. movq %rdi, x87
  15354. movq %rsi, y88
  15355. movq x87, %rax
  15356. addq y88, %rax
  15357. jmp inc1389conclusion
  15358. )
  15359. (define (main) : Integer
  15360. mainstart:
  15361. leaq (fun-ref add86 2), tmp89
  15362. movq $40, %rdi
  15363. movq $2, %rsi
  15364. tail-jmp tmp89
  15365. )
  15366. \end{lstlisting}
  15367. \fi}
  15368. {\if\edition\pythonEd\pythonColor
  15369. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15370. def add() -> int:
  15371. addstart:
  15372. movq %rdi, x
  15373. movq %rsi, y
  15374. movq x, %rax
  15375. addq y, %rax
  15376. jmp addconclusion
  15377. def main() -> int:
  15378. mainstart:
  15379. leaq add, fun.0
  15380. movq $40, %rdi
  15381. movq $2, %rsi
  15382. callq *fun.0
  15383. movq %rax, tmp.1
  15384. movq tmp.1, %rdi
  15385. callq print_int
  15386. movq $0, %rax
  15387. jmp mainconclusion
  15388. \end{lstlisting}
  15389. \fi}
  15390. $\Downarrow$
  15391. \end{minipage}
  15392. \end{tabular}
  15393. \begin{tabular}{ll}
  15394. \begin{minipage}{0.3\textwidth}
  15395. {\if\edition\racketEd
  15396. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15397. .globl add86
  15398. .align 8
  15399. add86:
  15400. pushq %rbp
  15401. movq %rsp, %rbp
  15402. jmp add86start
  15403. add86start:
  15404. movq %rdi, %rax
  15405. addq %rsi, %rax
  15406. jmp add86conclusion
  15407. add86conclusion:
  15408. popq %rbp
  15409. retq
  15410. \end{lstlisting}
  15411. \fi}
  15412. {\if\edition\pythonEd\pythonColor
  15413. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15414. .align 8
  15415. add:
  15416. pushq %rbp
  15417. movq %rsp, %rbp
  15418. subq $0, %rsp
  15419. jmp addstart
  15420. addstart:
  15421. movq %rdi, %rdx
  15422. movq %rsi, %rcx
  15423. movq %rdx, %rax
  15424. addq %rcx, %rax
  15425. jmp addconclusion
  15426. addconclusion:
  15427. subq $0, %r15
  15428. addq $0, %rsp
  15429. popq %rbp
  15430. retq
  15431. \end{lstlisting}
  15432. \fi}
  15433. \end{minipage}
  15434. &
  15435. \begin{minipage}{0.5\textwidth}
  15436. {\if\edition\racketEd
  15437. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15438. .globl main
  15439. .align 8
  15440. main:
  15441. pushq %rbp
  15442. movq %rsp, %rbp
  15443. movq $16384, %rdi
  15444. movq $16384, %rsi
  15445. callq initialize
  15446. movq rootstack_begin(%rip), %r15
  15447. jmp mainstart
  15448. mainstart:
  15449. leaq add86(%rip), %rcx
  15450. movq $40, %rdi
  15451. movq $2, %rsi
  15452. movq %rcx, %rax
  15453. popq %rbp
  15454. jmp *%rax
  15455. mainconclusion:
  15456. popq %rbp
  15457. retq
  15458. \end{lstlisting}
  15459. \fi}
  15460. {\if\edition\pythonEd\pythonColor
  15461. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15462. .globl main
  15463. .align 8
  15464. main:
  15465. pushq %rbp
  15466. movq %rsp, %rbp
  15467. subq $0, %rsp
  15468. movq $65536, %rdi
  15469. movq $65536, %rsi
  15470. callq initialize
  15471. movq rootstack_begin(%rip), %r15
  15472. jmp mainstart
  15473. mainstart:
  15474. leaq add(%rip), %rcx
  15475. movq $40, %rdi
  15476. movq $2, %rsi
  15477. callq *%rcx
  15478. movq %rax, %rcx
  15479. movq %rcx, %rdi
  15480. callq print_int
  15481. movq $0, %rax
  15482. jmp mainconclusion
  15483. mainconclusion:
  15484. subq $0, %r15
  15485. addq $0, %rsp
  15486. popq %rbp
  15487. retq
  15488. \end{lstlisting}
  15489. \fi}
  15490. \end{minipage}
  15491. \end{tabular}
  15492. \end{tcolorbox}
  15493. \caption{Example compilation of a simple function to x86.}
  15494. \label{fig:add-fun}
  15495. \end{figure}
  15496. % Challenge idea: inlining! (simple version)
  15497. % Further Reading
  15498. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15499. \chapter{Lexically Scoped Functions}
  15500. \label{ch:Llambda}
  15501. \setcounter{footnote}{0}
  15502. This chapter studies lexically scoped functions. Lexical
  15503. scoping\index{subject}{lexical scoping} means that a function's body
  15504. may refer to variables whose binding site is outside of the function,
  15505. in an enclosing scope.
  15506. %
  15507. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15508. in \LangLam{}, which extends \LangFun{} with the
  15509. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15510. functions. The body of the \key{lambda} refers to three variables:
  15511. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15512. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15513. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15514. function \code{f}}, and \code{x} is a parameter of function
  15515. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15516. result value. The main expression of the program includes two calls to
  15517. \code{f} with different arguments for \code{x}: first \code{5} and
  15518. then \code{3}. The functions returned from \code{f} are bound to
  15519. variables \code{g} and \code{h}. Even though these two functions were
  15520. created by the same \code{lambda}, they are really different functions
  15521. because they use different values for \code{x}. Applying \code{g} to
  15522. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15523. produces \code{22}, so the result of the program is \code{42}.
  15524. \begin{figure}[btp]
  15525. \begin{tcolorbox}[colback=white]
  15526. {\if\edition\racketEd
  15527. % lambda_test_21.rkt
  15528. \begin{lstlisting}
  15529. (define (f [x : Integer]) : (Integer -> Integer)
  15530. (let ([y 4])
  15531. (lambda: ([z : Integer]) : Integer
  15532. (+ x (+ y z)))))
  15533. (let ([g (f 5)])
  15534. (let ([h (f 3)])
  15535. (+ (g 11) (h 15))))
  15536. \end{lstlisting}
  15537. \fi}
  15538. {\if\edition\pythonEd\pythonColor
  15539. \begin{lstlisting}
  15540. def f(x : int) -> Callable[[int], int]:
  15541. y = 4
  15542. return lambda z: x + y + z
  15543. g = f(5)
  15544. h = f(3)
  15545. print(g(11) + h(15))
  15546. \end{lstlisting}
  15547. \fi}
  15548. \end{tcolorbox}
  15549. \caption{Example of a lexically scoped function.}
  15550. \label{fig:lexical-scoping}
  15551. \end{figure}
  15552. The approach that we take for implementing lexically scoped functions
  15553. is to compile them into top-level function definitions, translating
  15554. from \LangLam{} into \LangFun{}. However, the compiler must give
  15555. special treatment to variable occurrences such as \code{x} and
  15556. \code{y} in the body of the \code{lambda} shown in
  15557. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15558. may not refer to variables defined outside of it. To identify such
  15559. variable occurrences, we review the standard notion of free variable.
  15560. \begin{definition}\normalfont
  15561. A variable is \emph{free in expression} $e$ if the variable occurs
  15562. inside $e$ but does not have an enclosing definition that is also in
  15563. $e$.\index{subject}{free variable}
  15564. \end{definition}
  15565. For example, in the expression
  15566. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15567. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15568. only \code{x} and \code{y} are free in the following expression,
  15569. because \code{z} is defined by the \code{lambda}
  15570. {\if\edition\racketEd
  15571. \begin{lstlisting}
  15572. (lambda: ([z : Integer]) : Integer
  15573. (+ x (+ y z)))
  15574. \end{lstlisting}
  15575. \fi}
  15576. {\if\edition\pythonEd\pythonColor
  15577. \begin{lstlisting}
  15578. lambda z: x + y + z
  15579. \end{lstlisting}
  15580. \fi}
  15581. %
  15582. \noindent Thus the free variables of a \code{lambda} are the ones that
  15583. need special treatment. We need to transport at runtime the values
  15584. of those variables from the point where the \code{lambda} was created
  15585. to the point where the \code{lambda} is applied. An efficient solution
  15586. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15587. values of the free variables together with a function pointer into a
  15588. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15589. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15590. closure}
  15591. %
  15592. By design, we have all the ingredients to make closures:
  15593. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15594. function pointers. The function pointer resides at index $0$, and the
  15595. values for the free variables fill in the rest of the tuple.
  15596. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15597. to see how closures work. It is a three-step dance. The program calls
  15598. function \code{f}, which creates a closure for the \code{lambda}. The
  15599. closure is a tuple whose first element is a pointer to the top-level
  15600. function that we will generate for the \code{lambda}; the second
  15601. element is the value of \code{x}, which is \code{5}; and the third
  15602. element is \code{4}, the value of \code{y}. The closure does not
  15603. contain an element for \code{z} because \code{z} is not a free
  15604. variable of the \code{lambda}. Creating the closure is step 1 of the
  15605. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15606. shown in figure~\ref{fig:closures}.
  15607. %
  15608. The second call to \code{f} creates another closure, this time with
  15609. \code{3} in the second slot (for \code{x}). This closure is also
  15610. returned from \code{f} but bound to \code{h}, which is also shown in
  15611. figure~\ref{fig:closures}.
  15612. \begin{figure}[tbp]
  15613. \centering
  15614. \begin{minipage}{0.65\textwidth}
  15615. \begin{tcolorbox}[colback=white]
  15616. \includegraphics[width=\textwidth]{figs/closures}
  15617. \end{tcolorbox}
  15618. \end{minipage}
  15619. \caption{Flat closure representations for the two functions
  15620. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15621. \label{fig:closures}
  15622. \end{figure}
  15623. Continuing with the example, consider the application of \code{g} to
  15624. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15625. closure, we obtain the function pointer from the first element of the
  15626. closure and call it, passing in the closure itself and then the
  15627. regular arguments, in this case \code{11}. This technique for applying
  15628. a closure is step 2 of the dance.
  15629. %
  15630. But doesn't this \code{lambda} take only one argument, for parameter
  15631. \code{z}? The third and final step of the dance is generating a
  15632. top-level function for a \code{lambda}. We add an additional
  15633. parameter for the closure and insert an initialization at the beginning
  15634. of the function for each free variable, to bind those variables to the
  15635. appropriate elements from the closure parameter.
  15636. %
  15637. This three-step dance is known as \emph{closure
  15638. conversion}\index{subject}{closure conversion}. We discuss the
  15639. details of closure conversion in section~\ref{sec:closure-conversion}
  15640. and show the code generated from the example in
  15641. section~\ref{sec:example-lambda}. First, we define the syntax and
  15642. semantics of \LangLam{} in section~\ref{sec:r5}.
  15643. \section{The \LangLam{} Language}
  15644. \label{sec:r5}
  15645. The definitions of the concrete syntax and abstract syntax for
  15646. \LangLam{}, a language with anonymous functions and lexical scoping,
  15647. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15648. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15649. for \LangFun{}, which already has syntax for function application.
  15650. %
  15651. \python{The syntax also includes an assignment statement that includes
  15652. a type annotation for the variable on the left-hand side, which
  15653. facilitates the type checking of \code{lambda} expressions that we
  15654. discuss later in this section.}
  15655. %
  15656. \racket{The \code{procedure-arity} operation returns the number of parameters
  15657. of a given function, an operation that we need for the translation
  15658. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15659. %
  15660. \python{The \code{arity} operation returns the number of parameters of
  15661. a given function, an operation that we need for the translation
  15662. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15663. The \code{arity} operation is not in Python, but the same functionality
  15664. is available in a more complex form. We include \code{arity} in the
  15665. \LangLam{} source language to enable testing.}
  15666. \newcommand{\LlambdaGrammarRacket}{
  15667. \begin{array}{lcl}
  15668. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15669. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15670. \end{array}
  15671. }
  15672. \newcommand{\LlambdaASTRacket}{
  15673. \begin{array}{lcl}
  15674. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15675. \itm{op} &::=& \code{procedure-arity}
  15676. \end{array}
  15677. }
  15678. \newcommand{\LlambdaGrammarPython}{
  15679. \begin{array}{lcl}
  15680. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15681. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15682. \end{array}
  15683. }
  15684. \newcommand{\LlambdaASTPython}{
  15685. \begin{array}{lcl}
  15686. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15687. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15688. \end{array}
  15689. }
  15690. % include AnnAssign in ASTPython
  15691. \begin{figure}[tp]
  15692. \centering
  15693. \begin{tcolorbox}[colback=white]
  15694. \small
  15695. {\if\edition\racketEd
  15696. \[
  15697. \begin{array}{l}
  15698. \gray{\LintGrammarRacket{}} \\ \hline
  15699. \gray{\LvarGrammarRacket{}} \\ \hline
  15700. \gray{\LifGrammarRacket{}} \\ \hline
  15701. \gray{\LwhileGrammarRacket} \\ \hline
  15702. \gray{\LtupGrammarRacket} \\ \hline
  15703. \gray{\LfunGrammarRacket} \\ \hline
  15704. \LlambdaGrammarRacket \\
  15705. \begin{array}{lcl}
  15706. \LangLamM{} &::=& \Def\ldots \; \Exp
  15707. \end{array}
  15708. \end{array}
  15709. \]
  15710. \fi}
  15711. {\if\edition\pythonEd\pythonColor
  15712. \[
  15713. \begin{array}{l}
  15714. \gray{\LintGrammarPython{}} \\ \hline
  15715. \gray{\LvarGrammarPython{}} \\ \hline
  15716. \gray{\LifGrammarPython{}} \\ \hline
  15717. \gray{\LwhileGrammarPython} \\ \hline
  15718. \gray{\LtupGrammarPython} \\ \hline
  15719. \gray{\LfunGrammarPython} \\ \hline
  15720. \LlambdaGrammarPython \\
  15721. \begin{array}{lcl}
  15722. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15723. \end{array}
  15724. \end{array}
  15725. \]
  15726. \fi}
  15727. \end{tcolorbox}
  15728. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15729. with \key{lambda}.}
  15730. \label{fig:Llam-concrete-syntax}
  15731. \index{subject}{Llambda@\LangLam{} concrete syntax}
  15732. \end{figure}
  15733. \begin{figure}[tp]
  15734. \centering
  15735. \begin{tcolorbox}[colback=white]
  15736. \small
  15737. {\if\edition\racketEd
  15738. \[\arraycolsep=3pt
  15739. \begin{array}{l}
  15740. \gray{\LintOpAST} \\ \hline
  15741. \gray{\LvarASTRacket{}} \\ \hline
  15742. \gray{\LifASTRacket{}} \\ \hline
  15743. \gray{\LwhileASTRacket{}} \\ \hline
  15744. \gray{\LtupASTRacket{}} \\ \hline
  15745. \gray{\LfunASTRacket} \\ \hline
  15746. \LlambdaASTRacket \\
  15747. \begin{array}{lcl}
  15748. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15749. \end{array}
  15750. \end{array}
  15751. \]
  15752. \fi}
  15753. {\if\edition\pythonEd\pythonColor
  15754. \[
  15755. \begin{array}{l}
  15756. \gray{\LintASTPython} \\ \hline
  15757. \gray{\LvarASTPython{}} \\ \hline
  15758. \gray{\LifASTPython{}} \\ \hline
  15759. \gray{\LwhileASTPython{}} \\ \hline
  15760. \gray{\LtupASTPython{}} \\ \hline
  15761. \gray{\LfunASTPython} \\ \hline
  15762. \LlambdaASTPython \\
  15763. \begin{array}{lcl}
  15764. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15765. \end{array}
  15766. \end{array}
  15767. \]
  15768. \fi}
  15769. \end{tcolorbox}
  15770. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15771. \label{fig:Llam-syntax}
  15772. \index{subject}{Llambda@\LangLam{} abstract syntax}
  15773. \end{figure}
  15774. Figure~\ref{fig:interp-Llambda} shows the definitional
  15775. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15776. \key{Lambda} saves the current environment inside the returned
  15777. function value. Recall that during function application, the
  15778. environment stored in the function value, extended with the mapping of
  15779. parameters to argument values, is used to interpret the body of the
  15780. function.
  15781. \begin{figure}[tbp]
  15782. \begin{tcolorbox}[colback=white]
  15783. {\if\edition\racketEd
  15784. \begin{lstlisting}
  15785. (define interp-Llambda-class
  15786. (class interp-Lfun-class
  15787. (super-new)
  15788. (define/override (interp-op op)
  15789. (match op
  15790. ['procedure-arity
  15791. (lambda (v)
  15792. (match v
  15793. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15794. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15795. [else (super interp-op op)]))
  15796. (define/override ((interp-exp env) e)
  15797. (define recur (interp-exp env))
  15798. (match e
  15799. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15800. `(function ,xs ,body ,env)]
  15801. [else ((super interp-exp env) e)]))
  15802. ))
  15803. (define (interp-Llambda p)
  15804. (send (new interp-Llambda-class) interp-program p))
  15805. \end{lstlisting}
  15806. \fi}
  15807. {\if\edition\pythonEd\pythonColor
  15808. \begin{lstlisting}
  15809. class InterpLlambda(InterpLfun):
  15810. def arity(self, v):
  15811. match v:
  15812. case Function(name, params, body, env):
  15813. return len(params)
  15814. case _:
  15815. raise Exception('Llambda arity unexpected ' + repr(v))
  15816. def interp_exp(self, e, env):
  15817. match e:
  15818. case Call(Name('arity'), [fun]):
  15819. f = self.interp_exp(fun, env)
  15820. return self.arity(f)
  15821. case Lambda(params, body):
  15822. return Function('lambda', params, [Return(body)], env)
  15823. case _:
  15824. return super().interp_exp(e, env)
  15825. def interp_stmt(self, s, env, cont):
  15826. match s:
  15827. case AnnAssign(lhs, typ, value, simple):
  15828. env[lhs.id] = self.interp_exp(value, env)
  15829. return self.interp_stmts(cont, env)
  15830. case Pass():
  15831. return self.interp_stmts(cont, env)
  15832. case _:
  15833. return super().interp_stmt(s, env, cont)
  15834. \end{lstlisting}
  15835. \fi}
  15836. \end{tcolorbox}
  15837. \caption{Interpreter for \LangLam{}.}
  15838. \label{fig:interp-Llambda}
  15839. \end{figure}
  15840. {\if\edition\racketEd
  15841. %
  15842. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15843. \key{lambda} form. The body of the \key{lambda} is checked in an
  15844. environment that includes the current environment (because it is
  15845. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15846. require the body's type to match the declared return type.
  15847. %
  15848. \fi}
  15849. {\if\edition\pythonEd\pythonColor
  15850. %
  15851. Figures~\ref{fig:type-check-Llambda} and
  15852. \ref{fig:type-check-Llambda-part2} define the type checker for
  15853. \LangLam{}, which is more complex than one might expect. The reason
  15854. for the added complexity is that the syntax of \key{lambda} does not
  15855. include type annotations for the parameters or return type. Instead
  15856. they must be inferred. There are many approaches to type inference
  15857. from which to choose, of varying degrees of complexity. We choose one
  15858. of the simpler approaches, bidirectional type
  15859. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15860. book is compilation, not type inference.
  15861. The main idea of bidirectional type inference is to add an auxiliary
  15862. function, here named \code{check\_exp}, that takes an expected type
  15863. and checks whether the given expression is of that type. Thus, in
  15864. \code{check\_exp}, type information flows in a top-down manner with
  15865. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15866. function, where type information flows in a primarily bottom-up
  15867. manner.
  15868. %
  15869. The idea then is to use \code{check\_exp} in all the places where we
  15870. already know what the type of an expression should be, such as in the
  15871. \code{return} statement of a top-level function definition or on the
  15872. right-hand side of an annotated assignment statement.
  15873. With regard to \code{lambda}, it is straightforward to check a
  15874. \code{lambda} inside \code{check\_exp} because the expected type
  15875. provides the parameter types and the return type. On the other hand,
  15876. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15877. that we do not allow \code{lambda} in contexts in which we don't already
  15878. know its type. This restriction does not incur a loss of
  15879. expressiveness for \LangLam{} because it is straightforward to modify
  15880. a program to sidestep the restriction, for example, by using an
  15881. annotated assignment statement to assign the \code{lambda} to a
  15882. temporary variable.
  15883. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15884. checker records their type in a \code{has\_type} field. This type
  15885. information is used further on in this chapter.
  15886. %
  15887. \fi}
  15888. \begin{figure}[tbp]
  15889. \begin{tcolorbox}[colback=white]
  15890. {\if\edition\racketEd
  15891. \begin{lstlisting}
  15892. (define (type-check-Llambda env)
  15893. (lambda (e)
  15894. (match e
  15895. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15896. (define-values (new-body bodyT)
  15897. ((type-check-exp (append (map cons xs Ts) env)) body))
  15898. (define ty `(,@Ts -> ,rT))
  15899. (cond
  15900. [(equal? rT bodyT)
  15901. (values (HasType (Lambda params rT new-body) ty) ty)]
  15902. [else
  15903. (error "mismatch in return type" bodyT rT)])]
  15904. ...
  15905. )))
  15906. \end{lstlisting}
  15907. \fi}
  15908. {\if\edition\pythonEd\pythonColor
  15909. \begin{lstlisting}
  15910. class TypeCheckLlambda(TypeCheckLfun):
  15911. def type_check_exp(self, e, env):
  15912. match e:
  15913. case Name(id):
  15914. e.has_type = env[id]
  15915. return env[id]
  15916. case Lambda(params, body):
  15917. raise Exception('cannot synthesize a type for a lambda')
  15918. case Call(Name('arity'), [func]):
  15919. func_t = self.type_check_exp(func, env)
  15920. match func_t:
  15921. case FunctionType(params_t, return_t):
  15922. return IntType()
  15923. case _:
  15924. raise Exception('in arity, unexpected ' + repr(func_t))
  15925. case _:
  15926. return super().type_check_exp(e, env)
  15927. def check_exp(self, e, ty, env):
  15928. match e:
  15929. case Lambda(params, body):
  15930. e.has_type = ty
  15931. match ty:
  15932. case FunctionType(params_t, return_t):
  15933. new_env = env.copy().update(zip(params, params_t))
  15934. self.check_exp(body, return_t, new_env)
  15935. case _:
  15936. raise Exception('lambda does not have type ' + str(ty))
  15937. case Call(func, args):
  15938. func_t = self.type_check_exp(func, env)
  15939. match func_t:
  15940. case FunctionType(params_t, return_t):
  15941. for (arg, param_t) in zip(args, params_t):
  15942. self.check_exp(arg, param_t, env)
  15943. self.check_type_equal(return_t, ty, e)
  15944. case _:
  15945. raise Exception('type_check_exp: in call, unexpected ' + \
  15946. repr(func_t))
  15947. case _:
  15948. t = self.type_check_exp(e, env)
  15949. self.check_type_equal(t, ty, e)
  15950. \end{lstlisting}
  15951. \fi}
  15952. \end{tcolorbox}
  15953. \caption{Type checking \LangLam{}\python{, part 1}.}
  15954. \label{fig:type-check-Llambda}
  15955. \end{figure}
  15956. {\if\edition\pythonEd\pythonColor
  15957. \begin{figure}[tbp]
  15958. \begin{tcolorbox}[colback=white]
  15959. \begin{lstlisting}
  15960. def check_stmts(self, ss, return_ty, env):
  15961. if len(ss) == 0:
  15962. return
  15963. match ss[0]:
  15964. case FunctionDef(name, params, body, dl, returns, comment):
  15965. new_env = env.copy().update(params)
  15966. rt = self.check_stmts(body, returns, new_env)
  15967. self.check_stmts(ss[1:], return_ty, env)
  15968. case Return(value):
  15969. self.check_exp(value, return_ty, env)
  15970. case Assign([Name(id)], value):
  15971. if id in env:
  15972. self.check_exp(value, env[id], env)
  15973. else:
  15974. env[id] = self.type_check_exp(value, env)
  15975. self.check_stmts(ss[1:], return_ty, env)
  15976. case Assign([Subscript(tup, Constant(index), Store())], value):
  15977. tup_t = self.type_check_exp(tup, env)
  15978. match tup_t:
  15979. case TupleType(ts):
  15980. self.check_exp(value, ts[index], env)
  15981. case _:
  15982. raise Exception('expected a tuple, not ' + repr(tup_t))
  15983. self.check_stmts(ss[1:], return_ty, env)
  15984. case AnnAssign(Name(id), ty_annot, value, simple):
  15985. ss[0].annotation = ty_annot
  15986. if id in env:
  15987. self.check_type_equal(env[id], ty_annot)
  15988. else:
  15989. env[id] = ty_annot
  15990. self.check_exp(value, ty_annot, env)
  15991. self.check_stmts(ss[1:], return_ty, env)
  15992. case _:
  15993. self.type_check_stmts(ss, env)
  15994. def type_check(self, p):
  15995. match p:
  15996. case Module(body):
  15997. env = {}
  15998. for s in body:
  15999. match s:
  16000. case FunctionDef(name, params, bod, dl, returns, comment):
  16001. params_t = [t for (x,t) in params]
  16002. env[name] = FunctionType(params_t, returns)
  16003. self.check_stmts(body, int, env)
  16004. \end{lstlisting}
  16005. \end{tcolorbox}
  16006. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  16007. \label{fig:type-check-Llambda-part2}
  16008. \end{figure}
  16009. \fi}
  16010. \clearpage
  16011. \section{Assignment and Lexically Scoped Functions}
  16012. \label{sec:assignment-scoping}
  16013. The combination of lexically scoped functions and assignment to
  16014. variables raises a challenge with the flat-closure approach to
  16015. implementing lexically scoped functions. Consider the following
  16016. example in which function \code{f} has a free variable \code{x} that
  16017. is changed after \code{f} is created but before the call to \code{f}.
  16018. % loop_test_11.rkt
  16019. {\if\edition\racketEd
  16020. \begin{lstlisting}
  16021. (let ([x 0])
  16022. (let ([y 0])
  16023. (let ([z 20])
  16024. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16025. (begin
  16026. (set! x 10)
  16027. (set! y 12)
  16028. (f y))))))
  16029. \end{lstlisting}
  16030. \fi}
  16031. {\if\edition\pythonEd\pythonColor
  16032. % box_free_assign.py
  16033. \begin{lstlisting}
  16034. def g(z : int) -> int:
  16035. x = 0
  16036. y = 0
  16037. f : Callable[[int],int] = lambda a: a + x + z
  16038. x = 10
  16039. y = 12
  16040. return f(y)
  16041. print(g(20))
  16042. \end{lstlisting}
  16043. \fi} The correct output for this example is \code{42} because the call
  16044. to \code{f} is required to use the current value of \code{x} (which is
  16045. \code{10}). Unfortunately, the closure conversion pass
  16046. (section~\ref{sec:closure-conversion}) generates code for the
  16047. \code{lambda} that copies the old value of \code{x} into a
  16048. closure. Thus, if we naively applied closure conversion, the output of
  16049. this program would be \code{32}.
  16050. A first attempt at solving this problem would be to save a pointer to
  16051. \code{x} in the closure and change the occurrences of \code{x} inside
  16052. the lambda to dereference the pointer. Of course, this would require
  16053. assigning \code{x} to the stack and not to a register. However, the
  16054. problem goes a bit deeper.
  16055. Consider the following example that returns a function that refers to
  16056. a local variable of the enclosing function:
  16057. \begin{center}
  16058. \begin{minipage}{\textwidth}
  16059. {\if\edition\racketEd
  16060. \begin{lstlisting}
  16061. (define (f) : ( -> Integer)
  16062. (let ([x 0])
  16063. (let ([g (lambda: () : Integer x)])
  16064. (begin
  16065. (set! x 42)
  16066. g))))
  16067. ((f))
  16068. \end{lstlisting}
  16069. \fi}
  16070. {\if\edition\pythonEd\pythonColor
  16071. % counter.py
  16072. \begin{lstlisting}
  16073. def f():
  16074. x = 0
  16075. g = lambda: x
  16076. x = 42
  16077. return g
  16078. print(f()())
  16079. \end{lstlisting}
  16080. \fi}
  16081. \end{minipage}
  16082. \end{center}
  16083. In this example, the lifetime of \code{x} extends beyond the lifetime
  16084. of the call to \code{f}. Thus, if we were to store \code{x} on the
  16085. stack frame for the call to \code{f}, it would be gone by the time we
  16086. called \code{g}, leaving us with dangling pointers for
  16087. \code{x}. This example demonstrates that when a variable occurs free
  16088. inside a function, its lifetime becomes indefinite. Thus, the value of
  16089. the variable needs to live on the heap. The verb
  16090. \emph{box}\index{subject}{box} is often used for allocating a single
  16091. value on the heap, producing a pointer, and
  16092. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  16093. %
  16094. We introduce a new pass named \code{convert\_assignments} to address
  16095. this challenge.
  16096. %
  16097. \python{But before diving into that, we have one more
  16098. problem to discuss.}
  16099. {\if\edition\pythonEd\pythonColor
  16100. \section{Uniquify Variables}
  16101. \label{sec:uniquify-lambda}
  16102. With the addition of \code{lambda} we have a complication to deal
  16103. with: name shadowing. Consider the following program with a function
  16104. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  16105. \code{lambda} expressions. The first \code{lambda} has a parameter
  16106. that is also named \code{x}.
  16107. \begin{lstlisting}
  16108. def f(x:int, y:int) -> Callable[[int], int]:
  16109. g : Callable[[int],int] = (lambda x: x + y)
  16110. h : Callable[[int],int] = (lambda y: x + y)
  16111. x = input_int()
  16112. return g
  16113. print(f(0, 10)(32))
  16114. \end{lstlisting}
  16115. Many of our compiler passes rely on being able to connect variable
  16116. uses with their definitions using just the name of the
  16117. variable. However, in the example above, the name of the variable does
  16118. not uniquely determine its definition. To solve this problem we
  16119. recommend implementing a pass named \code{uniquify} that renames every
  16120. variable in the program to make sure that they are all unique.
  16121. The following shows the result of \code{uniquify} for the example
  16122. above. The \code{x} parameter of function \code{f} is renamed to
  16123. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  16124. renamed to \code{x\_4}.
  16125. \begin{lstlisting}
  16126. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  16127. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  16128. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  16129. x_0 = input_int()
  16130. return g_2
  16131. def main() -> int :
  16132. print(f(0, 10)(32))
  16133. return 0
  16134. \end{lstlisting}
  16135. \fi} % pythonEd
  16136. %% \section{Reveal Functions}
  16137. %% \label{sec:reveal-functions-r5}
  16138. %% \racket{To support the \code{procedure-arity} operator we need to
  16139. %% communicate the arity of a function to the point of closure
  16140. %% creation.}
  16141. %% %
  16142. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  16143. %% function at runtime. Thus, we need to communicate the arity of a
  16144. %% function to the point of closure creation.}
  16145. %% %
  16146. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  16147. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  16148. %% \[
  16149. %% \begin{array}{lcl}
  16150. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  16151. %% \end{array}
  16152. %% \]
  16153. \section{Assignment Conversion}
  16154. \label{sec:convert-assignments}
  16155. The purpose of the \code{convert\_assignments} pass is to address the
  16156. challenge regarding the interaction between variable assignments and
  16157. closure conversion. First we identify which variables need to be
  16158. boxed, and then we transform the program to box those variables. In
  16159. general, boxing introduces runtime overhead that we would like to
  16160. avoid, so we should box as few variables as possible. We recommend
  16161. boxing the variables in the intersection of the following two sets of
  16162. variables:
  16163. \begin{enumerate}
  16164. \item The variables that are free in a \code{lambda}.
  16165. \item The variables that appear on the left-hand side of an
  16166. assignment.
  16167. \end{enumerate}
  16168. The first condition is a must but the second condition is
  16169. conservative. It is possible to develop a more liberal condition using
  16170. static program analysis.
  16171. Consider again the first example from
  16172. section~\ref{sec:assignment-scoping}:
  16173. %
  16174. {\if\edition\racketEd
  16175. \begin{lstlisting}
  16176. (let ([x 0])
  16177. (let ([y 0])
  16178. (let ([z 20])
  16179. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16180. (begin
  16181. (set! x 10)
  16182. (set! y 12)
  16183. (f y))))))
  16184. \end{lstlisting}
  16185. \fi}
  16186. {\if\edition\pythonEd\pythonColor
  16187. \begin{lstlisting}
  16188. def g(z : int) -> int:
  16189. x = 0
  16190. y = 0
  16191. f : Callable[[int],int] = lambda a: a + x + z
  16192. x = 10
  16193. y = 12
  16194. return f(y)
  16195. print(g(20))
  16196. \end{lstlisting}
  16197. \fi}
  16198. %
  16199. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16200. side of assignments. The variables \code{x} and \code{z} occur free
  16201. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16202. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16203. three transformations: initialize \code{x} with a tuple whose element
  16204. is uninitialized, replace reads from \code{x} with tuple reads, and
  16205. replace each assignment to \code{x} with a tuple write. The output of
  16206. \code{convert\_assignments} for this example is as follows:
  16207. %
  16208. {\if\edition\racketEd
  16209. \begin{lstlisting}
  16210. (define (main) : Integer
  16211. (let ([x0 (vector 0)])
  16212. (let ([y1 0])
  16213. (let ([z2 20])
  16214. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16215. (+ a3 (+ (vector-ref x0 0) z2)))])
  16216. (begin
  16217. (vector-set! x0 0 10)
  16218. (set! y1 12)
  16219. (f4 y1)))))))
  16220. \end{lstlisting}
  16221. \fi}
  16222. %
  16223. {\if\edition\pythonEd\pythonColor
  16224. \begin{lstlisting}
  16225. def g(z : int)-> int:
  16226. x = (uninitialized(int),)
  16227. x[0] = 0
  16228. y = 0
  16229. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16230. x[0] = 10
  16231. y = 12
  16232. return f(y)
  16233. def main() -> int:
  16234. print(g(20))
  16235. return 0
  16236. \end{lstlisting}
  16237. \fi}
  16238. To compute the free variables of all the \code{lambda} expressions, we
  16239. recommend defining the following two auxiliary functions:
  16240. \begin{enumerate}
  16241. \item \code{free\_variables} computes the free variables of an expression, and
  16242. \item \code{free\_in\_lambda} collects all the variables that are
  16243. free in any of the \code{lambda} expressions, using
  16244. \code{free\_variables} in the case for each \code{lambda}.
  16245. \end{enumerate}
  16246. {\if\edition\racketEd
  16247. %
  16248. To compute the variables that are assigned to, we recommend updating
  16249. the \code{collect-set!} function that we introduced in
  16250. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16251. as \code{Lambda}.
  16252. %
  16253. \fi}
  16254. {\if\edition\pythonEd\pythonColor
  16255. %
  16256. To compute the variables that are assigned to, we recommend defining
  16257. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16258. the set of variables that occur in the left-hand side of an assignment
  16259. statement and otherwise returns the empty set.
  16260. %
  16261. \fi}
  16262. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16263. free in a \code{lambda} and that are assigned to in the enclosing
  16264. function definition.
  16265. Next we discuss the \code{convert\_assignments} pass. In the case for
  16266. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16267. $\VAR{x}$ to a tuple read.
  16268. %
  16269. {\if\edition\racketEd
  16270. \begin{lstlisting}
  16271. (Var |$x$|)
  16272. |$\Rightarrow$|
  16273. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16274. \end{lstlisting}
  16275. \fi}
  16276. %
  16277. {\if\edition\pythonEd\pythonColor
  16278. \begin{lstlisting}
  16279. Name(|$x$|)
  16280. |$\Rightarrow$|
  16281. Subscript(Name(|$x$|), Constant(0), Load())
  16282. \end{lstlisting}
  16283. \fi}
  16284. %
  16285. \noindent In the case for assignment, recursively process the
  16286. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16287. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16288. as follows:
  16289. %
  16290. {\if\edition\racketEd
  16291. \begin{lstlisting}
  16292. (SetBang |$x$| |$\itm{rhs}$|)
  16293. |$\Rightarrow$|
  16294. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16295. \end{lstlisting}
  16296. \fi}
  16297. {\if\edition\pythonEd\pythonColor
  16298. \begin{lstlisting}
  16299. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16300. |$\Rightarrow$|
  16301. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16302. \end{lstlisting}
  16303. \fi}
  16304. %
  16305. {\if\edition\racketEd
  16306. The case for \code{Lambda} is nontrivial, but it is similar to the
  16307. case for function definitions, which we discuss next.
  16308. \fi}
  16309. %
  16310. To translate a function definition, we first compute $\mathit{AF}$,
  16311. the intersection of the variables that are free in a \code{lambda} and
  16312. that are assigned to. We then apply assignment conversion to the body
  16313. of the function definition. Finally, we box the parameters of this
  16314. function definition that are in $\mathit{AF}$. For example,
  16315. the parameter \code{x} of the following function \code{g}
  16316. needs to be boxed:
  16317. {\if\edition\racketEd
  16318. \begin{lstlisting}
  16319. (define (g [x : Integer]) : Integer
  16320. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16321. (begin
  16322. (set! x 10)
  16323. (f 32))))
  16324. \end{lstlisting}
  16325. \fi}
  16326. %
  16327. {\if\edition\pythonEd\pythonColor
  16328. \begin{lstlisting}
  16329. def g(x : int) -> int:
  16330. f : Callable[[int],int] = lambda a: a + x
  16331. x = 10
  16332. return f(32)
  16333. \end{lstlisting}
  16334. \fi}
  16335. %
  16336. \noindent We box parameter \code{x} by creating a local variable named
  16337. \code{x} that is initialized to a tuple whose contents is the value of
  16338. the parameter, which is renamed to \code{x\_0}.
  16339. %
  16340. {\if\edition\racketEd
  16341. \begin{lstlisting}
  16342. (define (g [x_0 : Integer]) : Integer
  16343. (let ([x (vector x_0)])
  16344. (let ([f (lambda: ([a : Integer]) : Integer
  16345. (+ a (vector-ref x 0)))])
  16346. (begin
  16347. (vector-set! x 0 10)
  16348. (f 32)))))
  16349. \end{lstlisting}
  16350. \fi}
  16351. %
  16352. {\if\edition\pythonEd\pythonColor
  16353. \begin{lstlisting}
  16354. def g(x_0 : int)-> int:
  16355. x = (x_0,)
  16356. f : Callable[[int], int] = (lambda a: a + x[0])
  16357. x[0] = 10
  16358. return f(32)
  16359. \end{lstlisting}
  16360. \fi}
  16361. \section{Closure Conversion}
  16362. \label{sec:closure-conversion}
  16363. \index{subject}{closure conversion}
  16364. The compiling of lexically scoped functions into top-level function
  16365. definitions and flat closures is accomplished in the pass
  16366. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16367. and before \code{limit\_functions}.
  16368. As usual, we implement the pass as a recursive function over the
  16369. AST. The interesting cases are for \key{lambda} and function
  16370. application. We transform a \key{lambda} expression into an expression
  16371. that creates a closure, that is, a tuple for which the first element
  16372. is a function pointer and the rest of the elements are the values of
  16373. the free variables of the \key{lambda}.
  16374. %
  16375. However, we use the \code{Closure} AST node instead of using a tuple
  16376. so that we can record the arity.
  16377. %
  16378. In the generated code that follows, \itm{fvs} is the list of free
  16379. variables of the lambda and \itm{name} is a unique symbol generated to
  16380. identify the lambda.
  16381. %
  16382. \racket{The \itm{arity} is the number of parameters (the length of
  16383. \itm{ps}).}
  16384. %
  16385. {\if\edition\racketEd
  16386. \begin{lstlisting}
  16387. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16388. |$\Rightarrow$|
  16389. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16390. \end{lstlisting}
  16391. \fi}
  16392. %
  16393. {\if\edition\pythonEd\pythonColor
  16394. \begin{lstlisting}
  16395. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16396. |$\Rightarrow$|
  16397. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16398. \end{lstlisting}
  16399. \fi}
  16400. %
  16401. In addition to transforming each \key{Lambda} AST node into a
  16402. tuple, we create a top-level function definition for each
  16403. \key{Lambda}, as shown next.\\
  16404. \begin{minipage}{0.8\textwidth}
  16405. {\if\edition\racketEd
  16406. \begin{lstlisting}
  16407. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16408. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16409. ...
  16410. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16411. |\itm{body'}|)...))
  16412. \end{lstlisting}
  16413. \fi}
  16414. {\if\edition\pythonEd\pythonColor
  16415. \begin{lstlisting}
  16416. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16417. |$\itm{fvs}_1$| = clos[1]
  16418. |$\ldots$|
  16419. |$\itm{fvs}_m$| = clos[|$m$|]
  16420. |\itm{body'}|
  16421. \end{lstlisting}
  16422. \fi}
  16423. \end{minipage}\\
  16424. %
  16425. The \code{clos} parameter refers to the closure. The type
  16426. \itm{closTy} is a tuple type for which the first element type is
  16427. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16428. rest of the element types are the types of the free variables in the
  16429. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16430. is nontrivial to give a type to the function in the closure's
  16431. type.\footnote{To give an accurate type to a closure, we would need to
  16432. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16433. %
  16434. \racket{Translate the type
  16435. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16436. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16437. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16438. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16439. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16440. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16441. %% The dummy type is considered to be equal to any other type during type
  16442. %% checking.
  16443. The free variables become local variables that are initialized with
  16444. their values in the closure.
  16445. Closure conversion turns every function into a tuple, so the type
  16446. annotations in the program must also be translated. We recommend
  16447. defining an auxiliary recursive function for this purpose. Function
  16448. types should be translated as follows:
  16449. %
  16450. {\if\edition\racketEd
  16451. \begin{lstlisting}
  16452. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16453. |$\Rightarrow$|
  16454. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16455. \end{lstlisting}
  16456. \fi}
  16457. {\if\edition\pythonEd\pythonColor
  16458. \begin{lstlisting}
  16459. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16460. |$\Rightarrow$|
  16461. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16462. \end{lstlisting}
  16463. \fi}
  16464. %
  16465. This type indicates that the first thing in the tuple is a
  16466. function. The first parameter of the function is a tuple (a closure)
  16467. and the rest of the parameters are the ones from the original
  16468. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16469. omits the types of the free variables because (1) those types are not
  16470. available in this context, and (2) we do not need them in the code that
  16471. is generated for function application. So this type describes only the
  16472. first component of the closure tuple. At runtime the tuple may have
  16473. more components, but we ignore them at this point.
  16474. We transform function application into code that retrieves the
  16475. function from the closure and then calls the function, passing the
  16476. closure as the first argument. We place $e'$ in a temporary variable
  16477. to avoid code duplication.
  16478. \begin{center}
  16479. \begin{minipage}{\textwidth}
  16480. {\if\edition\racketEd
  16481. \begin{lstlisting}
  16482. (Apply |$e$| |$\itm{es}$|)
  16483. |$\Rightarrow$|
  16484. (Let |$\itm{tmp}$| |$e'$|
  16485. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16486. \end{lstlisting}
  16487. \fi}
  16488. %
  16489. {\if\edition\pythonEd\pythonColor
  16490. \begin{lstlisting}
  16491. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16492. |$\Rightarrow$|
  16493. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16494. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16495. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16496. \end{lstlisting}
  16497. \fi}
  16498. \end{minipage}
  16499. \end{center}
  16500. There is also the question of what to do with references to top-level
  16501. function definitions. To maintain a uniform translation of function
  16502. application, we turn function references into closures.
  16503. \begin{tabular}{lll}
  16504. \begin{minipage}{0.2\textwidth}
  16505. {\if\edition\racketEd
  16506. \begin{lstlisting}
  16507. (FunRef |$f$| |$n$|)
  16508. \end{lstlisting}
  16509. \fi}
  16510. {\if\edition\pythonEd\pythonColor
  16511. \begin{lstlisting}
  16512. FunRef(|$f$|, |$n$|)
  16513. \end{lstlisting}
  16514. \fi}
  16515. \end{minipage}
  16516. &
  16517. $\Rightarrow\qquad$
  16518. &
  16519. \begin{minipage}{0.5\textwidth}
  16520. {\if\edition\racketEd
  16521. \begin{lstlisting}
  16522. (Closure |$n$| (list (FunRef |$f$| |$n$|)))
  16523. \end{lstlisting}
  16524. \fi}
  16525. {\if\edition\pythonEd\pythonColor
  16526. \begin{lstlisting}
  16527. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16528. \end{lstlisting}
  16529. \fi}
  16530. \end{minipage}
  16531. \end{tabular} \\
  16532. We no longer need the annotated assignment statement \code{AnnAssign}
  16533. to support the type checking of \code{lambda} expressions, so we
  16534. translate it to a regular \code{Assign} statement.
  16535. The top-level function definitions need to be updated to take an extra
  16536. closure parameter, but that parameter is ignored in the body of those
  16537. functions.
  16538. \subsection{An Example Translation}
  16539. \label{sec:example-lambda}
  16540. Figure~\ref{fig:lexical-functions-example} shows the result of
  16541. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16542. program demonstrating lexical scoping that we discussed at the
  16543. beginning of this chapter.
  16544. \begin{figure}[tbp]
  16545. \begin{tcolorbox}[colback=white]
  16546. \begin{minipage}{0.8\textwidth}
  16547. {\if\edition\racketEd
  16548. % tests/lambda_test_6.rkt
  16549. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16550. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16551. (let ([y8 4])
  16552. (lambda: ([z9 : Integer]) : Integer
  16553. (+ x7 (+ y8 z9)))))
  16554. (define (main) : Integer
  16555. (let ([g0 ((fun-ref f6 1) 5)])
  16556. (let ([h1 ((fun-ref f6 1) 3)])
  16557. (+ (g0 11) (h1 15)))))
  16558. \end{lstlisting}
  16559. $\Rightarrow$
  16560. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16561. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16562. (let ([y8 4])
  16563. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16564. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16565. (let ([x7 (vector-ref fvs3 1)])
  16566. (let ([y8 (vector-ref fvs3 2)])
  16567. (+ x7 (+ y8 z9)))))
  16568. (define (main) : Integer
  16569. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16570. ((vector-ref clos5 0) clos5 5))])
  16571. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16572. ((vector-ref clos6 0) clos6 3))])
  16573. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16574. \end{lstlisting}
  16575. \fi}
  16576. %
  16577. {\if\edition\pythonEd\pythonColor
  16578. % free_var.py
  16579. \begin{lstlisting}
  16580. def f(x: int) -> Callable[[int],int]:
  16581. y = 4
  16582. return lambda z: x + y + z
  16583. g = f(5)
  16584. h = f(3)
  16585. print(g(11) + h(15))
  16586. \end{lstlisting}
  16587. $\Rightarrow$
  16588. \begin{lstlisting}
  16589. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16590. x = fvs_1[1]
  16591. y = fvs_1[2]
  16592. return (x + y[0] + z)
  16593. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16594. y = (uninitialized(int),)
  16595. y[0] = 4
  16596. return closure{1}({lambda_0}, x, y)
  16597. def main() -> int:
  16598. g = (begin: clos_3 = closure{1}({f})
  16599. clos_3[0](clos_3, 5))
  16600. h = (begin: clos_4 = closure{1}({f})
  16601. clos_4[0](clos_4, 3))
  16602. print((begin: clos_5 = g
  16603. clos_5[0](clos_5, 11))
  16604. + (begin: clos_6 = h
  16605. clos_6[0](clos_6, 15)))
  16606. return 0
  16607. \end{lstlisting}
  16608. \fi}
  16609. \end{minipage}
  16610. \end{tcolorbox}
  16611. \caption{Example of closure conversion.}
  16612. \label{fig:lexical-functions-example}
  16613. \end{figure}
  16614. \begin{exercise}\normalfont\normalsize
  16615. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16616. Create five new programs that use \key{lambda} functions and make use of
  16617. lexical scoping. Test your compiler on these new programs and all
  16618. your previously created test programs.
  16619. \end{exercise}
  16620. \section{Expose Allocation}
  16621. \label{sec:expose-allocation-r5}
  16622. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code that
  16623. allocates and initializes a tuple, similar to the translation of the
  16624. tuple creation in section~\ref{sec:expose-allocation}. The main
  16625. difference is replacing the use of \ALLOC{\itm{len}}{\itm{type}} with
  16626. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}. The result type of
  16627. the translation of $\CLOSURE{\itm{arity}}{\Exp^{*}}$ should be a tuple
  16628. type, but only a single element tuple type. The types of the tuple
  16629. elements that correspond to the free variables of the closure should
  16630. not appear in the tuple type. The new AST class \code{UncheckedCast}
  16631. can be used to adjust the result type.
  16632. \section{Explicate Control and \LangCLam{}}
  16633. \label{sec:explicate-r5}
  16634. The output language of \code{explicate\_control} is \LangCLam{}; the
  16635. definition of its abstract syntax is shown in
  16636. figure~\ref{fig:Clam-syntax}.
  16637. %
  16638. \racket{The only differences with respect to \LangCFun{} are the
  16639. addition of the \code{AllocateClosure} form to the grammar for
  16640. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16641. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16642. similar to the handling of other expressions such as primitive
  16643. operators.}
  16644. %
  16645. \python{The differences with respect to \LangCFun{} are the
  16646. additions of \code{Uninitialized}, \code{AllocateClosure},
  16647. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16648. \code{explicate\_control} pass is similar to the handling of other
  16649. expressions such as primitive operators.}
  16650. \newcommand{\ClambdaASTRacket}{
  16651. \begin{array}{lcl}
  16652. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16653. \itm{op} &::= & \code{procedure-arity}
  16654. \end{array}
  16655. }
  16656. \newcommand{\ClambdaASTPython}{
  16657. \begin{array}{lcl}
  16658. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16659. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16660. &\MID& \ARITY{\Atm}
  16661. \MID \key{UncheckedCast}\LP\Exp,\Type\RP
  16662. \end{array}
  16663. }
  16664. \begin{figure}[tp]
  16665. \begin{tcolorbox}[colback=white]
  16666. \small
  16667. {\if\edition\racketEd
  16668. \[
  16669. \begin{array}{l}
  16670. \gray{\CvarASTRacket} \\ \hline
  16671. \gray{\CifASTRacket} \\ \hline
  16672. \gray{\CloopASTRacket} \\ \hline
  16673. \gray{\CtupASTRacket} \\ \hline
  16674. \gray{\CfunASTRacket} \\ \hline
  16675. \ClambdaASTRacket \\
  16676. \begin{array}{lcl}
  16677. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16678. \end{array}
  16679. \end{array}
  16680. \]
  16681. \fi}
  16682. {\if\edition\pythonEd\pythonColor
  16683. \[
  16684. \begin{array}{l}
  16685. \gray{\CifASTPython} \\ \hline
  16686. \gray{\CtupASTPython} \\ \hline
  16687. \gray{\CfunASTPython} \\ \hline
  16688. \ClambdaASTPython \\
  16689. \begin{array}{lcl}
  16690. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16691. \end{array}
  16692. \end{array}
  16693. \]
  16694. \fi}
  16695. \end{tcolorbox}
  16696. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16697. \label{fig:Clam-syntax}
  16698. \index{subject}{Clambda@\LangCLam{} abstract syntax}
  16699. \end{figure}
  16700. \section{Select Instructions}
  16701. \label{sec:select-instructions-Llambda}
  16702. \index{subject}{select instructions}
  16703. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16704. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16705. (section~\ref{sec:select-instructions-gc}). The only difference is
  16706. that you should place the \itm{arity} in the tag that is stored at
  16707. position $0$ of the tuple. Recall that in
  16708. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16709. was not used. We store the arity in the $5$ bits starting at position
  16710. $57$.
  16711. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16712. instructions that access the tag from position $0$ of the vector and
  16713. extract the $5$ bits starting at position $57$ from the tag.}
  16714. %
  16715. \python{Compile a call to the \code{arity} operator to a sequence of
  16716. instructions that access the tag from position $0$ of the tuple
  16717. (representing a closure) and extract the $5$ bits starting at position
  16718. $57$ from the tag.}
  16719. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16720. needed for the compilation of \LangLam{}.
  16721. \begin{figure}[bthp]
  16722. \begin{tcolorbox}[colback=white]
  16723. {\if\edition\racketEd
  16724. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16725. \node (Lfun) at (0,2) {\large \LangLam{}};
  16726. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16727. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16728. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16729. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16730. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16731. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16732. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16733. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16734. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16735. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16736. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16737. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16738. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16739. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16740. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16741. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16742. \path[->,bend left=15] (Lfun) edge [above] node
  16743. {\ttfamily\footnotesize shrink} (Lfun-2);
  16744. \path[->,bend left=15] (Lfun-2) edge [above] node
  16745. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16746. \path[->,bend left=15] (Lfun-3) edge [above] node
  16747. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16748. \path[->,bend left=15] (F1-0) edge [left] node
  16749. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16750. \path[->,bend left=15] (F1-1) edge [below] node
  16751. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16752. \path[->,bend right=15] (F1-2) edge [above] node
  16753. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16754. \path[->,bend right=15] (F1-3) edge [above] node
  16755. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16756. \path[->,bend left=15] (F1-4) edge [right] node
  16757. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16758. \path[->,bend right=15] (F1-5) edge [below] node
  16759. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16760. \path[->,bend left=15] (F1-6) edge [above] node
  16761. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16762. \path[->] (C3-2) edge [right] node
  16763. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16764. \path[->,bend right=15] (x86-2) edge [right] node
  16765. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16766. \path[->,bend right=15] (x86-2-1) edge [below] node
  16767. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16768. \path[->,bend right=15] (x86-2-2) edge [right] node
  16769. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16770. \path[->,bend left=15] (x86-3) edge [above] node
  16771. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16772. \path[->,bend left=15] (x86-4) edge [right] node
  16773. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16774. \end{tikzpicture}
  16775. \fi}
  16776. {\if\edition\pythonEd\pythonColor
  16777. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16778. \node (Lfun) at (0,2) {\large \LangLam{}};
  16779. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16780. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16781. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16782. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16783. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16784. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16785. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16786. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16787. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16788. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16789. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16790. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16791. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16792. \path[->,bend left=15] (Lfun) edge [above] node
  16793. {\ttfamily\footnotesize shrink} (Lfun-2);
  16794. \path[->,bend left=15] (Lfun-2) edge [above] node
  16795. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16796. \path[->,bend left=15] (Lfun-3) edge [above] node
  16797. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16798. \path[->,bend left=15] (F1-0) edge [left] node
  16799. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16800. \path[->,bend left=15] (F1-1) edge [below] node
  16801. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16802. \path[->,bend left=15] (F1-2) edge [below] node
  16803. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16804. \path[->,bend right=15] (F1-3) edge [above] node
  16805. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16806. \path[->,bend right=15] (F1-5) edge [right] node
  16807. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16808. \path[->,bend left=15] (F1-6) edge [right] node
  16809. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16810. \path[->,bend right=15] (C3-2) edge [right] node
  16811. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16812. \path[->,bend right=15] (x86-2) edge [below] node
  16813. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16814. \path[->,bend right=15] (x86-3) edge [below] node
  16815. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16816. \path[->,bend left=15] (x86-4) edge [above] node
  16817. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16818. \end{tikzpicture}
  16819. \fi}
  16820. \end{tcolorbox}
  16821. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16822. functions.}
  16823. \label{fig:Llambda-passes}
  16824. \end{figure}
  16825. \clearpage
  16826. \section{Challenge: Optimize Closures}
  16827. \label{sec:optimize-closures}
  16828. In this chapter we compile lexically scoped functions into a
  16829. relatively efficient representation: flat closures. However, even this
  16830. representation comes with some overhead. For example, consider the
  16831. following program with a function \code{tail\_sum} that does not have
  16832. any free variables and where all the uses of \code{tail\_sum} are in
  16833. applications in which we know that only \code{tail\_sum} is being applied
  16834. (and not any other functions):
  16835. \begin{center}
  16836. \begin{minipage}{0.95\textwidth}
  16837. {\if\edition\racketEd
  16838. \begin{lstlisting}
  16839. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16840. (if (eq? n 0)
  16841. s
  16842. (tail_sum (- n 1) (+ n s))))
  16843. (+ (tail_sum 3 0) 36)
  16844. \end{lstlisting}
  16845. \fi}
  16846. {\if\edition\pythonEd\pythonColor
  16847. \begin{lstlisting}
  16848. def tail_sum(n : int, s : int) -> int:
  16849. if n == 0:
  16850. return s
  16851. else:
  16852. return tail_sum(n - 1, n + s)
  16853. print(tail_sum(3, 0) + 36)
  16854. \end{lstlisting}
  16855. \fi}
  16856. \end{minipage}
  16857. \end{center}
  16858. As described in this chapter, we uniformly apply closure conversion to
  16859. all functions, obtaining the following output for this program:
  16860. \begin{center}
  16861. \begin{minipage}{0.95\textwidth}
  16862. {\if\edition\racketEd
  16863. \begin{lstlisting}
  16864. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16865. (if (eq? n2 0)
  16866. s3
  16867. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16868. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16869. (define (main) : Integer
  16870. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16871. ((vector-ref clos6 0) clos6 3 0)) 27))
  16872. \end{lstlisting}
  16873. \fi}
  16874. {\if\edition\pythonEd\pythonColor
  16875. \begin{lstlisting}
  16876. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16877. if n_0 == 0:
  16878. return s_1
  16879. else:
  16880. return (begin: clos_2 = (tail_sum,)
  16881. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16882. def main() -> int :
  16883. print((begin: clos_4 = (tail_sum,)
  16884. clos_4[0](clos_4, 3, 0)) + 36)
  16885. return 0
  16886. \end{lstlisting}
  16887. \fi}
  16888. \end{minipage}
  16889. \end{center}
  16890. If this program were compiled according to the previous chapter, there
  16891. would be no allocation and the calls to \code{tail\_sum} would be
  16892. direct calls. In contrast, the program presented here allocates memory
  16893. for each closure and the calls to \code{tail\_sum} are indirect. These
  16894. two differences incur considerable overhead in a program such as this,
  16895. in which the allocations and indirect calls occur inside a tight loop.
  16896. One might think that this problem is trivial to solve: can't we just
  16897. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16898. and compile them to direct calls instead of treating it like a call to
  16899. a closure? We would also drop the new \code{fvs} parameter of
  16900. \code{tail\_sum}.
  16901. %
  16902. However, this problem is not so trivial, because a global function may
  16903. \emph{escape} and become involved in applications that also involve
  16904. closures. Consider the following example in which the application
  16905. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16906. application because the \code{lambda} may flow into \code{f}, but the
  16907. \code{inc} function might also flow into \code{f}:
  16908. \begin{center}
  16909. \begin{minipage}{\textwidth}
  16910. % lambda_test_30.rkt
  16911. {\if\edition\racketEd
  16912. \begin{lstlisting}
  16913. (define (inc [x : Integer]) : Integer
  16914. (+ x 1))
  16915. (let ([y (read)])
  16916. (let ([f (if (eq? (read) 0)
  16917. inc
  16918. (lambda: ([x : Integer]) : Integer (- x y)))])
  16919. (f 41)))
  16920. \end{lstlisting}
  16921. \fi}
  16922. {\if\edition\pythonEd\pythonColor
  16923. \begin{lstlisting}
  16924. def add1(x : int) -> int:
  16925. return x + 1
  16926. y = input_int()
  16927. g : Callable[[int], int] = lambda x: x - y
  16928. f = add1 if input_int() == 0 else g
  16929. print(f(41))
  16930. \end{lstlisting}
  16931. \fi}
  16932. \end{minipage}
  16933. \end{center}
  16934. If a global function name is used in any way other than as the
  16935. operator in a direct call, then we say that the function
  16936. \emph{escapes}. If a global function does not escape, then we do not
  16937. need to perform closure conversion on the function.
  16938. \begin{exercise}\normalfont\normalsize
  16939. Implement an auxiliary function for detecting which global
  16940. functions escape. Using that function, implement an improved version
  16941. of closure conversion that does not apply closure conversion to
  16942. global functions that do not escape but instead compiles them as
  16943. regular functions. Create several new test cases that check whether
  16944. your compiler properly detects whether global functions escape or not.
  16945. \end{exercise}
  16946. So far we have reduced the overhead of calling global functions, but
  16947. it would also be nice to reduce the overhead of calling a
  16948. \code{lambda} when we can determine at compile time which
  16949. \code{lambda} will be called. We refer to such calls as \emph{known
  16950. calls}. Consider the following example in which a \code{lambda} is
  16951. bound to \code{f} and then applied.
  16952. {\if\edition\racketEd
  16953. % lambda_test_9.rkt
  16954. \begin{lstlisting}
  16955. (let ([y (read)])
  16956. (let ([f (lambda: ([x : Integer]) : Integer
  16957. (+ x y))])
  16958. (f 21)))
  16959. \end{lstlisting}
  16960. \fi}
  16961. {\if\edition\pythonEd\pythonColor
  16962. \begin{lstlisting}
  16963. y = input_int()
  16964. f : Callable[[int],int] = lambda x: x + y
  16965. print(f(21))
  16966. \end{lstlisting}
  16967. \fi}
  16968. %
  16969. \noindent Closure conversion compiles the application
  16970. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16971. %
  16972. {\if\edition\racketEd
  16973. \begin{lstlisting}
  16974. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16975. (let ([y2 (vector-ref fvs6 1)])
  16976. (+ x3 y2)))
  16977. (define (main) : Integer
  16978. (let ([y2 (read)])
  16979. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16980. ((vector-ref f4 0) f4 21))))
  16981. \end{lstlisting}
  16982. \fi}
  16983. {\if\edition\pythonEd\pythonColor
  16984. \begin{lstlisting}
  16985. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16986. y_1 = fvs_4[1]
  16987. return x_2 + y_1[0]
  16988. def main() -> int:
  16989. y_1 = (777,)
  16990. y_1[0] = input_int()
  16991. f_0 = (lambda_3, y_1)
  16992. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16993. return 0
  16994. \end{lstlisting}
  16995. \fi}
  16996. %
  16997. \noindent However, we can instead compile the application
  16998. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16999. %
  17000. {\if\edition\racketEd
  17001. \begin{lstlisting}
  17002. (define (main) : Integer
  17003. (let ([y2 (read)])
  17004. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  17005. ((fun-ref lambda5 1) f4 21))))
  17006. \end{lstlisting}
  17007. \fi}
  17008. {\if\edition\pythonEd\pythonColor
  17009. \begin{lstlisting}
  17010. def main() -> int:
  17011. y_1 = (777,)
  17012. y_1[0] = input_int()
  17013. f_0 = (lambda_3, y_1)
  17014. print(lambda_3(f_0, 21))
  17015. return 0
  17016. \end{lstlisting}
  17017. \fi}
  17018. The problem of determining which \code{lambda} will be called from a
  17019. particular application is quite challenging in general and the topic
  17020. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  17021. following exercise we recommend that you compile an application to a
  17022. direct call when the operator is a variable and \racket{the variable
  17023. is \code{let}-bound to a closure}\python{the previous assignment to
  17024. the variable is a closure}. This can be accomplished by maintaining
  17025. an environment that maps variables to function names. Extend the
  17026. environment whenever you encounter a closure on the right-hand side of
  17027. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  17028. name of the global function for the closure. This pass should come
  17029. after closure conversion.
  17030. \begin{exercise}\normalfont\normalsize
  17031. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  17032. compiles known calls into direct calls. Verify that your compiler is
  17033. successful in this regard on several example programs.
  17034. \end{exercise}
  17035. These exercises only scratch the surface of closure optimization. A
  17036. good next step for the interested reader is to look at the work of
  17037. \citet{Keep:2012ab}.
  17038. \section{Further Reading}
  17039. The notion of lexically scoped functions predates modern computers by
  17040. about a decade. They were invented by \citet{Church:1932aa}, who
  17041. proposed the lambda calculus as a foundation for logic. Anonymous
  17042. functions were included in the LISP~\citep{McCarthy:1960dz}
  17043. programming language but were initially dynamically scoped. The Scheme
  17044. dialect of LISP adopted lexical scoping, and
  17045. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  17046. Scheme programs. However, environments were represented as linked
  17047. lists, so variable look-up was linear in the size of the
  17048. environment. \citet{Appel91} gives a detailed description of several
  17049. closure representations. In this chapter we represent environments
  17050. using flat closures, which were invented by
  17051. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  17052. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  17053. closures, variable look-up is constant time but the time to create a
  17054. closure is proportional to the number of its free variables. Flat
  17055. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  17056. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  17057. % todo: related work on assignment conversion (e.g. orbit and rabbit
  17058. % compilers)
  17059. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17060. \chapter{Dynamic Typing}
  17061. \label{ch:Ldyn}
  17062. \index{subject}{dynamic typing}
  17063. \setcounter{footnote}{0}
  17064. In this chapter we learn how to compile \LangDyn{}, a dynamically
  17065. typed language that is a subset of \racket{Racket}\python{Python}. The
  17066. focus on dynamic typing is in contrast to the previous chapters, which
  17067. have studied the compilation of statically typed languages. In
  17068. dynamically typed languages such as \LangDyn{}, a particular
  17069. expression may produce a value of a different type each time it is
  17070. executed. Consider the following example with a conditional \code{if}
  17071. expression that may return a Boolean or an integer depending on the
  17072. input to the program:
  17073. % part of dynamic_test_25.rkt
  17074. {\if\edition\racketEd
  17075. \begin{lstlisting}
  17076. (not (if (eq? (read) 1) #f 0))
  17077. \end{lstlisting}
  17078. \fi}
  17079. {\if\edition\pythonEd\pythonColor
  17080. \begin{lstlisting}
  17081. not (False if input_int() == 1 else 0)
  17082. \end{lstlisting}
  17083. \fi}
  17084. Languages that allow expressions to produce different kinds of values
  17085. are called \emph{polymorphic}, a word composed of the Greek roots
  17086. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  17087. There are several kinds of polymorphism in programming languages, such as
  17088. subtype polymorphism\index{subject}{subtype polymorphism} and
  17089. parametric polymorphism\index{subject}{parametric polymorphism}
  17090. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  17091. study in this chapter does not have a special name; it is the kind
  17092. that arises in dynamically typed languages.
  17093. Another characteristic of dynamically typed languages is that
  17094. their primitive operations, such as \code{not}, are often defined to operate
  17095. on many different types of values. In fact, in
  17096. \racket{Racket}\python{Python}, the \code{not} operator produces a
  17097. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  17098. given anything else it returns \FALSE{}.
  17099. Furthermore, even when primitive operations restrict their inputs to
  17100. values of a certain type, this restriction is enforced at runtime
  17101. instead of during compilation. For example, the tuple read
  17102. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  17103. results in a runtime error because the first argument must
  17104. be a tuple, not a Boolean.
  17105. \section{The \LangDyn{} Language}
  17106. \newcommand{\LdynGrammarRacket}{
  17107. \begin{array}{rcl}
  17108. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  17109. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  17110. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  17111. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  17112. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  17113. \end{array}
  17114. }
  17115. \newcommand{\LdynASTRacket}{
  17116. \begin{array}{lcl}
  17117. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17118. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  17119. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  17120. \end{array}
  17121. }
  17122. \begin{figure}[tp]
  17123. \centering
  17124. \begin{tcolorbox}[colback=white]
  17125. \small
  17126. {\if\edition\racketEd
  17127. \[
  17128. \begin{array}{l}
  17129. \gray{\LintGrammarRacket{}} \\ \hline
  17130. \gray{\LvarGrammarRacket{}} \\ \hline
  17131. \gray{\LifGrammarRacket{}} \\ \hline
  17132. \gray{\LwhileGrammarRacket} \\ \hline
  17133. \gray{\LtupGrammarRacket} \\ \hline
  17134. \LdynGrammarRacket \\
  17135. \begin{array}{rcl}
  17136. \LangDynM{} &::=& \Def\ldots\; \Exp
  17137. \end{array}
  17138. \end{array}
  17139. \]
  17140. \fi}
  17141. {\if\edition\pythonEd\pythonColor
  17142. \[
  17143. \begin{array}{rcl}
  17144. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  17145. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  17146. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  17147. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  17148. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  17149. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  17150. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  17151. \MID \CLEN{\Exp} \\
  17152. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17153. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  17154. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  17155. \MID \Var\mathop{\key{=}}\Exp \\
  17156. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  17157. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  17158. &\MID& \CRETURN{\Exp} \\
  17159. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  17160. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  17161. \end{array}
  17162. \]
  17163. \fi}
  17164. \end{tcolorbox}
  17165. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  17166. \label{fig:r7-concrete-syntax}
  17167. \index{subject}{Ldyn@\LangDyn{} concrete syntax}
  17168. \end{figure}
  17169. \begin{figure}[tp]
  17170. \centering
  17171. \begin{tcolorbox}[colback=white]
  17172. \small
  17173. {\if\edition\racketEd
  17174. \[
  17175. \begin{array}{l}
  17176. \gray{\LintASTRacket{}} \\ \hline
  17177. \gray{\LvarASTRacket{}} \\ \hline
  17178. \gray{\LifASTRacket{}} \\ \hline
  17179. \gray{\LwhileASTRacket} \\ \hline
  17180. \gray{\LtupASTRacket} \\ \hline
  17181. \LdynASTRacket \\
  17182. \begin{array}{lcl}
  17183. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17184. \end{array}
  17185. \end{array}
  17186. \]
  17187. \fi}
  17188. {\if\edition\pythonEd\pythonColor
  17189. \[
  17190. \begin{array}{rcl}
  17191. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17192. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17193. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17194. \MID \code{Is()} \\
  17195. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17196. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17197. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17198. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17199. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17200. &\MID& \VAR{\Var{}}
  17201. \MID \BOOL{\itm{bool}}
  17202. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17203. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17204. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17205. &\MID& \LEN{\Exp} \\
  17206. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17207. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17208. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17209. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17210. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17211. &\MID& \RETURN{\Exp} \\
  17212. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17213. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17214. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17215. \end{array}
  17216. \]
  17217. \fi}
  17218. \end{tcolorbox}
  17219. \caption{The abstract syntax of \LangDyn{}.}
  17220. \label{fig:r7-syntax}
  17221. \index{subject}{Ldyn@\LangDyn{} abstract syntax}
  17222. \end{figure}
  17223. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17224. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17225. %
  17226. There is no type checker for \LangDyn{} because it checks types only
  17227. at runtime.
  17228. The definitional interpreter for \LangDyn{} is presented in
  17229. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17230. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17231. \INT{n}. Instead of simply returning the integer \code{n} (as
  17232. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17233. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17234. value} that combines an underlying value with a tag that identifies
  17235. what kind of value it is. We define the following \racket{struct}\python{class}
  17236. to represent tagged values:
  17237. %
  17238. {\if\edition\racketEd
  17239. \begin{lstlisting}
  17240. (struct Tagged (value tag) #:transparent)
  17241. \end{lstlisting}
  17242. \fi}
  17243. {\if\edition\pythonEd\pythonColor
  17244. \begin{minipage}{\textwidth}
  17245. \begin{lstlisting}
  17246. @dataclass(eq=True)
  17247. class Tagged(Value):
  17248. value : Value
  17249. tag : str
  17250. def __str__(self):
  17251. return str(self.value)
  17252. \end{lstlisting}
  17253. \end{minipage}
  17254. \fi}
  17255. %
  17256. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17257. \code{Vector}, and \code{Procedure}.}
  17258. %
  17259. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17260. \skey{tuple}, and \skey{function}.}
  17261. %
  17262. Tags are closely related to types but do not always capture all the
  17263. information that a type does.
  17264. %
  17265. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17266. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17267. Any)} is tagged with \code{Procedure}.}
  17268. %
  17269. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17270. is tagged with \skey{tuple} and a function of type
  17271. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17272. is tagged with \skey{function}.}
  17273. Next consider the match case for accessing the element of a tuple.
  17274. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17275. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17276. argument is a tuple and the second is an integer.
  17277. \racket{
  17278. If they are not, a \code{trapped-error} is raised. Recall from
  17279. section~\ref{sec:interp_Lint} that when a definition interpreter
  17280. raises a \code{trapped-error} error, the compiled code must also
  17281. signal an error by exiting with return code \code{255}. A
  17282. \code{trapped-error} is also raised if the index is not less than the
  17283. length of the vector.
  17284. }
  17285. %
  17286. \python{If they are not, an exception is raised. The compiled code
  17287. must also signal an error by exiting with return code \code{255}. A
  17288. exception is also raised if the index is not less than the length of the
  17289. tuple or if it is negative.}
  17290. \begin{figure}[tbp]
  17291. \begin{tcolorbox}[colback=white]
  17292. {\if\edition\racketEd
  17293. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17294. (define ((interp-Ldyn-exp env) ast)
  17295. (define recur (interp-Ldyn-exp env))
  17296. (match ast
  17297. [(Var x) (unbox (lookup x env)]
  17298. [(Int n) (Tagged n 'Integer)]
  17299. [(Bool b) (Tagged b 'Boolean)]
  17300. [(Lambda xs rt body)
  17301. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17302. [(Prim 'vector es)
  17303. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17304. [(Prim 'vector-ref (list e1 e2))
  17305. (define vec (recur e1)) (define i (recur e2))
  17306. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17307. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17308. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17309. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17310. [(Prim 'vector-set! (list e1 e2 e3))
  17311. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17312. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17313. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17314. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17315. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17316. (Tagged (void) 'Void)]
  17317. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17318. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17319. [(Prim 'or (list e1 e2))
  17320. (define v1 (recur e1))
  17321. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17322. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17323. [(Prim op (list e1))
  17324. #:when (set-member? type-predicates op)
  17325. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17326. [(Prim op es)
  17327. (define args (map recur es))
  17328. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17329. (unless (for/or ([expected-tags (op-tags op)])
  17330. (equal? expected-tags tags))
  17331. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17332. (tag-value
  17333. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17334. [(If q t f)
  17335. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17336. [(Apply f es)
  17337. (define new-f (recur f)) (define args (map recur es))
  17338. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17339. (match f-val
  17340. [`(function ,xs ,body ,lam-env)
  17341. (unless (eq? (length xs) (length args))
  17342. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17343. (define new-env (append (map cons xs args) lam-env))
  17344. ((interp-Ldyn-exp new-env) body)]
  17345. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17346. \end{lstlisting}
  17347. \fi}
  17348. {\if\edition\pythonEd\pythonColor
  17349. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17350. class InterpLdyn(InterpLlambda):
  17351. def interp_exp(self, e, env):
  17352. match e:
  17353. case Constant(n):
  17354. return self.tag(super().interp_exp(e, env))
  17355. case Tuple(es, Load()):
  17356. return self.tag(super().interp_exp(e, env))
  17357. case Lambda(params, body):
  17358. return self.tag(super().interp_exp(e, env))
  17359. case Call(Name('input_int'), []):
  17360. return self.tag(super().interp_exp(e, env))
  17361. case BinOp(left, Add(), right):
  17362. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17363. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17364. case BinOp(left, Sub(), right):
  17365. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17366. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17367. case UnaryOp(USub(), e1):
  17368. v = self.interp_exp(e1, env)
  17369. return self.tag(- self.untag(v, 'int', e))
  17370. case IfExp(test, body, orelse):
  17371. v = self.interp_exp(test, env)
  17372. if self.untag(v, 'bool', e):
  17373. return self.interp_exp(body, env)
  17374. else:
  17375. return self.interp_exp(orelse, env)
  17376. case UnaryOp(Not(), e1):
  17377. v = self.interp_exp(e1, env)
  17378. return self.tag(not self.untag(v, 'bool', e))
  17379. case BoolOp(And(), values):
  17380. left = values[0]; right = values[1]
  17381. l = self.interp_exp(left, env)
  17382. if self.untag(l, 'bool', e):
  17383. return self.interp_exp(right, env)
  17384. else:
  17385. return self.tag(False)
  17386. case BoolOp(Or(), values):
  17387. left = values[0]; right = values[1]
  17388. l = self.interp_exp(left, env)
  17389. if self.untag(l, 'bool', e):
  17390. return self.tag(True)
  17391. else:
  17392. return self.interp_exp(right, env)
  17393. \end{lstlisting}
  17394. \fi}
  17395. \end{tcolorbox}
  17396. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17397. \label{fig:interp-Ldyn}
  17398. \end{figure}
  17399. {\if\edition\pythonEd\pythonColor
  17400. \begin{figure}[tbp]
  17401. \begin{tcolorbox}[colback=white]
  17402. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17403. # interp_exp continued
  17404. case Compare(left, [cmp], [right]):
  17405. l = self.interp_exp(left, env)
  17406. r = self.interp_exp(right, env)
  17407. if l.tag == r.tag:
  17408. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17409. else:
  17410. raise Exception('interp Compare unexpected '
  17411. + repr(l) + ' ' + repr(r))
  17412. case Subscript(tup, index, Load()):
  17413. t = self.interp_exp(tup, env)
  17414. n = self.interp_exp(index, env)
  17415. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17416. case Call(Name('len'), [tup]):
  17417. t = self.interp_exp(tup, env)
  17418. return self.tag(len(self.untag(t, 'tuple', e)))
  17419. case _:
  17420. return self.tag(super().interp_exp(e, env))
  17421. def interp_stmt(self, s, env, cont):
  17422. match s:
  17423. case If(test, body, orelse):
  17424. v = self.interp_exp(test, env)
  17425. match self.untag(v, 'bool', s):
  17426. case True:
  17427. return self.interp_stmts(body + cont, env)
  17428. case False:
  17429. return self.interp_stmts(orelse + cont, env)
  17430. case While(test, body, []):
  17431. v = self.interp_exp(test, env)
  17432. if self.untag(v, 'bool', test):
  17433. self.interp_stmts(body + [s] + cont, env)
  17434. else:
  17435. return self.interp_stmts(cont, env)
  17436. case Assign([Subscript(tup, index)], value):
  17437. tup = self.interp_exp(tup, env)
  17438. index = self.interp_exp(index, env)
  17439. tup_v = self.untag(tup, 'tuple', s)
  17440. index_v = self.untag(index, 'int', s)
  17441. tup_v[index_v] = self.interp_exp(value, env)
  17442. return self.interp_stmts(cont, env)
  17443. case FunctionDef(name, params, bod, dl, returns, comment):
  17444. if isinstance(params, ast.arguments):
  17445. ps = [p.arg for p in params.args]
  17446. else:
  17447. ps = [x for (x,t) in params]
  17448. env[name] = self.tag(Function(name, ps, bod, env))
  17449. return self.interp_stmts(cont, env)
  17450. case _:
  17451. return super().interp_stmt(s, env, cont)
  17452. \end{lstlisting}
  17453. \end{tcolorbox}
  17454. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17455. \label{fig:interp-Ldyn-2}
  17456. \end{figure}
  17457. \fi}
  17458. \begin{figure}[tbp]
  17459. \begin{tcolorbox}[colback=white]
  17460. {\if\edition\racketEd
  17461. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17462. (define (interp-op op)
  17463. (match op
  17464. ['+ fx+]
  17465. ['- fx-]
  17466. ['read read-fixnum]
  17467. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17468. ['< (lambda (v1 v2)
  17469. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17470. ['<= (lambda (v1 v2)
  17471. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17472. ['> (lambda (v1 v2)
  17473. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17474. ['>= (lambda (v1 v2)
  17475. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17476. ['boolean? boolean?]
  17477. ['integer? fixnum?]
  17478. ['void? void?]
  17479. ['vector? vector?]
  17480. ['vector-length vector-length]
  17481. ['procedure? (match-lambda
  17482. [`(functions ,xs ,body ,env) #t] [else #f])]
  17483. [else (error 'interp-op "unknown operator" op)]))
  17484. (define (op-tags op)
  17485. (match op
  17486. ['+ '((Integer Integer))]
  17487. ['- '((Integer Integer) (Integer))]
  17488. ['read '(())]
  17489. ['not '((Boolean))]
  17490. ['< '((Integer Integer))]
  17491. ['<= '((Integer Integer))]
  17492. ['> '((Integer Integer))]
  17493. ['>= '((Integer Integer))]
  17494. ['vector-length '((Vector))]))
  17495. (define type-predicates
  17496. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17497. (define (tag-value v)
  17498. (cond [(boolean? v) (Tagged v 'Boolean)]
  17499. [(fixnum? v) (Tagged v 'Integer)]
  17500. [(procedure? v) (Tagged v 'Procedure)]
  17501. [(vector? v) (Tagged v 'Vector)]
  17502. [(void? v) (Tagged v 'Void)]
  17503. [else (error 'tag-value "unidentified value ~a" v)]))
  17504. (define (check-tag val expected ast)
  17505. (define tag (Tagged-tag val))
  17506. (unless (eq? tag expected)
  17507. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17508. \end{lstlisting}
  17509. \fi}
  17510. {\if\edition\pythonEd\pythonColor
  17511. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17512. class InterpLdyn(InterpLlambda):
  17513. def tag(self, v):
  17514. if v is True or v is False:
  17515. return Tagged(v, 'bool')
  17516. elif isinstance(v, int):
  17517. return Tagged(v, 'int')
  17518. elif isinstance(v, Function):
  17519. return Tagged(v, 'function')
  17520. elif isinstance(v, tuple):
  17521. return Tagged(v, 'tuple')
  17522. elif isinstance(v, type(None)):
  17523. return Tagged(v, 'none')
  17524. else:
  17525. raise Exception('tag: unexpected ' + repr(v))
  17526. def untag(self, v, expected_tag, ast):
  17527. match v:
  17528. case Tagged(val, tag) if tag == expected_tag:
  17529. return val
  17530. case _:
  17531. raise TrappedError('expected Tagged value with '
  17532. + expected_tag + ', not ' + ' ' + repr(v))
  17533. def apply_fun(self, fun, args, e):
  17534. f = self.untag(fun, 'function', e)
  17535. return super().apply_fun(f, args, e)
  17536. \end{lstlisting}
  17537. \fi}
  17538. \end{tcolorbox}
  17539. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17540. \label{fig:interp-Ldyn-aux}
  17541. \end{figure}
  17542. %\clearpage
  17543. \section{Representation of Tagged Values}
  17544. The interpreter for \LangDyn{} introduced a new kind of value: the
  17545. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17546. represent tagged values at the bit level. Because almost every
  17547. operation in \LangDyn{} involves manipulating tagged values, the
  17548. representation must be efficient. Recall that all our values are 64
  17549. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17550. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17551. $011$ for procedures, and $101$ for the void value\python{,
  17552. \key{None}}. We define the following auxiliary function for mapping
  17553. types to tag codes:
  17554. %
  17555. {\if\edition\racketEd
  17556. \begin{align*}
  17557. \itm{tagof}(\key{Integer}) &= 001 \\
  17558. \itm{tagof}(\key{Boolean}) &= 100 \\
  17559. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17560. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17561. \itm{tagof}(\key{Void}) &= 101
  17562. \end{align*}
  17563. \fi}
  17564. {\if\edition\pythonEd\pythonColor
  17565. \begin{align*}
  17566. \itm{tagof}(\key{IntType()}) &= 001 \\
  17567. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17568. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17569. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17570. \itm{tagof}(\key{type(None)}) &= 101
  17571. \end{align*}
  17572. \fi}
  17573. %
  17574. This stealing of 3 bits comes at some price: integers are now restricted
  17575. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17576. affect tuples and procedures because those values are addresses, and
  17577. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17578. they are always $000$. Thus, we do not lose information by overwriting
  17579. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17580. to recover the original address.
  17581. To make tagged values into first-class entities, we can give them a
  17582. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17583. operations such as \code{Inject} and \code{Project} for creating and
  17584. using them, yielding the statically typed \LangAny{} intermediate
  17585. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17586. section~\ref{sec:compile-r7}; in the next section we describe the
  17587. \LangAny{} language in greater detail.
  17588. \section{The \LangAny{} Language}
  17589. \label{sec:Rany-lang}
  17590. \newcommand{\LanyASTRacket}{
  17591. \begin{array}{lcl}
  17592. \Type &::= & \ANYTY \\
  17593. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17594. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17595. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17596. \itm{op} &::= & \code{any-vector-length}
  17597. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17598. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17599. \MID \code{procedure?} \MID \code{void?} \\
  17600. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17601. \end{array}
  17602. }
  17603. \newcommand{\LanyASTPython}{
  17604. \begin{array}{lcl}
  17605. \Type &::= & \key{AnyType()} \\
  17606. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17607. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17608. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17609. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17610. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17611. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17612. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17613. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17614. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17615. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17616. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17617. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17618. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17619. \end{array}
  17620. }
  17621. \begin{figure}[tp]
  17622. \centering
  17623. \begin{tcolorbox}[colback=white]
  17624. \small
  17625. {\if\edition\racketEd
  17626. \[
  17627. \begin{array}{l}
  17628. \gray{\LintOpAST} \\ \hline
  17629. \gray{\LvarASTRacket{}} \\ \hline
  17630. \gray{\LifASTRacket{}} \\ \hline
  17631. \gray{\LwhileASTRacket{}} \\ \hline
  17632. \gray{\LtupASTRacket{}} \\ \hline
  17633. \gray{\LfunASTRacket} \\ \hline
  17634. \gray{\LlambdaASTRacket} \\ \hline
  17635. \LanyASTRacket \\
  17636. \begin{array}{lcl}
  17637. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17638. \end{array}
  17639. \end{array}
  17640. \]
  17641. \fi}
  17642. {\if\edition\pythonEd\pythonColor
  17643. \[
  17644. \begin{array}{l}
  17645. \gray{\LintASTPython} \\ \hline
  17646. \gray{\LvarASTPython{}} \\ \hline
  17647. \gray{\LifASTPython{}} \\ \hline
  17648. \gray{\LwhileASTPython{}} \\ \hline
  17649. \gray{\LtupASTPython{}} \\ \hline
  17650. \gray{\LfunASTPython} \\ \hline
  17651. \gray{\LlambdaASTPython} \\ \hline
  17652. \LanyASTPython \\
  17653. \begin{array}{lcl}
  17654. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17655. \end{array}
  17656. \end{array}
  17657. \]
  17658. \fi}
  17659. \end{tcolorbox}
  17660. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17661. \label{fig:Lany-syntax}
  17662. \index{subject}{Lany@\LangAny{} abstract syntax}
  17663. \end{figure}
  17664. The definition of the abstract syntax of \LangAny{} is given in
  17665. figure~\ref{fig:Lany-syntax}.
  17666. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17667. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17668. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17669. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17670. converts the tagged value produced by expression $e$ into a value of
  17671. type $T$ or halts the program if the type tag does not match $T$.
  17672. %
  17673. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17674. restricted to be a flat type (the nonterminal $\FType$) which
  17675. simplifies the implementation and complies with the needs for
  17676. compiling \LangDyn{}.
  17677. The \racket{\code{any-vector}} operators
  17678. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17679. operations so that they can be applied to a value of type
  17680. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17681. tuple operations in that the index is not restricted to a literal
  17682. integer in the grammar but is allowed to be any expression.
  17683. \racket{The type predicates such as
  17684. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17685. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17686. the predicate and return {\FALSE} otherwise.}
  17687. \racket{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}
  17688. and it uses the auxiliary functions presented in figure~\ref{fig:type-check-Lany-aux}.}
  17689. \python{The type checker for \LangAny{} is shown in figure~\ref{fig:type-check-Lany}.}
  17690. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17691. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17692. \begin{figure}[btp]
  17693. \begin{tcolorbox}[colback=white]
  17694. {\if\edition\racketEd
  17695. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17696. (define type-check-Lany-class
  17697. (class type-check-Llambda-class
  17698. (super-new)
  17699. (inherit check-type-equal?)
  17700. (define/override (type-check-exp env)
  17701. (lambda (e)
  17702. (define recur (type-check-exp env))
  17703. (match e
  17704. [(Inject e1 ty)
  17705. (unless (flat-ty? ty)
  17706. (error 'type-check "may only inject from flat type, not ~a" ty))
  17707. (define-values (new-e1 e-ty) (recur e1))
  17708. (check-type-equal? e-ty ty e)
  17709. (values (Inject new-e1 ty) 'Any)]
  17710. [(Project e1 ty)
  17711. (unless (flat-ty? ty)
  17712. (error 'type-check "may only project to flat type, not ~a" ty))
  17713. (define-values (new-e1 e-ty) (recur e1))
  17714. (check-type-equal? e-ty 'Any e)
  17715. (values (Project new-e1 ty) ty)]
  17716. [(Prim 'any-vector-length (list e1))
  17717. (define-values (e1^ t1) (recur e1))
  17718. (check-type-equal? t1 'Any e)
  17719. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17720. [(Prim 'any-vector-ref (list e1 e2))
  17721. (define-values (e1^ t1) (recur e1))
  17722. (define-values (e2^ t2) (recur e2))
  17723. (check-type-equal? t1 'Any e)
  17724. (check-type-equal? t2 'Integer e)
  17725. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17726. [(Prim 'any-vector-set! (list e1 e2 e3))
  17727. (define-values (e1^ t1) (recur e1))
  17728. (define-values (e2^ t2) (recur e2))
  17729. (define-values (e3^ t3) (recur e3))
  17730. (check-type-equal? t1 'Any e)
  17731. (check-type-equal? t2 'Integer e)
  17732. (check-type-equal? t3 'Any e)
  17733. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17734. [(Prim pred (list e1))
  17735. #:when (set-member? (type-predicates) pred)
  17736. (define-values (new-e1 e-ty) (recur e1))
  17737. (check-type-equal? e-ty 'Any e)
  17738. (values (Prim pred (list new-e1)) 'Boolean)]
  17739. [(Prim 'eq? (list arg1 arg2))
  17740. (define-values (e1 t1) (recur arg1))
  17741. (define-values (e2 t2) (recur arg2))
  17742. (match* (t1 t2)
  17743. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17744. [(other wise) (check-type-equal? t1 t2 e)])
  17745. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17746. [else ((super type-check-exp env) e)])))
  17747. ))
  17748. \end{lstlisting}
  17749. \fi}
  17750. {\if\edition\pythonEd\pythonColor
  17751. \begin{lstlisting}
  17752. class TypeCheckLany(TypeCheckLlambda):
  17753. def type_check_exp(self, e, env):
  17754. match e:
  17755. case Inject(value, typ):
  17756. self.check_exp(value, typ, env)
  17757. return AnyType()
  17758. case Project(value, typ):
  17759. self.check_exp(value, AnyType(), env)
  17760. return typ
  17761. case Call(Name('any_tuple_load'), [tup, index]):
  17762. self.check_exp(tup, AnyType(), env)
  17763. self.check_exp(index, IntType(), env)
  17764. return AnyType()
  17765. case Call(Name('any_len'), [tup]):
  17766. self.check_exp(tup, AnyType(), env)
  17767. return IntType()
  17768. case Call(Name('arity'), [fun]):
  17769. ty = self.type_check_exp(fun, env)
  17770. match ty:
  17771. case FunctionType(ps, rt):
  17772. return IntType()
  17773. case TupleType([FunctionType(ps,rs)]):
  17774. return IntType()
  17775. case _:
  17776. raise Exception('type check arity unexpected ' + repr(ty))
  17777. case Call(Name('make_any'), [value, tag]):
  17778. self.type_check_exp(value, env)
  17779. self.check_exp(tag, IntType(), env)
  17780. return AnyType()
  17781. case AnnLambda(params, returns, body):
  17782. new_env = {x:t for (x,t) in env.items()}
  17783. for (x,t) in params:
  17784. new_env[x] = t
  17785. return_t = self.type_check_exp(body, new_env)
  17786. self.check_type_equal(returns, return_t, e)
  17787. return FunctionType([t for (x,t) in params], return_t)
  17788. case _:
  17789. return super().type_check_exp(e, env)
  17790. \end{lstlisting}
  17791. \fi}
  17792. \end{tcolorbox}
  17793. \caption{Type checker for the \LangAny{} language.}
  17794. \label{fig:type-check-Lany}
  17795. \end{figure}
  17796. {\if\edition\racketEd
  17797. \begin{figure}[tbp]
  17798. \begin{tcolorbox}[colback=white]
  17799. \begin{lstlisting}
  17800. (define/override (operator-types)
  17801. (append
  17802. '((integer? . ((Any) . Boolean))
  17803. (vector? . ((Any) . Boolean))
  17804. (procedure? . ((Any) . Boolean))
  17805. (void? . ((Any) . Boolean)))
  17806. (super operator-types)))
  17807. (define/public (type-predicates)
  17808. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17809. (define/public (flat-ty? ty)
  17810. (match ty
  17811. [(or `Integer `Boolean `Void) #t]
  17812. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17813. [`(,ts ... -> ,rt)
  17814. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17815. [else #f]))
  17816. \end{lstlisting}
  17817. \end{tcolorbox}
  17818. \caption{Auxiliary methods for type checking \LangAny{}.}
  17819. \label{fig:type-check-Lany-aux}
  17820. \end{figure}
  17821. \fi}
  17822. \begin{figure}[tbp]
  17823. \begin{tcolorbox}[colback=white]
  17824. {\if\edition\racketEd
  17825. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17826. (define interp-Lany-class
  17827. (class interp-Llambda-class
  17828. (super-new)
  17829. (define/override (interp-op op)
  17830. (match op
  17831. ['boolean? (match-lambda
  17832. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17833. [else #f])]
  17834. ['integer? (match-lambda
  17835. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17836. [else #f])]
  17837. ['vector? (match-lambda
  17838. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17839. [else #f])]
  17840. ['procedure? (match-lambda
  17841. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17842. [else #f])]
  17843. ['eq? (match-lambda*
  17844. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17845. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17846. [ls (apply (super interp-op op) ls)])]
  17847. ['any-vector-ref (lambda (v i)
  17848. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17849. ['any-vector-set! (lambda (v i a)
  17850. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17851. ['any-vector-length (lambda (v)
  17852. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17853. [else (super interp-op op)]))
  17854. (define/override ((interp-exp env) e)
  17855. (define recur (interp-exp env))
  17856. (match e
  17857. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17858. [(Project e ty2) (apply-project (recur e) ty2)]
  17859. [else ((super interp-exp env) e)]))
  17860. ))
  17861. (define (interp-Lany p)
  17862. (send (new interp-Lany-class) interp-program p))
  17863. \end{lstlisting}
  17864. \fi}
  17865. {\if\edition\pythonEd\pythonColor
  17866. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17867. class InterpLany(InterpLlambda):
  17868. def interp_exp(self, e, env):
  17869. match e:
  17870. case Inject(value, typ):
  17871. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17872. case Project(value, typ):
  17873. match self.interp_exp(value, env):
  17874. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17875. return val
  17876. case _:
  17877. raise Exception('failed project to ' + self.type_to_tag(typ))
  17878. case Call(Name('any_tuple_load'), [tup, index]):
  17879. match self.interp_exp(tup, env):
  17880. case Tagged(v, tag):
  17881. return v[self.interp_exp(index, env)]
  17882. case _:
  17883. raise Exception('in any_tuple_load untagged value')
  17884. case Call(Name('any_len'), [value]):
  17885. match self.interp_exp(value, env):
  17886. case Tagged(value, tag):
  17887. return len(value)
  17888. case _:
  17889. raise Exception('interp any_len untagged value')
  17890. case Call(Name('arity'), [fun]):
  17891. return self.arity(self.interp_exp(fun, env))
  17892. case _:
  17893. return super().interp_exp(e, env)
  17894. \end{lstlisting}
  17895. \fi}
  17896. \end{tcolorbox}
  17897. \caption{Interpreter for \LangAny{}.}
  17898. \label{fig:interp-Lany}
  17899. \end{figure}
  17900. \begin{figure}[btp]
  17901. \begin{tcolorbox}[colback=white]
  17902. {\if\edition\racketEd
  17903. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17904. (define/public (apply-inject v tg) (Tagged v tg))
  17905. (define/public (apply-project v ty2)
  17906. (define tag2 (any-tag ty2))
  17907. (match v
  17908. [(Tagged v1 tag1)
  17909. (cond
  17910. [(eq? tag1 tag2)
  17911. (match ty2
  17912. [`(Vector ,ts ...)
  17913. (define l1 ((interp-op 'vector-length) v1))
  17914. (cond
  17915. [(eq? l1 (length ts)) v1]
  17916. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17917. l1 (length ts))])]
  17918. [`(,ts ... -> ,rt)
  17919. (match v1
  17920. [`(function ,xs ,body ,env)
  17921. (cond [(eq? (length xs) (length ts)) v1]
  17922. [else
  17923. (error 'apply-project "arity mismatch ~a != ~a"
  17924. (length xs) (length ts))])]
  17925. [else (error 'apply-project "expected function not ~a" v1)])]
  17926. [else v1])]
  17927. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17928. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17929. \end{lstlisting}
  17930. \fi}
  17931. {\if\edition\pythonEd\pythonColor
  17932. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17933. class InterpLany(InterpLlambda):
  17934. def type_to_tag(self, typ):
  17935. match typ:
  17936. case FunctionType(params, rt):
  17937. return 'function'
  17938. case TupleType(fields):
  17939. return 'tuple'
  17940. case IntType():
  17941. return 'int'
  17942. case BoolType():
  17943. return 'bool'
  17944. case _:
  17945. raise Exception('type_to_tag unexpected ' + repr(typ))
  17946. def arity(self, v):
  17947. match v:
  17948. case Function(name, params, body, env):
  17949. return len(params)
  17950. case _:
  17951. raise Exception('Lany arity unexpected ' + repr(v))
  17952. \end{lstlisting}
  17953. \fi}
  17954. \end{tcolorbox}
  17955. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17956. \label{fig:interp-Lany-aux}
  17957. \end{figure}
  17958. \clearpage
  17959. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17960. \label{sec:compile-r7}
  17961. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17962. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17963. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17964. is that given any subexpression $e$ in the \LangDyn{} program, the
  17965. pass will produce an expression $e'$ in \LangAny{} that has type
  17966. \ANYTY{}. For example, the first row in
  17967. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17968. \TRUE{}, which must be injected to produce an expression of type
  17969. \ANYTY{}.
  17970. %
  17971. The compilation of addition is shown in the second row of
  17972. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17973. representative of many primitive operations: the arguments have type
  17974. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17975. be performed.
  17976. The compilation of \key{lambda} (third row of
  17977. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17978. produce type annotations: we simply use \ANYTY{}.
  17979. %
  17980. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17981. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17982. this pass has to account for some differences in behavior between
  17983. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17984. permissive than \LangAny{} regarding what kind of values can be used
  17985. in various places. For example, the condition of an \key{if} does
  17986. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17987. of the same type (in that case the result is \code{\#f}).}
  17988. \begin{figure}[btp]
  17989. \centering
  17990. \begin{tcolorbox}[colback=white]
  17991. {\if\edition\racketEd
  17992. \begin{tabular}{lll}
  17993. \begin{minipage}{0.27\textwidth}
  17994. \begin{lstlisting}
  17995. #t
  17996. \end{lstlisting}
  17997. \end{minipage}
  17998. &
  17999. $\Rightarrow$
  18000. &
  18001. \begin{minipage}{0.65\textwidth}
  18002. \begin{lstlisting}
  18003. (inject #t Boolean)
  18004. \end{lstlisting}
  18005. \end{minipage}
  18006. \\[2ex]\hline
  18007. \begin{minipage}{0.27\textwidth}
  18008. \begin{lstlisting}
  18009. (+ |$e_1$| |$e_2$|)
  18010. \end{lstlisting}
  18011. \end{minipage}
  18012. &
  18013. $\Rightarrow$
  18014. &
  18015. \begin{minipage}{0.65\textwidth}
  18016. \begin{lstlisting}
  18017. (inject
  18018. (+ (project |$e'_1$| Integer)
  18019. (project |$e'_2$| Integer))
  18020. Integer)
  18021. \end{lstlisting}
  18022. \end{minipage}
  18023. \\[2ex]\hline
  18024. \begin{minipage}{0.27\textwidth}
  18025. \begin{lstlisting}
  18026. (lambda (|$x_1 \ldots$|) |$e$|)
  18027. \end{lstlisting}
  18028. \end{minipage}
  18029. &
  18030. $\Rightarrow$
  18031. &
  18032. \begin{minipage}{0.65\textwidth}
  18033. \begin{lstlisting}
  18034. (inject
  18035. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  18036. (Any|$\ldots$|Any -> Any))
  18037. \end{lstlisting}
  18038. \end{minipage}
  18039. \\[2ex]\hline
  18040. \begin{minipage}{0.27\textwidth}
  18041. \begin{lstlisting}
  18042. (|$e_0$| |$e_1 \ldots e_n$|)
  18043. \end{lstlisting}
  18044. \end{minipage}
  18045. &
  18046. $\Rightarrow$
  18047. &
  18048. \begin{minipage}{0.65\textwidth}
  18049. \begin{lstlisting}
  18050. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  18051. \end{lstlisting}
  18052. \end{minipage}
  18053. \\[2ex]\hline
  18054. \begin{minipage}{0.27\textwidth}
  18055. \begin{lstlisting}
  18056. (vector-ref |$e_1$| |$e_2$|)
  18057. \end{lstlisting}
  18058. \end{minipage}
  18059. &
  18060. $\Rightarrow$
  18061. &
  18062. \begin{minipage}{0.65\textwidth}
  18063. \begin{lstlisting}
  18064. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  18065. \end{lstlisting}
  18066. \end{minipage}
  18067. \\[2ex]\hline
  18068. \begin{minipage}{0.27\textwidth}
  18069. \begin{lstlisting}
  18070. (if |$e_1$| |$e_2$| |$e_3$|)
  18071. \end{lstlisting}
  18072. \end{minipage}
  18073. &
  18074. $\Rightarrow$
  18075. &
  18076. \begin{minipage}{0.65\textwidth}
  18077. \begin{lstlisting}
  18078. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18079. \end{lstlisting}
  18080. \end{minipage}
  18081. \\[2ex]\hline
  18082. \begin{minipage}{0.27\textwidth}
  18083. \begin{lstlisting}
  18084. (eq? |$e_1$| |$e_2$|)
  18085. \end{lstlisting}
  18086. \end{minipage}
  18087. &
  18088. $\Rightarrow$
  18089. &
  18090. \begin{minipage}{0.65\textwidth}
  18091. \begin{lstlisting}
  18092. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18093. \end{lstlisting}
  18094. \end{minipage}
  18095. \\[2ex]\hline
  18096. \begin{minipage}{0.27\textwidth}
  18097. \begin{lstlisting}
  18098. (not |$e_1$|)
  18099. \end{lstlisting}
  18100. \end{minipage}
  18101. &
  18102. $\Rightarrow$
  18103. &
  18104. \begin{minipage}{0.65\textwidth}
  18105. \begin{lstlisting}
  18106. (if (eq? |$e'_1$| (inject #f Boolean))
  18107. (inject #t Boolean) (inject #f Boolean))
  18108. \end{lstlisting}
  18109. \end{minipage}
  18110. \end{tabular}
  18111. \fi}
  18112. {\if\edition\pythonEd\pythonColor
  18113. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  18114. \begin{minipage}{0.23\textwidth}
  18115. \begin{lstlisting}
  18116. True
  18117. \end{lstlisting}
  18118. \end{minipage}
  18119. &
  18120. $\Rightarrow$
  18121. &
  18122. \begin{minipage}{0.7\textwidth}
  18123. \begin{lstlisting}
  18124. Inject(True, BoolType())
  18125. \end{lstlisting}
  18126. \end{minipage}
  18127. \\[2ex]\hline
  18128. \begin{minipage}{0.23\textwidth}
  18129. \begin{lstlisting}
  18130. |$e_1$| + |$e_2$|
  18131. \end{lstlisting}
  18132. \end{minipage}
  18133. &
  18134. $\Rightarrow$
  18135. &
  18136. \begin{minipage}{0.7\textwidth}
  18137. \begin{lstlisting}
  18138. Inject(Project(|$e'_1$|, IntType())
  18139. + Project(|$e'_2$|, IntType()),
  18140. IntType())
  18141. \end{lstlisting}
  18142. \end{minipage}
  18143. \\[2ex]\hline
  18144. \begin{minipage}{0.23\textwidth}
  18145. \begin{lstlisting}
  18146. lambda |$x_1 \ldots$|: |$e$|
  18147. \end{lstlisting}
  18148. \end{minipage}
  18149. &
  18150. $\Rightarrow$
  18151. &
  18152. \begin{minipage}{0.7\textwidth}
  18153. \begin{lstlisting}
  18154. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  18155. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  18156. \end{lstlisting}
  18157. \end{minipage}
  18158. \\[2ex]\hline
  18159. \begin{minipage}{0.23\textwidth}
  18160. \begin{lstlisting}
  18161. |$e_0$|(|$e_1 \ldots e_n$|)
  18162. \end{lstlisting}
  18163. \end{minipage}
  18164. &
  18165. $\Rightarrow$
  18166. &
  18167. \begin{minipage}{0.7\textwidth}
  18168. \begin{lstlisting}
  18169. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18170. AnyType())), |$e'_1, \ldots, e'_n$|)
  18171. \end{lstlisting}
  18172. \end{minipage}
  18173. \\[2ex]\hline
  18174. \begin{minipage}{0.23\textwidth}
  18175. \begin{lstlisting}
  18176. |$e_1$|[|$e_2$|]
  18177. \end{lstlisting}
  18178. \end{minipage}
  18179. &
  18180. $\Rightarrow$
  18181. &
  18182. \begin{minipage}{0.7\textwidth}
  18183. \begin{lstlisting}
  18184. Call(Name('any_tuple_load'),
  18185. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18186. \end{lstlisting}
  18187. \end{minipage}
  18188. %% \begin{minipage}{0.23\textwidth}
  18189. %% \begin{lstlisting}
  18190. %% |$e_2$| if |$e_1$| else |$e_3$|
  18191. %% \end{lstlisting}
  18192. %% \end{minipage}
  18193. %% &
  18194. %% $\Rightarrow$
  18195. %% &
  18196. %% \begin{minipage}{0.7\textwidth}
  18197. %% \begin{lstlisting}
  18198. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18199. %% \end{lstlisting}
  18200. %% \end{minipage}
  18201. %% \\[2ex]\hline
  18202. %% \begin{minipage}{0.23\textwidth}
  18203. %% \begin{lstlisting}
  18204. %% (eq? |$e_1$| |$e_2$|)
  18205. %% \end{lstlisting}
  18206. %% \end{minipage}
  18207. %% &
  18208. %% $\Rightarrow$
  18209. %% &
  18210. %% \begin{minipage}{0.7\textwidth}
  18211. %% \begin{lstlisting}
  18212. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18213. %% \end{lstlisting}
  18214. %% \end{minipage}
  18215. %% \\[2ex]\hline
  18216. %% \begin{minipage}{0.23\textwidth}
  18217. %% \begin{lstlisting}
  18218. %% (not |$e_1$|)
  18219. %% \end{lstlisting}
  18220. %% \end{minipage}
  18221. %% &
  18222. %% $\Rightarrow$
  18223. %% &
  18224. %% \begin{minipage}{0.7\textwidth}
  18225. %% \begin{lstlisting}
  18226. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18227. %% (inject #t Boolean) (inject #f Boolean))
  18228. %% \end{lstlisting}
  18229. %% \end{minipage}
  18230. %% \\[2ex]\hline
  18231. \\\hline
  18232. \end{tabular}
  18233. \fi}
  18234. \end{tcolorbox}
  18235. \caption{Cast insertion.}
  18236. \label{fig:compile-r7-Lany}
  18237. \end{figure}
  18238. \section{Reveal Casts}
  18239. \label{sec:reveal-casts-Lany}
  18240. % TODO: define R'_6
  18241. In the \code{reveal\_casts} pass, we recommend compiling
  18242. \code{Project} into a conditional expression that checks whether the
  18243. value's tag matches the target type; if it does, the value is
  18244. converted to a value of the target type by removing the tag; if it
  18245. does not, the program exits.
  18246. %
  18247. {\if\edition\racketEd
  18248. %
  18249. To perform these actions we need a new primitive operation,
  18250. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18251. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18252. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18253. underlying value from a tagged value. The \code{ValueOf} form
  18254. includes the type for the underlying value that is used by the type
  18255. checker.
  18256. %
  18257. \fi}
  18258. %
  18259. {\if\edition\pythonEd\pythonColor
  18260. %
  18261. To perform these actions we need two new AST classes: \code{TagOf} and
  18262. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18263. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18264. the underlying value from a tagged value. The \code{ValueOf}
  18265. operation includes the type for the underlying value that is used by
  18266. the type checker.
  18267. %
  18268. \fi}
  18269. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18270. \code{Project} can be translated as follows:
  18271. \begin{center}
  18272. \begin{minipage}{1.0\textwidth}
  18273. {\if\edition\racketEd
  18274. \begin{lstlisting}
  18275. (Project |$e$| |$\FType$|)
  18276. |$\Rightarrow$|
  18277. (Let |$\itm{tmp}$| |$e'$|
  18278. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18279. (Int |$\itm{tagof}(\FType)$|)))
  18280. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18281. (Exit)))
  18282. \end{lstlisting}
  18283. \fi}
  18284. {\if\edition\pythonEd\pythonColor
  18285. \begin{lstlisting}
  18286. Project(|$e$|, |$\FType$|)
  18287. |$\Rightarrow$|
  18288. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18289. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18290. [Constant(|$\itm{tagof}(\FType)$|)]),
  18291. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18292. Call(Name('exit'), [])))
  18293. \end{lstlisting}
  18294. \fi}
  18295. \end{minipage}
  18296. \end{center}
  18297. If the target type of the projection is a tuple or function type, then
  18298. there is a bit more work to do. For tuples, check that the length of
  18299. the tuple type matches the length of the tuple. For functions, check
  18300. that the number of parameters in the function type matches the
  18301. function's arity.
  18302. Regarding \code{Inject}, we recommend compiling it to a slightly
  18303. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18304. takes a tag instead of a type.
  18305. \begin{center}
  18306. \begin{minipage}{1.0\textwidth}
  18307. {\if\edition\racketEd
  18308. \begin{lstlisting}
  18309. (Inject |$e$| |$\FType$|)
  18310. |$\Rightarrow$|
  18311. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18312. \end{lstlisting}
  18313. \fi}
  18314. {\if\edition\pythonEd\pythonColor
  18315. \begin{lstlisting}
  18316. Inject(|$e$|, |$\FType$|)
  18317. |$\Rightarrow$|
  18318. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18319. \end{lstlisting}
  18320. \fi}
  18321. \end{minipage}
  18322. \end{center}
  18323. {\if\edition\pythonEd\pythonColor
  18324. %
  18325. The introduction of \code{make\_any} makes it difficult to use
  18326. bidirectional type checking because we no longer have an expected type
  18327. to use for type checking the expression $e'$. Thus, we run into
  18328. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18329. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18330. annotated lambda) that contains its return type and the types of its
  18331. parameters.
  18332. %
  18333. \fi}
  18334. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18335. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18336. translation of \code{Project}.}
  18337. {\if\edition\racketEd
  18338. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18339. combine the projection action with the vector operation. Also, the
  18340. read and write operations allow arbitrary expressions for the index, so
  18341. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18342. cannot guarantee that the index is within bounds. Thus, we insert code
  18343. to perform bounds checking at runtime. The translation for
  18344. \code{any-vector-ref} is as follows, and the other two operations are
  18345. translated in a similar way:
  18346. \begin{center}
  18347. \begin{minipage}{0.95\textwidth}
  18348. \begin{lstlisting}
  18349. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18350. |$\Rightarrow$|
  18351. (Let |$v$| |$e'_1$|
  18352. (Let |$i$| |$e'_2$|
  18353. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18354. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18355. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18356. (Exit))
  18357. (Exit))))
  18358. \end{lstlisting}
  18359. \end{minipage}
  18360. \end{center}
  18361. \fi}
  18362. %
  18363. {\if\edition\pythonEd\pythonColor
  18364. %
  18365. The \code{any\_tuple\_load} operation combines the projection action
  18366. with the load operation. Also, the load operation allows arbitrary
  18367. expressions for the index, so the type checker for \LangAny{}
  18368. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18369. within bounds. Thus, we insert code to perform bounds checking at
  18370. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18371. \begin{lstlisting}
  18372. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18373. |$\Rightarrow$|
  18374. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18375. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18376. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18377. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18378. Call(Name('exit'), [])),
  18379. Call(Name('exit'), [])))
  18380. \end{lstlisting}
  18381. \fi}
  18382. {\if\edition\pythonEd\pythonColor
  18383. \section{Assignment Conversion}
  18384. \label{sec:convert-assignments-Lany}
  18385. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18386. \code{AnnLambda} AST classes.
  18387. \section{Closure Conversion}
  18388. \label{sec:closure-conversion-Lany}
  18389. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18390. \code{AnnLambda} AST classes.
  18391. \fi}
  18392. \section{Remove Complex Operands}
  18393. \label{sec:rco-Lany}
  18394. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18395. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18396. %
  18397. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18398. complex expressions. Their subexpressions must be atomic.}
  18399. \section{Explicate Control and \LangCAny{}}
  18400. \label{sec:explicate-Lany}
  18401. The output of \code{explicate\_control} is the \LangCAny{} language,
  18402. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18403. %
  18404. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18405. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18406. note that the index argument of \code{vector-ref} and
  18407. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18408. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18409. %
  18410. \python{Update the auxiliary functions \code{explicate\_tail},
  18411. \code{explicate\_effect}, and \code{explicate\_pred} as
  18412. appropriate to handle the new expressions in \LangCAny{}. }
  18413. \newcommand{\CanyASTPython}{
  18414. \begin{array}{lcl}
  18415. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18416. &\MID& \key{TagOf}\LP \Atm \RP
  18417. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18418. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18419. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18420. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18421. \end{array}
  18422. }
  18423. \newcommand{\CanyASTRacket}{
  18424. \begin{array}{lcl}
  18425. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18426. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18427. &\MID& \VALUEOF{\Atm}{\FType} \\
  18428. \Tail &::= & \LP\key{Exit}\RP
  18429. \end{array}
  18430. }
  18431. \begin{figure}[tp]
  18432. \begin{tcolorbox}[colback=white]
  18433. \small
  18434. {\if\edition\racketEd
  18435. \[
  18436. \begin{array}{l}
  18437. \gray{\CvarASTRacket} \\ \hline
  18438. \gray{\CifASTRacket} \\ \hline
  18439. \gray{\CloopASTRacket} \\ \hline
  18440. \gray{\CtupASTRacket} \\ \hline
  18441. \gray{\CfunASTRacket} \\ \hline
  18442. \gray{\ClambdaASTRacket} \\ \hline
  18443. \CanyASTRacket \\
  18444. \begin{array}{lcl}
  18445. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18446. \end{array}
  18447. \end{array}
  18448. \]
  18449. \fi}
  18450. {\if\edition\pythonEd\pythonColor
  18451. \[
  18452. \begin{array}{l}
  18453. \gray{\CifASTPython} \\ \hline
  18454. \gray{\CtupASTPython} \\ \hline
  18455. \gray{\CfunASTPython} \\ \hline
  18456. \gray{\ClambdaASTPython} \\ \hline
  18457. \CanyASTPython \\
  18458. \begin{array}{lcl}
  18459. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18460. \end{array}
  18461. \end{array}
  18462. \]
  18463. \fi}
  18464. \end{tcolorbox}
  18465. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18466. \label{fig:c5-syntax}
  18467. \index{subject}{Cany@\LangCAny{} abstract syntax}
  18468. \end{figure}
  18469. \section{Select Instructions}
  18470. \label{sec:select-Lany}
  18471. \index{subject}{select instructions}
  18472. In the \code{select\_instructions} pass, we translate the primitive
  18473. operations on the \ANYTY{} type to x86 instructions that manipulate
  18474. the three tag bits of the tagged value. In the following descriptions,
  18475. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18476. of translating $e$ into an x86 argument:
  18477. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18478. We recommend compiling the
  18479. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18480. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18481. shifts the destination to the left by the number of bits specified by its
  18482. source argument (in this case three, the length of the tag), and it
  18483. preserves the sign of the integer. We use the \key{orq} instruction to
  18484. combine the tag and the value to form the tagged value.
  18485. {\if\edition\racketEd
  18486. \begin{lstlisting}
  18487. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18488. |$\Rightarrow$|
  18489. movq |$e'$|, |\itm{lhs'}|
  18490. salq $3, |\itm{lhs'}|
  18491. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18492. \end{lstlisting}
  18493. \fi}
  18494. %
  18495. {\if\edition\pythonEd\pythonColor
  18496. \begin{lstlisting}
  18497. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18498. |$\Rightarrow$|
  18499. movq |$e'$|, |\itm{lhs'}|
  18500. salq $3, |\itm{lhs'}|
  18501. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18502. \end{lstlisting}
  18503. \fi}
  18504. %
  18505. The instruction selection\index{subject}{instruction selection} for
  18506. tuples and procedures is different because there is no need to shift
  18507. them to the left. The rightmost 3 bits are already zeros, so we simply
  18508. combine the value and the tag using \key{orq}. \\
  18509. %
  18510. {\if\edition\racketEd
  18511. \begin{center}
  18512. \begin{minipage}{\textwidth}
  18513. \begin{lstlisting}
  18514. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18515. |$\Rightarrow$|
  18516. movq |$e'$|, |\itm{lhs'}|
  18517. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18518. \end{lstlisting}
  18519. \end{minipage}
  18520. \end{center}
  18521. \fi}
  18522. %
  18523. {\if\edition\pythonEd\pythonColor
  18524. \begin{lstlisting}
  18525. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18526. |$\Rightarrow$|
  18527. movq |$e'$|, |\itm{lhs'}|
  18528. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18529. \end{lstlisting}
  18530. \fi}
  18531. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18532. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18533. operation extracts the type tag from a value of type \ANYTY{}. The
  18534. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18535. bitwise-and of the value with $111$ ($7$ decimal).
  18536. %
  18537. {\if\edition\racketEd
  18538. \begin{lstlisting}
  18539. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18540. |$\Rightarrow$|
  18541. movq |$e'$|, |\itm{lhs'}|
  18542. andq $7, |\itm{lhs'}|
  18543. \end{lstlisting}
  18544. \fi}
  18545. %
  18546. {\if\edition\pythonEd\pythonColor
  18547. \begin{lstlisting}
  18548. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18549. |$\Rightarrow$|
  18550. movq |$e'$|, |\itm{lhs'}|
  18551. andq $7, |\itm{lhs'}|
  18552. \end{lstlisting}
  18553. \fi}
  18554. \paragraph{\code{ValueOf}}
  18555. The instructions for \key{ValueOf} also differ, depending on whether
  18556. the type $T$ is a pointer (tuple or function) or not (integer or
  18557. Boolean). The following shows the instruction
  18558. selection for integers and
  18559. Booleans, in which we produce an untagged value by shifting it to the
  18560. right by 3 bits:
  18561. %
  18562. {\if\edition\racketEd
  18563. \begin{lstlisting}
  18564. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18565. |$\Rightarrow$|
  18566. movq |$e'$|, |\itm{lhs'}|
  18567. sarq $3, |\itm{lhs'}|
  18568. \end{lstlisting}
  18569. \fi}
  18570. %
  18571. {\if\edition\pythonEd\pythonColor
  18572. \begin{lstlisting}
  18573. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18574. |$\Rightarrow$|
  18575. movq |$e'$|, |\itm{lhs'}|
  18576. sarq $3, |\itm{lhs'}|
  18577. \end{lstlisting}
  18578. \fi}
  18579. %
  18580. In the case for tuples and procedures, we zero out the rightmost 3
  18581. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18582. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18583. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18584. Finally, we apply \code{andq} with the tagged value to get the desired
  18585. result.
  18586. %
  18587. {\if\edition\racketEd
  18588. \begin{lstlisting}
  18589. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18590. |$\Rightarrow$|
  18591. movq $|$-8$|, |\itm{lhs'}|
  18592. andq |$e'$|, |\itm{lhs'}|
  18593. \end{lstlisting}
  18594. \fi}
  18595. %
  18596. {\if\edition\pythonEd\pythonColor
  18597. \begin{lstlisting}
  18598. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18599. |$\Rightarrow$|
  18600. movq $|$-8$|, |\itm{lhs'}|
  18601. andq |$e'$|, |\itm{lhs'}|
  18602. \end{lstlisting}
  18603. \fi}
  18604. %% \paragraph{Type Predicates} We leave it to the reader to
  18605. %% devise a sequence of instructions to implement the type predicates
  18606. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18607. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18608. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18609. operation combines the effect of \code{ValueOf} with accessing the
  18610. length of a tuple from the tag stored at the zero index of the tuple.
  18611. {\if\edition\racketEd
  18612. \begin{lstlisting}
  18613. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18614. |$\Longrightarrow$|
  18615. movq $|$-8$|, %r11
  18616. andq |$e_1'$|, %r11
  18617. movq 0(%r11), %r11
  18618. andq $126, %r11
  18619. sarq $1, %r11
  18620. movq %r11, |$\itm{lhs'}$|
  18621. \end{lstlisting}
  18622. \fi}
  18623. {\if\edition\pythonEd\pythonColor
  18624. \begin{lstlisting}
  18625. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18626. |$\Longrightarrow$|
  18627. movq $|$-8$|, %r11
  18628. andq |$e_1'$|, %r11
  18629. movq 0(%r11), %r11
  18630. andq $126, %r11
  18631. sarq $1, %r11
  18632. movq %r11, |$\itm{lhs'}$|
  18633. \end{lstlisting}
  18634. \fi}
  18635. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18636. This operation combines the effect of \code{ValueOf} with reading an
  18637. element of the tuple (see
  18638. section~\ref{sec:select-instructions-gc}). However, the index may be
  18639. an arbitrary atom, so instead of computing the offset at compile time,
  18640. we must generate instructions to compute the offset at runtime as
  18641. follows. Note the use of the new instruction \code{imulq}.
  18642. \begin{center}
  18643. \begin{minipage}{0.96\textwidth}
  18644. {\if\edition\racketEd
  18645. \begin{lstlisting}
  18646. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18647. |$\Longrightarrow$|
  18648. movq |$\neg 111$|, %r11
  18649. andq |$e_1'$|, %r11
  18650. movq |$e_2'$|, %rax
  18651. addq $1, %rax
  18652. imulq $8, %rax
  18653. addq %rax, %r11
  18654. movq 0(%r11) |$\itm{lhs'}$|
  18655. \end{lstlisting}
  18656. \fi}
  18657. %
  18658. {\if\edition\pythonEd\pythonColor
  18659. \begin{lstlisting}
  18660. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18661. |$\Longrightarrow$|
  18662. movq $|$-8$|, %r11
  18663. andq |$e_1'$|, %r11
  18664. movq |$e_2'$|, %rax
  18665. addq $1, %rax
  18666. imulq $8, %rax
  18667. addq %rax, %r11
  18668. movq 0(%r11) |$\itm{lhs'}$|
  18669. \end{lstlisting}
  18670. \fi}
  18671. \end{minipage}
  18672. \end{center}
  18673. % $ pacify font lock
  18674. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18675. %% The code generation for
  18676. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18677. %% analogous to the above translation for reading from a tuple.
  18678. \section{Register Allocation for \LangAny{} }
  18679. \label{sec:register-allocation-Lany}
  18680. \index{subject}{register allocation}
  18681. There is an interesting interaction between tagged values and garbage
  18682. collection that has an impact on register allocation. A variable of
  18683. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18684. that needs to be inspected and copied during garbage collection. Thus,
  18685. we need to treat variables of type \ANYTY{} in a similar way to
  18686. variables of tuple type for purposes of register allocation,
  18687. with particular attention to the following:
  18688. \begin{itemize}
  18689. \item If a variable of type \ANYTY{} is live during a function call,
  18690. then it must be spilled. This can be accomplished by changing
  18691. \code{build\_interference} to mark all variables of type \ANYTY{}
  18692. that are live after a \code{callq} to be interfering with all the
  18693. registers.
  18694. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18695. the root stack instead of the normal procedure call stack.
  18696. \end{itemize}
  18697. Another concern regarding the root stack is that the garbage collector
  18698. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18699. tagged value that points to a tuple, and (3) a tagged value that is
  18700. not a tuple. We enable this differentiation by choosing not to use the
  18701. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18702. reserved for identifying plain old pointers to tuples. That way, if
  18703. one of the first three bits is set, then we have a tagged value and
  18704. inspecting the tag can differentiate between tuples ($010$) and the
  18705. other kinds of values.
  18706. %% \begin{exercise}\normalfont
  18707. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18708. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18709. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18710. %% compiler on these new programs and all of your previously created test
  18711. %% programs.
  18712. %% \end{exercise}
  18713. \begin{exercise}\normalfont\normalsize
  18714. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18715. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18716. by removing type annotations. Add five more test programs that
  18717. specifically rely on the language being dynamically typed. That is,
  18718. they should not be legal programs in a statically typed language, but
  18719. nevertheless they should be valid \LangDyn{} programs that run to
  18720. completion without error.
  18721. \end{exercise}
  18722. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18723. for the compilation of \LangDyn{}.
  18724. \begin{figure}[bthp]
  18725. \begin{tcolorbox}[colback=white]
  18726. {\if\edition\racketEd
  18727. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18728. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18729. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18730. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18731. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18732. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18733. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18734. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18735. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18736. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18737. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18738. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18739. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18740. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18741. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18742. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18743. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18744. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18745. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18746. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18747. \path[->,bend left=15] (Lfun) edge [above] node
  18748. {\ttfamily\footnotesize shrink} (Lfun-2);
  18749. \path[->,bend left=15] (Lfun-2) edge [above] node
  18750. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18751. \path[->,bend left=15] (Lfun-3) edge [above] node
  18752. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18753. \path[->,bend left=15] (Lfun-4) edge [left] node
  18754. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18755. \path[->,bend left=15] (Lfun-5) edge [below] node
  18756. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18757. \path[->,bend left=15] (Lfun-6) edge [below] node
  18758. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18759. \path[->,bend right=15] (Lfun-7) edge [above] node
  18760. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18761. \path[->,bend right=15] (F1-2) edge [right] node
  18762. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18763. \path[->,bend right=15] (F1-3) edge [below] node
  18764. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18765. \path[->,bend right=15] (F1-4) edge [below] node
  18766. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18767. \path[->,bend left=15] (F1-5) edge [above] node
  18768. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18769. \path[->,bend left=10] (F1-6) edge [below] node
  18770. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18771. \path[->,bend left=15] (C3-2) edge [right] node
  18772. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18773. \path[->,bend right=15] (x86-2) edge [right] node
  18774. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18775. \path[->,bend right=15] (x86-2-1) edge [below] node
  18776. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18777. \path[->,bend right=15] (x86-2-2) edge [right] node
  18778. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18779. \path[->,bend left=15] (x86-3) edge [above] node
  18780. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18781. \path[->,bend left=15] (x86-4) edge [right] node
  18782. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18783. \end{tikzpicture}
  18784. \fi}
  18785. {\if\edition\pythonEd\pythonColor
  18786. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18787. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18788. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18789. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18790. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18791. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18792. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18793. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18794. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18795. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18796. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18797. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18798. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18799. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18800. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18801. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18802. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18803. \path[->,bend left=15] (Lfun) edge [above] node
  18804. {\ttfamily\footnotesize shrink} (Lfun-2);
  18805. \path[->,bend left=15] (Lfun-2) edge [above] node
  18806. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18807. \path[->,bend left=15] (Lfun-3) edge [above] node
  18808. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18809. \path[->,bend left=15] (Lfun-4) edge [left] node
  18810. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18811. \path[->,bend left=15] (Lfun-5) edge [below] node
  18812. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18813. \path[->,bend right=15] (Lfun-6) edge [above] node
  18814. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18815. \path[->,bend right=15] (Lfun-7) edge [above] node
  18816. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18817. \path[->,bend right=15] (F1-2) edge [right] node
  18818. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18819. \path[->,bend right=15] (F1-3) edge [below] node
  18820. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18821. \path[->,bend left=15] (F1-5) edge [above] node
  18822. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18823. \path[->,bend left=10] (F1-6) edge [below] node
  18824. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18825. \path[->,bend right=15] (C3-2) edge [right] node
  18826. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18827. \path[->,bend right=15] (x86-2) edge [below] node
  18828. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18829. \path[->,bend right=15] (x86-3) edge [below] node
  18830. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18831. \path[->,bend left=15] (x86-4) edge [above] node
  18832. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18833. \end{tikzpicture}
  18834. \fi}
  18835. \end{tcolorbox}
  18836. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18837. \label{fig:Ldyn-passes}
  18838. \end{figure}
  18839. % Further Reading
  18840. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18841. %% {\if\edition\pythonEd\pythonColor
  18842. %% \chapter{Objects}
  18843. %% \label{ch:Lobject}
  18844. %% \index{subject}{objects}
  18845. %% \index{subject}{classes}
  18846. %% \setcounter{footnote}{0}
  18847. %% \fi}
  18848. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18849. \chapter{Gradual Typing}
  18850. \label{ch:Lgrad}
  18851. \index{subject}{gradual typing}
  18852. \setcounter{footnote}{0}
  18853. This chapter studies the language \LangGrad{}, in which the programmer
  18854. can choose between static and dynamic type checking in different parts
  18855. of a program, thereby mixing the statically typed \LangLam{} language
  18856. with the dynamically typed \LangDyn{}. There are several approaches to
  18857. mixing static and dynamic typing, including multilanguage
  18858. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18859. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18860. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18861. programmer controls the amount of static versus dynamic checking by
  18862. adding or removing type annotations on parameters and
  18863. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18864. The definition of the concrete syntax of \LangGrad{} is shown in
  18865. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18866. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18867. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18868. annotations are optional, which is specified in the grammar using the
  18869. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18870. annotations are not optional, but we use the \CANYTY{} type when a type
  18871. annotation is absent.
  18872. %
  18873. Both the type checker and the interpreter for \LangGrad{} require some
  18874. interesting changes to enable gradual typing, which we discuss in the
  18875. next two sections.
  18876. \newcommand{\LgradGrammarRacket}{
  18877. \begin{array}{lcl}
  18878. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18879. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18880. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18881. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18882. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18883. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18884. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18885. \end{array}
  18886. }
  18887. \newcommand{\LgradASTRacket}{
  18888. \begin{array}{lcl}
  18889. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18890. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18891. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18892. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18893. \itm{op} &::=& \code{procedure-arity} \\
  18894. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18895. \end{array}
  18896. }
  18897. \newcommand{\LgradGrammarPython}{
  18898. \begin{array}{lcl}
  18899. \Type &::=& \key{Any}
  18900. \MID \key{int}
  18901. \MID \key{bool}
  18902. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18903. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18904. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18905. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18906. \MID \CARITY{\Exp} \\
  18907. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18908. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18909. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18910. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18911. \end{array}
  18912. }
  18913. \newcommand{\LgradASTPython}{
  18914. \begin{array}{lcl}
  18915. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18916. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18917. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18918. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18919. &\MID& \ARITY{\Exp} \\
  18920. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18921. \MID \RETURN{\Exp} \\
  18922. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18923. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18924. \end{array}
  18925. }
  18926. \begin{figure}[tbp]
  18927. \centering
  18928. \begin{tcolorbox}[colback=white]
  18929. \vspace{-5pt}
  18930. \small
  18931. {\if\edition\racketEd
  18932. \[
  18933. \begin{array}{l}
  18934. \gray{\LintGrammarRacket{}} \\ \hline
  18935. \gray{\LvarGrammarRacket{}} \\ \hline
  18936. \gray{\LifGrammarRacket{}} \\ \hline
  18937. \gray{\LwhileGrammarRacket} \\ \hline
  18938. \gray{\LtupGrammarRacket} \\ \hline
  18939. \LgradGrammarRacket \\
  18940. \begin{array}{lcl}
  18941. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18942. \end{array}
  18943. \end{array}
  18944. \]
  18945. \fi}
  18946. {\if\edition\pythonEd\pythonColor
  18947. \[
  18948. \begin{array}{l}
  18949. \gray{\LintGrammarPython{}} \\ \hline
  18950. \gray{\LvarGrammarPython{}} \\ \hline
  18951. \gray{\LifGrammarPython{}} \\ \hline
  18952. \gray{\LwhileGrammarPython} \\ \hline
  18953. \gray{\LtupGrammarPython} \\ \hline
  18954. \LgradGrammarPython \\
  18955. \begin{array}{lcl}
  18956. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18957. \end{array}
  18958. \end{array}
  18959. \]
  18960. \fi}
  18961. \end{tcolorbox}
  18962. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18963. \label{fig:Lgrad-concrete-syntax}
  18964. \index{subject}{L?@\LangGrad{} concrete syntax}
  18965. \end{figure}
  18966. \begin{figure}[tbp]
  18967. \centering
  18968. \begin{tcolorbox}[colback=white]
  18969. \small
  18970. {\if\edition\racketEd
  18971. \[
  18972. \begin{array}{l}
  18973. \gray{\LintOpAST} \\ \hline
  18974. \gray{\LvarASTRacket{}} \\ \hline
  18975. \gray{\LifASTRacket{}} \\ \hline
  18976. \gray{\LwhileASTRacket{}} \\ \hline
  18977. \gray{\LtupASTRacket{}} \\ \hline
  18978. \LgradASTRacket \\
  18979. \begin{array}{lcl}
  18980. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18981. \end{array}
  18982. \end{array}
  18983. \]
  18984. \fi}
  18985. {\if\edition\pythonEd\pythonColor
  18986. \[
  18987. \begin{array}{l}
  18988. \gray{\LintASTPython{}} \\ \hline
  18989. \gray{\LvarASTPython{}} \\ \hline
  18990. \gray{\LifASTPython{}} \\ \hline
  18991. \gray{\LwhileASTPython} \\ \hline
  18992. \gray{\LtupASTPython} \\ \hline
  18993. \LgradASTPython \\
  18994. \begin{array}{lcl}
  18995. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18996. \end{array}
  18997. \end{array}
  18998. \]
  18999. \fi}
  19000. \end{tcolorbox}
  19001. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  19002. \label{fig:Lgrad-syntax}
  19003. \index{subject}{L?@\LangGrad{} abstract syntax}
  19004. \end{figure}
  19005. % TODO: more road map -Jeremy
  19006. %\clearpage
  19007. \section{Type Checking \LangGrad{}}
  19008. \label{sec:gradual-type-check}
  19009. We begin by discussing the type checking of a partially typed variant
  19010. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  19011. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  19012. statically typed, so there is nothing special happening there with
  19013. respect to type checking. On the other hand, the \code{inc} function
  19014. does not have type annotations, so the type checker assigns the type
  19015. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  19016. \code{+} operator inside \code{inc}. It expects both arguments to have
  19017. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  19018. a gradually typed language, such differences are allowed so long as
  19019. the types are \emph{consistent}; that is, they are equal except in
  19020. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  19021. is consistent with every other type. Figure~\ref{fig:consistent}
  19022. shows the definition of the
  19023. \racket{\code{consistent?}}\python{\code{consistent}} method.
  19024. %
  19025. So the type checker allows the \code{+} operator to be applied
  19026. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  19027. %
  19028. Next consider the call to the \code{map} function shown in
  19029. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  19030. tuple. The \code{inc} function has type
  19031. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  19032. but parameter \code{f} of \code{map} has type
  19033. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19034. The type checker for \LangGrad{} accepts this call because the two types are
  19035. consistent.
  19036. \begin{figure}[hbtp]
  19037. % gradual_test_9.rkt
  19038. \begin{tcolorbox}[colback=white]
  19039. {\if\edition\racketEd
  19040. \begin{lstlisting}
  19041. (define (map [f : (Integer -> Integer)]
  19042. [v : (Vector Integer Integer)])
  19043. : (Vector Integer Integer)
  19044. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19045. (define (inc x) (+ x 1))
  19046. (vector-ref (map inc (vector 0 41)) 1)
  19047. \end{lstlisting}
  19048. \fi}
  19049. {\if\edition\pythonEd\pythonColor
  19050. \begin{lstlisting}
  19051. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19052. return f(v[0]), f(v[1])
  19053. def inc(x):
  19054. return x + 1
  19055. t = map(inc, (0, 41))
  19056. print(t[1])
  19057. \end{lstlisting}
  19058. \fi}
  19059. \end{tcolorbox}
  19060. \caption{A partially typed version of the \code{map} example.}
  19061. \label{fig:gradual-map}
  19062. \end{figure}
  19063. \begin{figure}[tbp]
  19064. \begin{tcolorbox}[colback=white]
  19065. {\if\edition\racketEd
  19066. \begin{lstlisting}
  19067. (define/public (consistent? t1 t2)
  19068. (match* (t1 t2)
  19069. [('Integer 'Integer) #t]
  19070. [('Boolean 'Boolean) #t]
  19071. [('Void 'Void) #t]
  19072. [('Any t2) #t]
  19073. [(t1 'Any) #t]
  19074. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19075. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  19076. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19077. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  19078. (consistent? rt1 rt2))]
  19079. [(other wise) #f]))
  19080. \end{lstlisting}
  19081. \fi}
  19082. {\if\edition\pythonEd\pythonColor
  19083. \begin{lstlisting}
  19084. def consistent(self, t1, t2):
  19085. match (t1, t2):
  19086. case (AnyType(), _):
  19087. return True
  19088. case (_, AnyType()):
  19089. return True
  19090. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19091. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  19092. case (TupleType(ts1), TupleType(ts2)):
  19093. return all(map(self.consistent, ts1, ts2))
  19094. case (_, _):
  19095. return t1 == t2
  19096. \end{lstlisting}
  19097. \fi}
  19098. \vspace{-5pt}
  19099. \end{tcolorbox}
  19100. \caption{The consistency method on types.}
  19101. \label{fig:consistent}
  19102. \end{figure}
  19103. It is also helpful to consider how gradual typing handles programs with an
  19104. error, such as applying \code{map} to a function that sometimes
  19105. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  19106. type checker for \LangGrad{} accepts this program because the type of
  19107. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  19108. \code{map}; that is,
  19109. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  19110. is consistent with
  19111. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19112. One might say that a gradual type checker is optimistic in that it
  19113. accepts programs that might execute without a runtime type error.
  19114. %
  19115. The definition of the type checker for \LangGrad{} is shown in
  19116. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  19117. and \ref{fig:type-check-Lgradual-3}.
  19118. %% \begin{figure}[tp]
  19119. %% \centering
  19120. %% \fbox{
  19121. %% \begin{minipage}{0.96\textwidth}
  19122. %% \small
  19123. %% \[
  19124. %% \begin{array}{lcl}
  19125. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  19126. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  19127. %% \end{array}
  19128. %% \]
  19129. %% \end{minipage}
  19130. %% }
  19131. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  19132. %% \label{fig:Lgrad-prime-syntax}
  19133. %% \end{figure}
  19134. \begin{figure}[tbp]
  19135. \begin{tcolorbox}[colback=white]
  19136. {\if\edition\racketEd
  19137. \begin{lstlisting}
  19138. (define (map [f : (Integer -> Integer)]
  19139. [v : (Vector Integer Integer)])
  19140. : (Vector Integer Integer)
  19141. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19142. (define (inc x) (+ x 1))
  19143. (define (true) #t)
  19144. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  19145. (vector-ref (map maybe_inc (vector 0 41)) 0)
  19146. \end{lstlisting}
  19147. \fi}
  19148. {\if\edition\pythonEd\pythonColor
  19149. \begin{lstlisting}
  19150. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19151. return f(v[0]), f(v[1])
  19152. def inc(x):
  19153. return x + 1
  19154. def true():
  19155. return True
  19156. def maybe_inc(x):
  19157. return inc(x) if input_int() == 0 else true()
  19158. t = map(maybe_inc, (0, 41))
  19159. print(t[1])
  19160. \end{lstlisting}
  19161. \fi}
  19162. \vspace{-5pt}
  19163. \end{tcolorbox}
  19164. \caption{A variant of the \code{map} example with an error.}
  19165. \label{fig:map-maybe_inc}
  19166. \end{figure}
  19167. Running this program with input \code{1} triggers an
  19168. error when the \code{maybe\_inc} function returns
  19169. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  19170. performs checking at runtime to ensure the integrity of the static
  19171. types, such as the
  19172. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19173. annotation on
  19174. parameter \code{f} of \code{map}.
  19175. Here we give a preview of how the runtime checking is accomplished;
  19176. the following sections provide the details.
  19177. The runtime checking is carried out by a new \code{Cast} AST node that
  19178. is generated in a new pass named \code{cast\_insert}. The output of
  19179. \code{cast\_insert} is a program in the \LangCast{} language, which
  19180. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19181. %
  19182. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19183. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19184. inserted every time the type checker encounters two types that are
  19185. consistent but not equal. In the \code{inc} function, \code{x} is
  19186. cast to \INTTY{} and the result of the \code{+} is cast to
  19187. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19188. is cast from
  19189. \racket{\code{(Any -> Any)}}
  19190. \python{\code{Callable[[Any], Any]}}
  19191. to
  19192. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19193. %
  19194. In the next section we see how to interpret the \code{Cast} node.
  19195. \begin{figure}[btp]
  19196. \begin{tcolorbox}[colback=white]
  19197. {\if\edition\racketEd
  19198. \begin{lstlisting}
  19199. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19200. : (Vector Integer Integer)
  19201. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19202. (define (inc [x : Any]) : Any
  19203. (cast (+ (cast x Any Integer) 1) Integer Any))
  19204. (define (true) : Any (cast #t Boolean Any))
  19205. (define (maybe_inc [x : Any]) : Any
  19206. (if (eq? 0 (read)) (inc x) (true)))
  19207. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19208. (vector 0 41)) 0)
  19209. \end{lstlisting}
  19210. \fi}
  19211. {\if\edition\pythonEd\pythonColor
  19212. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19213. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19214. return f(v[0]), f(v[1])
  19215. def inc(x : Any) -> Any:
  19216. return Cast(Cast(x, Any, int) + 1, int, Any)
  19217. def true() -> Any:
  19218. return Cast(True, bool, Any)
  19219. def maybe_inc(x : Any) -> Any:
  19220. return inc(x) if input_int() == 0 else true()
  19221. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19222. (0, 41))
  19223. print(t[1])
  19224. \end{lstlisting}
  19225. \fi}
  19226. \vspace{-5pt}
  19227. \end{tcolorbox}
  19228. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19229. and \code{maybe\_inc} example.}
  19230. \label{fig:map-cast}
  19231. \end{figure}
  19232. {\if\edition\pythonEd\pythonColor
  19233. \begin{figure}[tbp]
  19234. \begin{tcolorbox}[colback=white]
  19235. \begin{lstlisting}
  19236. class TypeCheckLgrad(TypeCheckLlambda):
  19237. def type_check_exp(self, e, env) -> Type:
  19238. match e:
  19239. case Name(id):
  19240. return env[id]
  19241. case Constant(value) if isinstance(value, bool):
  19242. return BoolType()
  19243. case Constant(value) if isinstance(value, int):
  19244. return IntType()
  19245. case Call(Name('input_int'), []):
  19246. return IntType()
  19247. case BinOp(left, op, right):
  19248. left_type = self.type_check_exp(left, env)
  19249. self.check_consistent(left_type, IntType(), left)
  19250. right_type = self.type_check_exp(right, env)
  19251. self.check_consistent(right_type, IntType(), right)
  19252. return IntType()
  19253. case IfExp(test, body, orelse):
  19254. test_t = self.type_check_exp(test, env)
  19255. self.check_consistent(test_t, BoolType(), test)
  19256. body_t = self.type_check_exp(body, env)
  19257. orelse_t = self.type_check_exp(orelse, env)
  19258. self.check_consistent(body_t, orelse_t, e)
  19259. return self.join_types(body_t, orelse_t)
  19260. case Call(func, args):
  19261. func_t = self.type_check_exp(func, env)
  19262. args_t = [self.type_check_exp(arg, env) for arg in args]
  19263. match func_t:
  19264. case FunctionType(params_t, return_t) \
  19265. if len(params_t) == len(args_t):
  19266. for (arg_t, param_t) in zip(args_t, params_t):
  19267. self.check_consistent(param_t, arg_t, e)
  19268. return return_t
  19269. case AnyType():
  19270. return AnyType()
  19271. case _:
  19272. raise Exception('type_check_exp: in call, unexpected '
  19273. + repr(func_t))
  19274. ...
  19275. case _:
  19276. raise Exception('type_check_exp: unexpected ' + repr(e))
  19277. \end{lstlisting}
  19278. \end{tcolorbox}
  19279. \caption{Type checking expressions in the \LangGrad{} language.}
  19280. \label{fig:type-check-Lgradual-1}
  19281. \end{figure}
  19282. \begin{figure}[tbp]
  19283. \begin{tcolorbox}[colback=white]
  19284. \begin{lstlisting}
  19285. def check_exp(self, e, expected_ty, env):
  19286. match e:
  19287. case Lambda(params, body):
  19288. match expected_ty:
  19289. case FunctionType(params_t, return_t):
  19290. new_env = env.copy().update(zip(params, params_t))
  19291. e.has_type = expected_ty
  19292. body_ty = self.type_check_exp(body, new_env)
  19293. self.check_consistent(body_ty, return_t)
  19294. case AnyType():
  19295. new_env = env.copy().update((p, AnyType()) for p in params)
  19296. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19297. body_ty = self.type_check_exp(body, new_env)
  19298. case _:
  19299. raise Exception('lambda is not of type ' + str(expected_ty))
  19300. case _:
  19301. e_ty = self.type_check_exp(e, env)
  19302. self.check_consistent(e_ty, expected_ty, e)
  19303. \end{lstlisting}
  19304. \end{tcolorbox}
  19305. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19306. \label{fig:type-check-Lgradual-2}
  19307. \end{figure}
  19308. \begin{figure}[tbp]
  19309. \begin{tcolorbox}[colback=white]
  19310. \begin{lstlisting}
  19311. def type_check_stmt(self, s, env, return_type):
  19312. match s:
  19313. case Assign([Name(id)], value):
  19314. value_ty = self.type_check_exp(value, env)
  19315. if id in env:
  19316. self.check_consistent(env[id], value_ty, value)
  19317. else:
  19318. env[id] = value_ty
  19319. ...
  19320. case _:
  19321. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19322. def type_check_stmts(self, ss, env, return_type):
  19323. for s in ss:
  19324. self.type_check_stmt(s, env, return_type)
  19325. \end{lstlisting}
  19326. \end{tcolorbox}
  19327. \caption{Type checking statements in the \LangGrad{} language.}
  19328. \label{fig:type-check-Lgradual-3}
  19329. \end{figure}
  19330. \clearpage
  19331. \begin{figure}[tbp]
  19332. \begin{tcolorbox}[colback=white]
  19333. \begin{lstlisting}
  19334. def join_types(self, t1, t2):
  19335. match (t1, t2):
  19336. case (AnyType(), _):
  19337. return t2
  19338. case (_, AnyType()):
  19339. return t1
  19340. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19341. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19342. self.join_types(rt1,rt2))
  19343. case (TupleType(ts1), TupleType(ts2)):
  19344. return TupleType(list(map(self.join_types, ts1, ts2)))
  19345. case (_, _):
  19346. return t1
  19347. def check_consistent(self, t1, t2, e):
  19348. if not self.consistent(t1, t2):
  19349. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19350. + repr(t2) + ' in ' + repr(e))
  19351. \end{lstlisting}
  19352. \end{tcolorbox}
  19353. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19354. \label{fig:type-check-Lgradual-aux}
  19355. \end{figure}
  19356. \fi}
  19357. {\if\edition\racketEd
  19358. \begin{figure}[tbp]
  19359. \begin{tcolorbox}[colback=white]
  19360. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19361. (define/override (type-check-exp env)
  19362. (lambda (e)
  19363. (define recur (type-check-exp env))
  19364. (match e
  19365. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19366. (define-values (new-es ts)
  19367. (for/lists (exprs types) ([e es])
  19368. (recur e)))
  19369. (define t-ret (type-check-op op ts e))
  19370. (values (Prim op new-es) t-ret)]
  19371. [(Prim 'eq? (list e1 e2))
  19372. (define-values (e1^ t1) (recur e1))
  19373. (define-values (e2^ t2) (recur e2))
  19374. (check-consistent? t1 t2 e)
  19375. (define T (meet t1 t2))
  19376. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19377. [(Prim 'and (list e1 e2))
  19378. (recur (If e1 e2 (Bool #f)))]
  19379. [(Prim 'or (list e1 e2))
  19380. (define tmp (gensym 'tmp))
  19381. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19382. [(If e1 e2 e3)
  19383. (define-values (e1^ T1) (recur e1))
  19384. (define-values (e2^ T2) (recur e2))
  19385. (define-values (e3^ T3) (recur e3))
  19386. (check-consistent? T1 'Boolean e)
  19387. (check-consistent? T2 T3 e)
  19388. (define Tif (meet T2 T3))
  19389. (values (If e1^ e2^ e3^) Tif)]
  19390. [(SetBang x e1)
  19391. (define-values (e1^ T1) (recur e1))
  19392. (define varT (dict-ref env x))
  19393. (check-consistent? T1 varT e)
  19394. (values (SetBang x e1^) 'Void)]
  19395. [(WhileLoop e1 e2)
  19396. (define-values (e1^ T1) (recur e1))
  19397. (check-consistent? T1 'Boolean e)
  19398. (define-values (e2^ T2) ((type-check-exp env) e2))
  19399. (values (WhileLoop e1^ e2^) 'Void)]
  19400. [(Prim 'vector-length (list e1))
  19401. (define-values (e1^ t) (recur e1))
  19402. (match t
  19403. [`(Vector ,ts ...)
  19404. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19405. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19406. \end{lstlisting}
  19407. \end{tcolorbox}
  19408. \caption{Type checker for the \LangGrad{} language, part 1.}
  19409. \label{fig:type-check-Lgradual-1}
  19410. \end{figure}
  19411. \begin{figure}[tbp]
  19412. \begin{tcolorbox}[colback=white]
  19413. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19414. [(Prim 'vector-ref (list e1 e2))
  19415. (define-values (e1^ t1) (recur e1))
  19416. (define-values (e2^ t2) (recur e2))
  19417. (check-consistent? t2 'Integer e)
  19418. (match t1
  19419. [`(Vector ,ts ...)
  19420. (match e2^
  19421. [(Int i)
  19422. (unless (and (0 . <= . i) (i . < . (length ts)))
  19423. (error 'type-check "invalid index ~a in ~a" i e))
  19424. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19425. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19426. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19427. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19428. [(Prim 'vector-set! (list e1 e2 e3) )
  19429. (define-values (e1^ t1) (recur e1))
  19430. (define-values (e2^ t2) (recur e2))
  19431. (define-values (e3^ t3) (recur e3))
  19432. (check-consistent? t2 'Integer e)
  19433. (match t1
  19434. [`(Vector ,ts ...)
  19435. (match e2^
  19436. [(Int i)
  19437. (unless (and (0 . <= . i) (i . < . (length ts)))
  19438. (error 'type-check "invalid index ~a in ~a" i e))
  19439. (check-consistent? (list-ref ts i) t3 e)
  19440. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19441. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19442. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19443. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19444. [(Apply e1 e2s)
  19445. (define-values (e1^ T1) (recur e1))
  19446. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19447. (match T1
  19448. [`(,T1ps ... -> ,T1rt)
  19449. (for ([T2 T2s] [Tp T1ps])
  19450. (check-consistent? T2 Tp e))
  19451. (values (Apply e1^ e2s^) T1rt)]
  19452. [`Any (values (Apply e1^ e2s^) 'Any)]
  19453. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19454. [(Lambda params Tr e1)
  19455. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19456. (match p
  19457. [`[,x : ,T] (values x T)]
  19458. [(? symbol? x) (values x 'Any)])))
  19459. (define-values (e1^ T1)
  19460. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19461. (check-consistent? Tr T1 e)
  19462. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19463. `(,@Ts -> ,Tr))]
  19464. [else ((super type-check-exp env) e)]
  19465. )))
  19466. \end{lstlisting}
  19467. \end{tcolorbox}
  19468. \caption{Type checker for the \LangGrad{} language, part 2.}
  19469. \label{fig:type-check-Lgradual-2}
  19470. \end{figure}
  19471. \begin{figure}[tbp]
  19472. \begin{tcolorbox}[colback=white]
  19473. \begin{lstlisting}
  19474. (define/override (type-check-def env)
  19475. (lambda (e)
  19476. (match e
  19477. [(Def f params rt info body)
  19478. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19479. (match p
  19480. [`[,x : ,T] (values x T)]
  19481. [(? symbol? x) (values x 'Any)])))
  19482. (define new-env (append (map cons xs ps) env))
  19483. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19484. (check-consistent? ty^ rt e)
  19485. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19486. [else (error 'type-check "ill-formed function definition ~a" e)]
  19487. )))
  19488. (define/override (type-check-program e)
  19489. (match e
  19490. [(Program info body)
  19491. (define-values (body^ ty) ((type-check-exp '()) body))
  19492. (check-consistent? ty 'Integer e)
  19493. (ProgramDefsExp info '() body^)]
  19494. [(ProgramDefsExp info ds body)
  19495. (define new-env (for/list ([d ds])
  19496. (cons (Def-name d) (fun-def-type d))))
  19497. (define ds^ (for/list ([d ds])
  19498. ((type-check-def new-env) d)))
  19499. (define-values (body^ ty) ((type-check-exp new-env) body))
  19500. (check-consistent? ty 'Integer e)
  19501. (ProgramDefsExp info ds^ body^)]
  19502. [else (super type-check-program e)]))
  19503. \end{lstlisting}
  19504. \end{tcolorbox}
  19505. \caption{Type checker for the \LangGrad{} language, part 3.}
  19506. \label{fig:type-check-Lgradual-3}
  19507. \end{figure}
  19508. \begin{figure}[tbp]
  19509. \begin{tcolorbox}[colback=white]
  19510. \begin{lstlisting}
  19511. (define/public (join t1 t2)
  19512. (match* (t1 t2)
  19513. [('Integer 'Integer) 'Integer]
  19514. [('Boolean 'Boolean) 'Boolean]
  19515. [('Void 'Void) 'Void]
  19516. [('Any t2) t2]
  19517. [(t1 'Any) t1]
  19518. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19519. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19520. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19521. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19522. -> ,(join rt1 rt2))]))
  19523. (define/public (meet t1 t2)
  19524. (match* (t1 t2)
  19525. [('Integer 'Integer) 'Integer]
  19526. [('Boolean 'Boolean) 'Boolean]
  19527. [('Void 'Void) 'Void]
  19528. [('Any t2) 'Any]
  19529. [(t1 'Any) 'Any]
  19530. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19531. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19532. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19533. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19534. -> ,(meet rt1 rt2))]))
  19535. (define/public (check-consistent? t1 t2 e)
  19536. (unless (consistent? t1 t2)
  19537. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19538. (define explicit-prim-ops
  19539. (set-union
  19540. (type-predicates)
  19541. (set 'procedure-arity 'eq? 'not 'and 'or
  19542. 'vector 'vector-length 'vector-ref 'vector-set!
  19543. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19544. (define/override (fun-def-type d)
  19545. (match d
  19546. [(Def f params rt info body)
  19547. (define ps
  19548. (for/list ([p params])
  19549. (match p
  19550. [`[,x : ,T] T]
  19551. [(? symbol?) 'Any]
  19552. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19553. `(,@ps -> ,rt)]
  19554. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19555. \end{lstlisting}
  19556. \end{tcolorbox}
  19557. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19558. \label{fig:type-check-Lgradual-aux}
  19559. \end{figure}
  19560. \fi}
  19561. \section{Interpreting \LangCast{} }
  19562. \label{sec:interp-casts}
  19563. The runtime behavior of casts involving simple types such as
  19564. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19565. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19566. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19567. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19568. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19569. operator, by checking the value's tag and either retrieving
  19570. the underlying integer or signaling an error if the tag is not the
  19571. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19572. %
  19573. Things get more interesting with casts involving
  19574. \racket{function and tuple types}\python{function, tuple, and array types}.
  19575. Consider the cast of the function \code{maybe\_inc} from
  19576. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19577. to
  19578. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19579. shown in figure~\ref{fig:map-maybe_inc}.
  19580. When the \code{maybe\_inc} function flows through
  19581. this cast at runtime, we don't know whether it will return
  19582. an integer, because that depends on the input from the user.
  19583. The \LangCast{} interpreter therefore delays the checking
  19584. of the cast until the function is applied. To do so it
  19585. wraps \code{maybe\_inc} in a new function that casts its parameter
  19586. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19587. casts the return value from \CANYTY{} to \INTTY{}.
  19588. {\if\edition\pythonEd\pythonColor
  19589. %
  19590. There are further complications regarding casts on mutable data,
  19591. such as the \code{list} type introduced in
  19592. the challenge assignment of section~\ref{sec:arrays}.
  19593. %
  19594. \fi}
  19595. %
  19596. Consider the example presented in figure~\ref{fig:map-bang} that
  19597. defines a partially typed version of \code{map} whose parameter
  19598. \code{v} has type
  19599. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19600. and that updates \code{v} in place
  19601. instead of returning a new tuple. We name this function
  19602. \code{map\_inplace}. We apply \code{map\_inplace} to
  19603. \racket{a tuple}\python{an array} of integers, so the type checker
  19604. inserts a cast from
  19605. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19606. to
  19607. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19608. A naive way for the \LangCast{} interpreter to cast between
  19609. \racket{tuple}\python{array} types would be to build a new
  19610. \racket{tuple}\python{array} whose elements are the result
  19611. of casting each of the original elements to the target
  19612. type. However, this approach is not valid for mutable data structures.
  19613. In the example of figure~\ref{fig:map-bang},
  19614. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19615. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19616. the original one.
  19617. Instead the interpreter needs to create a new kind of value, a
  19618. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19619. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19620. and then applies a
  19621. cast to the resulting value. On a write, the proxy casts the argument
  19622. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19623. \racket{
  19624. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19625. \code{0} from \INTTY{} to \CANYTY{}.
  19626. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19627. from \CANYTY{} to \INTTY{}.
  19628. }
  19629. \python{
  19630. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19631. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19632. For the subscript on the left of the assignment,
  19633. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19634. }
  19635. Finally we consider casts between the \CANYTY{} type and higher-order types
  19636. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19637. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19638. have a type annotation, so it is given type \CANYTY{}. In the call to
  19639. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19640. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19641. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19642. \code{Inject}, but that doesn't work because
  19643. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19644. a flat type. Instead, we must first cast to
  19645. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19646. and then inject to \CANYTY{}.
  19647. \begin{figure}[tbp]
  19648. \begin{tcolorbox}[colback=white]
  19649. % gradual_test_11.rkt
  19650. {\if\edition\racketEd
  19651. \begin{lstlisting}
  19652. (define (map_inplace [f : (Any -> Any)]
  19653. [v : (Vector Any Any)]) : Void
  19654. (begin
  19655. (vector-set! v 0 (f (vector-ref v 0)))
  19656. (vector-set! v 1 (f (vector-ref v 1)))))
  19657. (define (inc x) (+ x 1))
  19658. (let ([v (vector 0 41)])
  19659. (begin (map_inplace inc v) (vector-ref v 1)))
  19660. \end{lstlisting}
  19661. \fi}
  19662. {\if\edition\pythonEd\pythonColor
  19663. \begin{lstlisting}
  19664. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19665. i = 0
  19666. while i != len(v):
  19667. v[i] = f(v[i])
  19668. i = i + 1
  19669. def inc(x : int) -> int:
  19670. return x + 1
  19671. v = [0, 41]
  19672. map_inplace(inc, v)
  19673. print(v[1])
  19674. \end{lstlisting}
  19675. \fi}
  19676. \end{tcolorbox}
  19677. \caption{An example involving casts on arrays.}
  19678. \label{fig:map-bang}
  19679. \end{figure}
  19680. \begin{figure}[btp]
  19681. \begin{tcolorbox}[colback=white]
  19682. {\if\edition\racketEd
  19683. \begin{lstlisting}
  19684. (define (map_inplace [f : (Any -> Any)] v) : Void
  19685. (begin
  19686. (vector-set! v 0 (f (vector-ref v 0)))
  19687. (vector-set! v 1 (f (vector-ref v 1)))))
  19688. (define (inc x) (+ x 1))
  19689. (let ([v (vector 0 41)])
  19690. (begin (map_inplace inc v) (vector-ref v 1)))
  19691. \end{lstlisting}
  19692. \fi}
  19693. {\if\edition\pythonEd\pythonColor
  19694. \begin{lstlisting}
  19695. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19696. i = 0
  19697. while i != len(v):
  19698. v[i] = f(v[i])
  19699. i = i + 1
  19700. def inc(x):
  19701. return x + 1
  19702. v = [0, 41]
  19703. map_inplace(inc, v)
  19704. print(v[1])
  19705. \end{lstlisting}
  19706. \fi}
  19707. \end{tcolorbox}
  19708. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19709. \label{fig:map-any}
  19710. \end{figure}
  19711. \begin{figure}[tbp]
  19712. \begin{tcolorbox}[colback=white]
  19713. {\if\edition\racketEd
  19714. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19715. (define/public (apply_cast v s t)
  19716. (match* (s t)
  19717. [(t1 t2) #:when (equal? t1 t2) v]
  19718. [('Any t2)
  19719. (match t2
  19720. [`(,ts ... -> ,rt)
  19721. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19722. (define v^ (apply-project v any->any))
  19723. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19724. [`(Vector ,ts ...)
  19725. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19726. (define v^ (apply-project v vec-any))
  19727. (apply_cast v^ vec-any `(Vector ,@ts))]
  19728. [else (apply-project v t2)])]
  19729. [(t1 'Any)
  19730. (match t1
  19731. [`(,ts ... -> ,rt)
  19732. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19733. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19734. (apply-inject v^ (any-tag any->any))]
  19735. [`(Vector ,ts ...)
  19736. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19737. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19738. (apply-inject v^ (any-tag vec-any))]
  19739. [else (apply-inject v (any-tag t1))])]
  19740. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19741. (define x (gensym 'x))
  19742. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19743. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19744. (define cast-writes
  19745. (for/list ([t1 ts1] [t2 ts2])
  19746. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19747. `(vector-proxy ,(vector v (apply vector cast-reads)
  19748. (apply vector cast-writes)))]
  19749. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19750. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19751. `(function ,xs ,(Cast
  19752. (Apply (Value v)
  19753. (for/list ([x xs][t1 ts1][t2 ts2])
  19754. (Cast (Var x) t2 t1)))
  19755. rt1 rt2) ())]
  19756. ))
  19757. \end{lstlisting}
  19758. \fi}
  19759. {\if\edition\pythonEd\pythonColor
  19760. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19761. def apply_cast(self, value, src, tgt):
  19762. match (src, tgt):
  19763. case (AnyType(), FunctionType(ps2, rt2)):
  19764. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19765. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19766. case (AnyType(), TupleType(ts2)):
  19767. anytup = TupleType([AnyType() for t1 in ts2])
  19768. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19769. case (AnyType(), ListType(t2)):
  19770. anylist = ListType([AnyType() for t1 in ts2])
  19771. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19772. case (AnyType(), AnyType()):
  19773. return value
  19774. case (AnyType(), _):
  19775. return self.apply_project(value, tgt)
  19776. case (FunctionType(ps1,rt1), AnyType()):
  19777. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19778. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19779. case (TupleType(ts1), AnyType()):
  19780. anytup = TupleType([AnyType() for t1 in ts1])
  19781. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19782. case (ListType(t1), AnyType()):
  19783. anylist = ListType(AnyType())
  19784. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19785. case (_, AnyType()):
  19786. return self.apply_inject(value, src)
  19787. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19788. params = [generate_name('x') for p in ps2]
  19789. args = [Cast(Name(x), t2, t1)
  19790. for (x,t1,t2) in zip(params, ps1, ps2)]
  19791. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19792. return Function('cast', params, [Return(body)], {})
  19793. case (TupleType(ts1), TupleType(ts2)):
  19794. x = generate_name('x')
  19795. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19796. for (t1,t2) in zip(ts1,ts2)]
  19797. return ProxiedTuple(value, reads)
  19798. case (ListType(t1), ListType(t2)):
  19799. x = generate_name('x')
  19800. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19801. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19802. return ProxiedList(value, read, write)
  19803. case (t1, t2) if t1 == t2:
  19804. return value
  19805. case (t1, t2):
  19806. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19807. def apply_inject(self, value, src):
  19808. return Tagged(value, self.type_to_tag(src))
  19809. def apply_project(self, value, tgt):
  19810. match value:
  19811. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19812. return val
  19813. case _:
  19814. raise Exception('apply_project, unexpected ' + repr(value))
  19815. \end{lstlisting}
  19816. \fi}
  19817. \end{tcolorbox}
  19818. \caption{The \code{apply\_cast} auxiliary method.}
  19819. \label{fig:apply_cast}
  19820. \end{figure}
  19821. The \LangCast{} interpreter uses an auxiliary function named
  19822. \code{apply\_cast} to cast a value from a source type to a target type,
  19823. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19824. the kinds of casts that we've discussed in this section.
  19825. %
  19826. The definition of the interpreter for \LangCast{} is shown in
  19827. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19828. dispatching to \code{apply\_cast}.
  19829. \racket{To handle the addition of tuple
  19830. proxies, we update the tuple primitives in \code{interp-op} using the
  19831. functions given in figure~\ref{fig:guarded-tuple}.}
  19832. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19833. \begin{figure}[tbp]
  19834. \begin{tcolorbox}[colback=white]
  19835. {\if\edition\racketEd
  19836. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19837. (define interp-Lcast-class
  19838. (class interp-Llambda-class
  19839. (super-new)
  19840. (inherit apply-fun apply-inject apply-project)
  19841. (define/override (interp-op op)
  19842. (match op
  19843. ['vector-length guarded-vector-length]
  19844. ['vector-ref guarded-vector-ref]
  19845. ['vector-set! guarded-vector-set!]
  19846. ['any-vector-ref (lambda (v i)
  19847. (match v [`(tagged ,v^ ,tg)
  19848. (guarded-vector-ref v^ i)]))]
  19849. ['any-vector-set! (lambda (v i a)
  19850. (match v [`(tagged ,v^ ,tg)
  19851. (guarded-vector-set! v^ i a)]))]
  19852. ['any-vector-length (lambda (v)
  19853. (match v [`(tagged ,v^ ,tg)
  19854. (guarded-vector-length v^)]))]
  19855. [else (super interp-op op)]
  19856. ))
  19857. (define/override ((interp-exp env) e)
  19858. (define (recur e) ((interp-exp env) e))
  19859. (match e
  19860. [(Value v) v]
  19861. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19862. [else ((super interp-exp env) e)]))
  19863. ))
  19864. (define (interp-Lcast p)
  19865. (send (new interp-Lcast-class) interp-program p))
  19866. \end{lstlisting}
  19867. \fi}
  19868. {\if\edition\pythonEd\pythonColor
  19869. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19870. class InterpLcast(InterpLany):
  19871. def interp_exp(self, e, env):
  19872. match e:
  19873. case Cast(value, src, tgt):
  19874. v = self.interp_exp(value, env)
  19875. return self.apply_cast(v, src, tgt)
  19876. case ValueExp(value):
  19877. return value
  19878. ...
  19879. case _:
  19880. return super().interp_exp(e, env)
  19881. \end{lstlisting}
  19882. \fi}
  19883. \end{tcolorbox}
  19884. \caption{The interpreter for \LangCast{}.}
  19885. \label{fig:interp-Lcast}
  19886. \end{figure}
  19887. {\if\edition\racketEd
  19888. \begin{figure}[tbp]
  19889. \begin{tcolorbox}[colback=white]
  19890. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19891. (define (guarded-vector-ref vec i)
  19892. (match vec
  19893. [`(vector-proxy ,proxy)
  19894. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19895. (define rd (vector-ref (vector-ref proxy 1) i))
  19896. (apply-fun rd (list val) 'guarded-vector-ref)]
  19897. [else (vector-ref vec i)]))
  19898. (define (guarded-vector-set! vec i arg)
  19899. (match vec
  19900. [`(vector-proxy ,proxy)
  19901. (define wr (vector-ref (vector-ref proxy 2) i))
  19902. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19903. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19904. [else (vector-set! vec i arg)]))
  19905. (define (guarded-vector-length vec)
  19906. (match vec
  19907. [`(vector-proxy ,proxy)
  19908. (guarded-vector-length (vector-ref proxy 0))]
  19909. [else (vector-length vec)]))
  19910. \end{lstlisting}
  19911. %% {\if\edition\pythonEd\pythonColor
  19912. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19913. %% UNDER CONSTRUCTION
  19914. %% \end{lstlisting}
  19915. %% \fi}
  19916. \end{tcolorbox}
  19917. \caption{The \code{guarded-vector} auxiliary functions.}
  19918. \label{fig:guarded-tuple}
  19919. \end{figure}
  19920. \fi}
  19921. {\if\edition\pythonEd\pythonColor
  19922. \section{Overload Resolution }
  19923. \label{sec:gradual-resolution}
  19924. Recall that when we added support for arrays in
  19925. section~\ref{sec:arrays}, the syntax for the array operations were the
  19926. same as for tuple operations (for example, accessing an element and
  19927. getting the length). So we performed overload resolution, with a pass
  19928. named \code{resolve}, to separate the array and tuple operations. In
  19929. particular, we introduced the primitives \code{array\_load},
  19930. \code{array\_store}, and \code{array\_len}.
  19931. For gradual typing, we further overload these operators to work on
  19932. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19933. updated with new cases for the \CANYTY{} type, translating the element
  19934. access and length operations to the primitives \code{any\_load},
  19935. \code{any\_store}, and \code{any\_len}.
  19936. \fi}
  19937. \section{Cast Insertion }
  19938. \label{sec:gradual-insert-casts}
  19939. In our discussion of type checking of \LangGrad{}, we mentioned how
  19940. the runtime aspect of type checking is carried out by the \code{Cast}
  19941. AST node, which is added to the program by a new pass named
  19942. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19943. language. We now discuss the details of this pass.
  19944. The \code{cast\_insert} pass is closely related to the type checker
  19945. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19946. In particular, the type checker allows implicit casts between
  19947. consistent types. The job of the \code{cast\_insert} pass is to make
  19948. those casts explicit. It does so by inserting
  19949. \code{Cast} nodes into the AST.
  19950. %
  19951. For the most part, the implicit casts occur in places where the type
  19952. checker checks two types for consistency. Consider the case for
  19953. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19954. checker requires that the type of the left operand is consistent with
  19955. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19956. \code{Cast} around the left operand, converting from its type to
  19957. \INTTY{}. The story is similar for the right operand. It is not always
  19958. necessary to insert a cast, for example, if the left operand already has type
  19959. \INTTY{} then there is no need for a \code{Cast}.
  19960. Some of the implicit casts are not as straightforward. One such case
  19961. arises with the
  19962. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19963. see that the type checker requires that the two branches have
  19964. consistent types and that type of the conditional expression is the
  19965. meet of the branches' types. In the target language \LangCast{}, both
  19966. branches will need to have the same type, and that type
  19967. will be the type of the conditional expression. Thus, each branch requires
  19968. a \code{Cast} to convert from its type to the meet of the branches' types.
  19969. The case for the function call exhibits another interesting situation. If
  19970. the function expression is of type \CANYTY{}, then it needs to be cast
  19971. to a function type so that it can be used in a function call in
  19972. \LangCast{}. Which function type should it be cast to? The parameter
  19973. and return types are unknown, so we can simply use \CANYTY{} for all
  19974. of them. Furthermore, in \LangCast{} the argument types will need to
  19975. exactly match the parameter types, so we must cast all the arguments
  19976. to type \CANYTY{} (if they are not already of that type).
  19977. {\if\edition\racketEd
  19978. %
  19979. Likewise, the cases for the tuple operators \code{vector-length},
  19980. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19981. where the tuple expression is of type \CANYTY{}. Instead of
  19982. handling these situations with casts, we recommend translating
  19983. the special-purpose variants of the tuple operators that handle
  19984. tuples of type \CANYTY{}: \code{any-vector-length},
  19985. \code{any-vector-ref}, and \code{any-vector-set!}.
  19986. %
  19987. \fi}
  19988. \section{Lower Casts }
  19989. \label{sec:lower_casts}
  19990. The next step in the journey toward x86 is the \code{lower\_casts}
  19991. pass that translates the casts in \LangCast{} to the lower-level
  19992. \code{Inject} and \code{Project} operators and new operators for
  19993. proxies, extending the \LangLam{} language to \LangProxy{}.
  19994. The \LangProxy{} language can also be described as an extension of
  19995. \LangAny{}, with the addition of proxies. We recommend creating an
  19996. auxiliary function named \code{lower\_cast} that takes an expression
  19997. (in \LangCast{}), a source type, and a target type and translates it
  19998. to an expression in \LangProxy{}.
  19999. The \code{lower\_cast} function can follow a code structure similar to
  20000. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  20001. the interpreter for \LangCast{}, because it must handle the same cases
  20002. as \code{apply\_cast} and it needs to mimic the behavior of
  20003. \code{apply\_cast}. The most interesting cases concern
  20004. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  20005. {\if\edition\racketEd
  20006. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  20007. type to another tuple type is accomplished by creating a proxy that
  20008. intercepts the operations on the underlying tuple. Here we make the
  20009. creation of the proxy explicit with the \code{vector-proxy} AST
  20010. node. It takes three arguments: the first is an expression for the
  20011. tuple, the second is a tuple of functions for casting an element that is
  20012. being read from the tuple, and the third is a tuple of functions for
  20013. casting an element that is being written to the array. You can create
  20014. the functions for reading and writing using lambda expressions. Also,
  20015. as we show in the next section, we need to differentiate these tuples
  20016. of functions from the user-created ones, so we recommend using a new
  20017. AST node named \code{raw-vector} instead of \code{vector}.
  20018. %
  20019. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20020. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20021. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  20022. \fi}
  20023. {\if\edition\pythonEd\pythonColor
  20024. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  20025. type to another array type is accomplished by creating a proxy that
  20026. intercepts the operations on the underlying array. Here we make the
  20027. creation of the proxy explicit with the \code{ListProxy} AST node. It
  20028. takes fives arguments: the first is an expression for the array, the
  20029. second is a function for casting an element that is being read from
  20030. the array, the third is a function for casting an element that is
  20031. being written to the array, the fourth is the type of the underlying
  20032. array, and the fifth is the type of the proxied array. You can create
  20033. the functions for reading and writing using lambda expressions.
  20034. A cast between two tuple types can be handled in a similar manner. We
  20035. create a proxy with the \code{TupleProxy} AST node. Tuples are
  20036. immutable, so there is no need for a function to cast the value during
  20037. a write. Because there is a separate element type for each slot in
  20038. the tuple, we need more than one function for casting during a read:
  20039. we need a tuple of functions.
  20040. %
  20041. Also, as we show in the next section, we need to differentiate these
  20042. tuples from the user-created ones, so we recommend using a new AST
  20043. node named \code{RawTuple} instead of \code{Tuple} to create the
  20044. tuples of functions.
  20045. %
  20046. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  20047. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  20048. that involves casting an array of integers to an array of \CANYTY{}.
  20049. \fi}
  20050. \begin{figure}[tbp]
  20051. \begin{tcolorbox}[colback=white]
  20052. {\if\edition\racketEd
  20053. \begin{lstlisting}
  20054. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  20055. (begin
  20056. (vector-set! v 0 (f (vector-ref v 0)))
  20057. (vector-set! v 1 (f (vector-ref v 1)))))
  20058. (define (inc [x : Any]) : Any
  20059. (inject (+ (project x Integer) 1) Integer))
  20060. (let ([v (vector 0 41)])
  20061. (begin
  20062. (map_inplace inc (vector-proxy v
  20063. (raw-vector (lambda: ([x9 : Integer]) : Any
  20064. (inject x9 Integer))
  20065. (lambda: ([x9 : Integer]) : Any
  20066. (inject x9 Integer)))
  20067. (raw-vector (lambda: ([x9 : Any]) : Integer
  20068. (project x9 Integer))
  20069. (lambda: ([x9 : Any]) : Integer
  20070. (project x9 Integer)))))
  20071. (vector-ref v 1)))
  20072. \end{lstlisting}
  20073. \fi}
  20074. {\if\edition\pythonEd\pythonColor
  20075. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20076. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  20077. i = 0
  20078. while i != array_len(v):
  20079. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  20080. i = (i + 1)
  20081. def inc(x : int) -> int:
  20082. return (x + 1)
  20083. def main() -> int:
  20084. v = [0, 41]
  20085. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  20086. print(array_load(v, 1))
  20087. return 0
  20088. \end{lstlisting}
  20089. \fi}
  20090. \end{tcolorbox}
  20091. \caption{Output of \code{lower\_casts} on the example shown in
  20092. figure~\ref{fig:map-bang}.}
  20093. \label{fig:map-bang-lower-cast}
  20094. \end{figure}
  20095. A cast from one function type to another function type is accomplished
  20096. by generating a \code{lambda} whose parameter and return types match
  20097. the target function type. The body of the \code{lambda} should cast
  20098. the parameters from the target type to the source type. (Yes,
  20099. backward! Functions are contravariant\index{subject}{contravariant}
  20100. in the parameters.) Afterward, call the underlying function and then
  20101. cast the result from the source return type to the target return type.
  20102. Figure~\ref{fig:map-lower-cast} shows the output of the
  20103. \code{lower\_casts} pass on the \code{map} example given in
  20104. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  20105. call to \code{map} is wrapped in a \code{lambda}.
  20106. \begin{figure}[tbp]
  20107. \begin{tcolorbox}[colback=white]
  20108. {\if\edition\racketEd
  20109. \begin{lstlisting}
  20110. (define (map [f : (Integer -> Integer)]
  20111. [v : (Vector Integer Integer)])
  20112. : (Vector Integer Integer)
  20113. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20114. (define (inc [x : Any]) : Any
  20115. (inject (+ (project x Integer) 1) Integer))
  20116. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  20117. (project (inc (inject x9 Integer)) Integer))
  20118. (vector 0 41)) 1)
  20119. \end{lstlisting}
  20120. \fi}
  20121. {\if\edition\pythonEd\pythonColor
  20122. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  20123. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  20124. return (f(v[0]), f(v[1]),)
  20125. def inc(x : any) -> any:
  20126. return inject((project(x, int) + 1), int)
  20127. def main() -> int:
  20128. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  20129. print(t[1])
  20130. return 0
  20131. \end{lstlisting}
  20132. \fi}
  20133. \end{tcolorbox}
  20134. \caption{Output of \code{lower\_casts} on the example shown in
  20135. figure~\ref{fig:gradual-map}.}
  20136. \label{fig:map-lower-cast}
  20137. \end{figure}
  20138. %\pagebreak
  20139. \section{Differentiate Proxies }
  20140. \label{sec:differentiate-proxies}
  20141. So far, the responsibility of differentiating tuples and tuple proxies
  20142. has been the job of the interpreter.
  20143. %
  20144. \racket{For example, the interpreter for \LangCast{} implements
  20145. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  20146. figure~\ref{fig:guarded-tuple}.}
  20147. %
  20148. In the \code{differentiate\_proxies} pass we shift this responsibility
  20149. to the generated code.
  20150. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  20151. we used the type \TUPLETYPENAME{} for both
  20152. real tuples and tuple proxies.
  20153. \python{Similarly, we use the type \code{list} for both arrays and
  20154. array proxies.}
  20155. In \LangPVec{} we return the
  20156. \TUPLETYPENAME{} type to its original
  20157. meaning, as the type of just tuples, and we introduce a new type,
  20158. \PTUPLETYNAME{}, whose values
  20159. can be either real tuples or tuple
  20160. proxies.
  20161. %
  20162. {\if\edition\pythonEd\pythonColor
  20163. Likewise, we return the
  20164. \ARRAYTYPENAME{} type to its original
  20165. meaning, as the type of arrays, and we introduce a new type,
  20166. \PARRAYTYNAME{}, whose values
  20167. can be either arrays or array proxies.
  20168. These new types come with a suite of new primitive operations.
  20169. \fi}
  20170. {\if\edition\racketEd
  20171. A tuple proxy is represented by a tuple containing three things: (1) the
  20172. underlying tuple, (2) a tuple of functions for casting elements that
  20173. are read from the tuple, and (3) a tuple of functions for casting
  20174. values to be written to the tuple. So, we define the following
  20175. abbreviation for the type of a tuple proxy:
  20176. \[
  20177. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20178. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20179. \]
  20180. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20181. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20182. %
  20183. Next we describe each of the new primitive operations.
  20184. \begin{description}
  20185. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20186. (\key{PVector} $T \ldots$)]\ \\
  20187. %
  20188. This operation brands a vector as a value of the \code{PVector} type.
  20189. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20190. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20191. %
  20192. This operation brands a vector proxy as value of the \code{PVector} type.
  20193. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20194. \BOOLTY{}] \ \\
  20195. %
  20196. This returns true if the value is a tuple proxy and false if it is a
  20197. real tuple.
  20198. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20199. (\key{Vector} $T \ldots$)]\ \\
  20200. %
  20201. Assuming that the input is a tuple, this operation returns the
  20202. tuple.
  20203. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20204. $\to$ \INTTY{}]\ \\
  20205. %
  20206. Given a tuple proxy, this operation returns the length of the tuple.
  20207. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20208. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20209. %
  20210. Given a tuple proxy, this operation returns the $i$th element of the
  20211. tuple.
  20212. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20213. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20214. Given a tuple proxy, this operation writes a value to the $i$th element
  20215. of the tuple.
  20216. \end{description}
  20217. \fi}
  20218. {\if\edition\pythonEd\pythonColor
  20219. %
  20220. A tuple proxy is represented by a tuple containing (1) the underlying
  20221. tuple and (2) a tuple of functions for casting elements that are read
  20222. from the tuple. The \LangPVec{} language includes the following AST
  20223. classes and primitive functions.
  20224. \begin{description}
  20225. \item[\code{InjectTuple}] \ \\
  20226. %
  20227. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20228. \item[\code{InjectTupleProxy}]\ \\
  20229. %
  20230. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20231. \item[\code{is\_tuple\_proxy}]\ \\
  20232. %
  20233. This primitive returns true if the value is a tuple proxy and false
  20234. if it is a tuple.
  20235. \item[\code{project\_tuple}]\ \\
  20236. %
  20237. Converts a tuple that is branded as \PTUPLETYNAME{}
  20238. back to a tuple.
  20239. \item[\code{proxy\_tuple\_len}]\ \\
  20240. %
  20241. Given a tuple proxy, returns the length of the underlying tuple.
  20242. \item[\code{proxy\_tuple\_load}]\ \\
  20243. %
  20244. Given a tuple proxy, returns the $i$th element of the underlying
  20245. tuple.
  20246. \end{description}
  20247. An array proxy is represented by a tuple containing (1) the underlying
  20248. array, (2) a function for casting elements that are read from the
  20249. array, and (3) a function for casting elements that are written to the
  20250. array. The \LangPVec{} language includes the following AST classes
  20251. and primitive functions.
  20252. \begin{description}
  20253. \item[\code{InjectList}]\ \\
  20254. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20255. \item[\code{InjectListProxy}]\ \\
  20256. %
  20257. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20258. \item[\code{is\_array\_proxy}]\ \\
  20259. %
  20260. Returns true if the value is an array proxy and false if it is an
  20261. array.
  20262. \item[\code{project\_array}]\ \\
  20263. %
  20264. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20265. array.
  20266. \item[\code{proxy\_array\_len}]\ \\
  20267. %
  20268. Given an array proxy, returns the length of the underlying array.
  20269. \item[\code{proxy\_array\_load}]\ \\
  20270. %
  20271. Given an array proxy, returns the $i$th element of the underlying
  20272. array.
  20273. \item[\code{proxy\_array\_store}]\ \\
  20274. %
  20275. Given an array proxy, writes a value to the $i$th element of the
  20276. underlying array.
  20277. \end{description}
  20278. \fi}
  20279. Now we discuss the translation that differentiates tuples and arrays
  20280. from proxies. First, every type annotation in the program is
  20281. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20282. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20283. places. For example, we wrap every tuple creation with an
  20284. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20285. %
  20286. {\if\edition\racketEd
  20287. \begin{minipage}{0.96\textwidth}
  20288. \begin{lstlisting}
  20289. (vector |$e_1 \ldots e_n$|)
  20290. |$\Rightarrow$|
  20291. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20292. \end{lstlisting}
  20293. \end{minipage}
  20294. \fi}
  20295. {\if\edition\pythonEd\pythonColor
  20296. \begin{lstlisting}
  20297. Tuple(|$e_1, \ldots, e_n$|)
  20298. |$\Rightarrow$|
  20299. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20300. \end{lstlisting}
  20301. \fi}
  20302. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20303. AST node that we introduced in the previous
  20304. section does not get injected.
  20305. {\if\edition\racketEd
  20306. \begin{lstlisting}
  20307. (raw-vector |$e_1 \ldots e_n$|)
  20308. |$\Rightarrow$|
  20309. (vector |$e'_1 \ldots e'_n$|)
  20310. \end{lstlisting}
  20311. \fi}
  20312. {\if\edition\pythonEd\pythonColor
  20313. \begin{lstlisting}
  20314. RawTuple(|$e_1, \ldots, e_n$|)
  20315. |$\Rightarrow$|
  20316. Tuple(|$e'_1, \ldots, e'_n$|)
  20317. \end{lstlisting}
  20318. \fi}
  20319. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20320. translates as follows:
  20321. %
  20322. {\if\edition\racketEd
  20323. \begin{lstlisting}
  20324. (vector-proxy |$e_1~e_2~e_3$|)
  20325. |$\Rightarrow$|
  20326. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20327. \end{lstlisting}
  20328. \fi}
  20329. {\if\edition\pythonEd\pythonColor
  20330. \begin{lstlisting}
  20331. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20332. |$\Rightarrow$|
  20333. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20334. \end{lstlisting}
  20335. \fi}
  20336. We translate the element access operations into conditional
  20337. expressions that check whether the value is a proxy and then dispatch
  20338. to either the appropriate proxy tuple operation or the regular tuple
  20339. operation.
  20340. {\if\edition\racketEd
  20341. \begin{lstlisting}
  20342. (vector-ref |$e_1$| |$i$|)
  20343. |$\Rightarrow$|
  20344. (let ([|$v~e_1$|])
  20345. (if (proxy? |$v$|)
  20346. (proxy-vector-ref |$v$| |$i$|)
  20347. (vector-ref (project-vector |$v$|) |$i$|)
  20348. \end{lstlisting}
  20349. \fi}
  20350. %
  20351. Note that in the branch for a tuple, we must apply
  20352. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20353. from the tuple.
  20354. The translation of array operations is similar to the ones for tuples.
  20355. \section{Reveal Casts }
  20356. \label{sec:reveal-casts-gradual}
  20357. {\if\edition\racketEd
  20358. Recall that the \code{reveal\_casts} pass
  20359. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20360. \code{Inject} and \code{Project} into lower-level operations.
  20361. %
  20362. In particular, \code{Project} turns into a conditional expression that
  20363. inspects the tag and retrieves the underlying value. Here we need to
  20364. augment the translation of \code{Project} to handle the situation in which
  20365. the target type is \code{PVector}. Instead of using
  20366. \code{vector-length} we need to use \code{proxy-vector-length}.
  20367. \begin{lstlisting}
  20368. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20369. |$\Rightarrow$|
  20370. (let |$\itm{tmp}$| |$e'$|
  20371. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20372. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20373. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20374. (exit)))
  20375. \end{lstlisting}
  20376. \fi}
  20377. %
  20378. {\if\edition\pythonEd\pythonColor
  20379. Recall that the $\itm{tagof}$ function determines the bits used to
  20380. identify values of different types, and it is used in the \code{reveal\_casts}
  20381. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20382. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20383. decimal), just like the tuple and array types.
  20384. \fi}
  20385. %
  20386. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20387. \pagebreak
  20388. \section{Closure Conversion }
  20389. \label{sec:closure-conversion-gradual}
  20390. The auxiliary function that translates type annotations needs to be
  20391. updated to handle the \PTUPLETYNAME{}
  20392. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20393. %
  20394. Otherwise, the only other changes are adding cases that copy the new
  20395. AST nodes.
  20396. \section{Select Instructions }
  20397. \label{sec:select-instructions-gradual}
  20398. \index{subject}{select instructions}
  20399. Recall that the \code{select\_instructions} pass is responsible for
  20400. lowering the primitive operations into x86 instructions. So, we need
  20401. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20402. to x86. To do so, the first question we need to answer is how to
  20403. differentiate between tuple and tuple proxies\python{, and likewise for
  20404. arrays and array proxies}. We need just one bit to accomplish this;
  20405. we use the bit in position $63$ of the 64-bit tag at the front of
  20406. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20407. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20408. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20409. it that way.
  20410. {\if\edition\racketEd
  20411. \begin{lstlisting}
  20412. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20413. |$\Rightarrow$|
  20414. movq |$e'_1$|, |$\itm{lhs'}$|
  20415. \end{lstlisting}
  20416. \fi}
  20417. {\if\edition\pythonEd\pythonColor
  20418. \begin{lstlisting}
  20419. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20420. |$\Rightarrow$|
  20421. movq |$e'_1$|, |$\itm{lhs'}$|
  20422. \end{lstlisting}
  20423. \fi}
  20424. \python{The translation for \code{InjectList} is also a move instruction.}
  20425. \noindent On the other hand,
  20426. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20427. $63$ to $1$.
  20428. %
  20429. {\if\edition\racketEd
  20430. \begin{lstlisting}
  20431. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20432. |$\Rightarrow$|
  20433. movq |$e'_1$|, %r11
  20434. movq |$(1 << 63)$|, %rax
  20435. orq 0(%r11), %rax
  20436. movq %rax, 0(%r11)
  20437. movq %r11, |$\itm{lhs'}$|
  20438. \end{lstlisting}
  20439. \fi}
  20440. {\if\edition\pythonEd\pythonColor
  20441. \begin{lstlisting}
  20442. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20443. |$\Rightarrow$|
  20444. movq |$e'_1$|, %r11
  20445. movq |$(1 << 63)$|, %rax
  20446. orq 0(%r11), %rax
  20447. movq %rax, 0(%r11)
  20448. movq %r11, |$\itm{lhs'}$|
  20449. \end{lstlisting}
  20450. \fi}
  20451. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20452. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20453. The \racket{\code{proxy?} operation consumes}%
  20454. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20455. consume}
  20456. the information so carefully stashed away by the injections. It
  20457. isolates bit $63$ to tell whether the value is a proxy.
  20458. %
  20459. {\if\edition\racketEd
  20460. \begin{lstlisting}
  20461. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20462. |$\Rightarrow$|
  20463. movq |$e_1'$|, %r11
  20464. movq 0(%r11), %rax
  20465. sarq $63, %rax
  20466. andq $1, %rax
  20467. movq %rax, |$\itm{lhs'}$|
  20468. \end{lstlisting}
  20469. \fi}%
  20470. %
  20471. {\if\edition\pythonEd\pythonColor
  20472. \begin{lstlisting}
  20473. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20474. |$\Rightarrow$|
  20475. movq |$e_1'$|, %r11
  20476. movq 0(%r11), %rax
  20477. sarq $63, %rax
  20478. andq $1, %rax
  20479. movq %rax, |$\itm{lhs'}$|
  20480. \end{lstlisting}
  20481. \fi}%
  20482. %
  20483. The \racket{\code{project-vector} operation is}
  20484. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20485. straightforward to translate, so we leave that to the reader.
  20486. Regarding the element access operations for tuples\python{ and arrays}, the
  20487. runtime provides procedures that implement them (they are recursive
  20488. functions!), so here we simply need to translate these tuple
  20489. operations into the appropriate function call. For example, here is
  20490. the translation for
  20491. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20492. {\if\edition\racketEd
  20493. \begin{minipage}{0.96\textwidth}
  20494. \begin{lstlisting}
  20495. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20496. |$\Rightarrow$|
  20497. movq |$e_1'$|, %rdi
  20498. movq |$e_2'$|, %rsi
  20499. callq proxy_vector_ref
  20500. movq %rax, |$\itm{lhs'}$|
  20501. \end{lstlisting}
  20502. \end{minipage}
  20503. \fi}
  20504. {\if\edition\pythonEd\pythonColor
  20505. \begin{lstlisting}
  20506. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20507. |$\Rightarrow$|
  20508. movq |$e_1'$|, %rdi
  20509. movq |$e_2'$|, %rsi
  20510. callq proxy_vector_ref
  20511. movq %rax, |$\itm{lhs'}$|
  20512. \end{lstlisting}
  20513. \fi}
  20514. {\if\edition\pythonEd\pythonColor
  20515. % TODO: revisit the names vecof for python -Jeremy
  20516. We translate
  20517. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20518. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20519. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20520. \fi}
  20521. We have another batch of operations to deal with: those for the
  20522. \CANYTY{} type. Recall that we generate an
  20523. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20524. there is a element access on something of type \CANYTY{}, and
  20525. similarly for
  20526. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20527. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20528. section~\ref{sec:select-Lany} we selected instructions for these
  20529. operations on the basis of the idea that the underlying value was a tuple or
  20530. array. But in the current setting, the underlying value is of type
  20531. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20532. functions to deal with this:
  20533. \code{proxy\_vector\_ref},
  20534. \code{proxy\_vector\_set}, and
  20535. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20536. to determine whether the value is a proxy, and then
  20537. dispatches to the the appropriate code.
  20538. %
  20539. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20540. can be translated as follows.
  20541. We begin by projecting the underlying value out of the tagged value and
  20542. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20543. {\if\edition\racketEd
  20544. \begin{lstlisting}
  20545. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20546. |$\Rightarrow$|
  20547. movq |$\neg 111$|, %rdi
  20548. andq |$e_1'$|, %rdi
  20549. movq |$e_2'$|, %rsi
  20550. callq proxy_vector_ref
  20551. movq %rax, |$\itm{lhs'}$|
  20552. \end{lstlisting}
  20553. \fi}
  20554. {\if\edition\pythonEd\pythonColor
  20555. \begin{lstlisting}
  20556. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20557. |$\Rightarrow$|
  20558. movq |$\neg 111$|, %rdi
  20559. andq |$e_1'$|, %rdi
  20560. movq |$e_2'$|, %rsi
  20561. callq proxy_vector_ref
  20562. movq %rax, |$\itm{lhs'}$|
  20563. \end{lstlisting}
  20564. \fi}
  20565. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20566. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20567. are translated in a similar way. Alternatively, you could generate
  20568. instructions to open-code
  20569. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20570. and \code{proxy\_vector\_length} functions.
  20571. \begin{exercise}\normalfont\normalsize
  20572. Implement a compiler for the gradually typed \LangGrad{} language by
  20573. extending and adapting your compiler for \LangLam{}. Create ten new
  20574. partially typed test programs. In addition to testing with these
  20575. new programs, test your compiler on all the tests for \LangLam{}
  20576. and for \LangDyn{}.
  20577. %
  20578. \racket{Sometimes you may get a type-checking error on the
  20579. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20580. the \CANYTY{} type around each subexpression that has caused a type
  20581. error. Although \LangDyn{} does not have explicit casts, you can
  20582. induce one by wrapping the subexpression \code{e} with a call to
  20583. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20584. %
  20585. \python{Sometimes you may get a type-checking error on the
  20586. \LangDyn{} programs, but you can adapt them by inserting a
  20587. temporary variable of type \CANYTY{} that is initialized with the
  20588. troublesome expression.}
  20589. \end{exercise}
  20590. \begin{figure}[t]
  20591. \begin{tcolorbox}[colback=white]
  20592. {\if\edition\racketEd
  20593. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20594. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20595. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20596. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20597. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20598. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20599. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20600. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20601. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20602. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20603. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20604. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20605. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20606. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20607. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20608. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20609. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20610. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20611. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20612. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20613. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20614. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20615. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20616. \path[->,bend left=15] (Lgradual) edge [above] node
  20617. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20618. \path[->,bend left=15] (Lgradual2) edge [above] node
  20619. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20620. \path[->,bend left=15] (Lgradual3) edge [above] node
  20621. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20622. \path[->,bend left=15] (Lgradual4) edge [left] node
  20623. {\ttfamily\footnotesize shrink} (Lgradualr);
  20624. \path[->,bend left=15] (Lgradualr) edge [above] node
  20625. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20626. \path[->,bend right=15] (Lgradualp) edge [above] node
  20627. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20628. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20629. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20630. \path[->,bend right=15] (Llambdapp) edge [above] node
  20631. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20632. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20633. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20634. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20635. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20636. \path[->,bend left=15] (F1-2) edge [above] node
  20637. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20638. \path[->,bend left=15] (F1-3) edge [left] node
  20639. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20640. \path[->,bend left=15] (F1-4) edge [below] node
  20641. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20642. \path[->,bend right=15] (F1-5) edge [above] node
  20643. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20644. \path[->,bend right=15] (F1-6) edge [above] node
  20645. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20646. \path[->,bend right=15] (C3-2) edge [right] node
  20647. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20648. \path[->,bend right=15] (x86-2) edge [right] node
  20649. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20650. \path[->,bend right=15] (x86-2-1) edge [below] node
  20651. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20652. \path[->,bend right=15] (x86-2-2) edge [right] node
  20653. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20654. \path[->,bend left=15] (x86-3) edge [above] node
  20655. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20656. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20657. \end{tikzpicture}
  20658. \fi}
  20659. {\if\edition\pythonEd\pythonColor
  20660. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20661. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20662. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20663. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20664. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20665. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20666. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20667. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20668. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20669. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20670. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20671. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20672. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20673. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20674. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20675. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20676. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20677. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20678. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20679. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20680. \path[->,bend left=15] (Lgradual) edge [above] node
  20681. {\ttfamily\footnotesize shrink} (Lgradual2);
  20682. \path[->,bend left=15] (Lgradual2) edge [above] node
  20683. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20684. \path[->,bend left=15] (Lgradual3) edge [above] node
  20685. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20686. \path[->,bend left=15] (Lgradual4) edge [left] node
  20687. {\ttfamily\footnotesize resolve} (Lgradualr);
  20688. \path[->,bend left=15] (Lgradualr) edge [below] node
  20689. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20690. \path[->,bend right=15] (Lgradualp) edge [above] node
  20691. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20692. \path[->,bend right=15] (Llambdapp) edge [above] node
  20693. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20694. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20695. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20696. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20697. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20698. \path[->,bend left=15] (F1-1) edge [above] node
  20699. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20700. \path[->,bend left=15] (F1-2) edge [above] node
  20701. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20702. \path[->,bend left=15] (F1-3) edge [right] node
  20703. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20704. \path[->,bend right=15] (F1-5) edge [above] node
  20705. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20706. \path[->,bend right=15] (F1-6) edge [above] node
  20707. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20708. \path[->,bend right=15] (C3-2) edge [right] node
  20709. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20710. \path[->,bend right=15] (x86-2) edge [below] node
  20711. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20712. \path[->,bend right=15] (x86-3) edge [below] node
  20713. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20714. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20715. \end{tikzpicture}
  20716. \fi}
  20717. \end{tcolorbox}
  20718. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20719. \label{fig:Lgradual-passes}
  20720. \end{figure}
  20721. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20722. needed for the compilation of \LangGrad{}.
  20723. \section{Further Reading}
  20724. This chapter just scratches the surface of gradual typing. The basic
  20725. approach described here is missing two key ingredients that one would
  20726. want in an implementation of gradual typing: blame
  20727. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20728. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20729. problem addressed by blame tracking is that when a cast on a
  20730. higher-order value fails, it often does so at a point in the program
  20731. that is far removed from the original cast. Blame tracking is a
  20732. technique for propagating extra information through casts and proxies
  20733. so that when a cast fails, the error message can point back to the
  20734. original location of the cast in the source program.
  20735. The problem addressed by space-efficient casts also relates to
  20736. higher-order casts. It turns out that in partially typed programs, a
  20737. function or tuple can flow through a great many casts at runtime. With
  20738. the approach described in this chapter, each cast adds another
  20739. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20740. considerable space, but it also makes the function calls and tuple
  20741. operations slow. For example, a partially typed version of quicksort
  20742. could, in the worst case, build a chain of proxies of length $O(n)$
  20743. around the tuple, changing the overall time complexity of the
  20744. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20745. solution to this problem by representing casts using the coercion
  20746. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20747. long chains of proxies by compressing them into a concise normal
  20748. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20749. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20750. the Grift compiler:
  20751. \begin{center}
  20752. \url{https://github.com/Gradual-Typing/Grift}
  20753. \end{center}
  20754. There are also interesting interactions between gradual typing and
  20755. other language features, such as generics, information-flow types, and
  20756. type inference, to name a few. We recommend to the reader the
  20757. online gradual typing bibliography for more material:
  20758. \begin{center}
  20759. \url{http://samth.github.io/gradual-typing-bib/}
  20760. \end{center}
  20761. % TODO: challenge problem:
  20762. % type analysis and type specialization?
  20763. % coercions?
  20764. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20765. \chapter{Generics}
  20766. \label{ch:Lpoly}
  20767. \setcounter{footnote}{0}
  20768. This chapter studies the compilation of
  20769. generics\index{subject}{generics} (aka parametric
  20770. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20771. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20772. enable programmers to make code more reusable by parameterizing
  20773. functions and data structures with respect to the types on which they
  20774. operate. For example, figure~\ref{fig:map-poly} revisits the
  20775. \code{map} example and this time gives it a more fitting type. This
  20776. \code{map} function is parameterized with respect to the element type
  20777. of the tuple. The type of \code{map} is the following generic type
  20778. specified by the \code{All} type with parameter \code{T}:
  20779. {\if\edition\racketEd
  20780. \begin{lstlisting}
  20781. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20782. \end{lstlisting}
  20783. \fi}
  20784. {\if\edition\pythonEd\pythonColor
  20785. \begin{lstlisting}
  20786. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20787. \end{lstlisting}
  20788. \fi}
  20789. %
  20790. The idea is that \code{map} can be used at \emph{all} choices of a
  20791. type for parameter \code{T}. In the example shown in
  20792. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20793. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20794. \code{T}, but we could have just as well applied \code{map} to a tuple
  20795. of Booleans.
  20796. %
  20797. A \emph{monomorphic} function is simply one that is not generic.
  20798. %
  20799. We use the term \emph{instantiation} for the process (within the
  20800. language implementation) of turning a generic function into a
  20801. monomorphic one, where the type parameters have been replaced by
  20802. types.
  20803. {\if\edition\pythonEd\pythonColor
  20804. %
  20805. In Python, when writing a generic function such as \code{map}, one
  20806. does not explicitly write its generic type (using \code{All}).
  20807. Instead, that the function is generic is implied by the use of type
  20808. variables (such as \code{T}) in the type annotations of its
  20809. parameters.
  20810. %
  20811. \fi}
  20812. \begin{figure}[tbp]
  20813. % poly_test_2.rkt
  20814. \begin{tcolorbox}[colback=white]
  20815. {\if\edition\racketEd
  20816. \begin{lstlisting}
  20817. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20818. (define (map f v)
  20819. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20820. (define (inc [x : Integer]) : Integer (+ x 1))
  20821. (vector-ref (map inc (vector 0 41)) 1)
  20822. \end{lstlisting}
  20823. \fi}
  20824. {\if\edition\pythonEd\pythonColor
  20825. \begin{lstlisting}
  20826. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20827. return (f(tup[0]), f(tup[1]))
  20828. def add1(x : int) -> int:
  20829. return x + 1
  20830. t = map(add1, (0, 41))
  20831. print(t[1])
  20832. \end{lstlisting}
  20833. \fi}
  20834. \end{tcolorbox}
  20835. \caption{A generic version of the \code{map} function.}
  20836. \label{fig:map-poly}
  20837. \end{figure}
  20838. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20839. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20840. shows the definition of the abstract syntax.
  20841. %
  20842. {\if\edition\racketEd
  20843. We add a second form for function definitions in which a type
  20844. declaration comes before the \code{define}. In the abstract syntax,
  20845. the return type in the \code{Def} is \CANYTY{}, but that should be
  20846. ignored in favor of the return type in the type declaration. (The
  20847. \CANYTY{} comes from using the same parser as discussed in
  20848. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20849. enables the use of an \code{All} type for a function, thereby making
  20850. it generic.
  20851. \fi}
  20852. %
  20853. The grammar for types is extended to include the type of a generic
  20854. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20855. abstract syntax)}.
  20856. \newcommand{\LpolyGrammarRacket}{
  20857. \begin{array}{lcl}
  20858. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20859. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20860. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20861. \end{array}
  20862. }
  20863. \newcommand{\LpolyASTRacket}{
  20864. \begin{array}{lcl}
  20865. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20866. \Def &::=& \DECL{\Var}{\Type} \\
  20867. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20868. \end{array}
  20869. }
  20870. \newcommand{\LpolyGrammarPython}{
  20871. \begin{array}{lcl}
  20872. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20873. \end{array}
  20874. }
  20875. \newcommand{\LpolyASTPython}{
  20876. \begin{array}{lcl}
  20877. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20878. \MID \key{GenericVar}\LP\Var\RP
  20879. \end{array}
  20880. }
  20881. \begin{figure}[tp]
  20882. \centering
  20883. \begin{tcolorbox}[colback=white]
  20884. \footnotesize
  20885. {\if\edition\racketEd
  20886. \[
  20887. \begin{array}{l}
  20888. \gray{\LintGrammarRacket{}} \\ \hline
  20889. \gray{\LvarGrammarRacket{}} \\ \hline
  20890. \gray{\LifGrammarRacket{}} \\ \hline
  20891. \gray{\LwhileGrammarRacket} \\ \hline
  20892. \gray{\LtupGrammarRacket} \\ \hline
  20893. \gray{\LfunGrammarRacket} \\ \hline
  20894. \gray{\LlambdaGrammarRacket} \\ \hline
  20895. \LpolyGrammarRacket \\
  20896. \begin{array}{lcl}
  20897. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20898. \end{array}
  20899. \end{array}
  20900. \]
  20901. \fi}
  20902. {\if\edition\pythonEd\pythonColor
  20903. \[
  20904. \begin{array}{l}
  20905. \gray{\LintGrammarPython{}} \\ \hline
  20906. \gray{\LvarGrammarPython{}} \\ \hline
  20907. \gray{\LifGrammarPython{}} \\ \hline
  20908. \gray{\LwhileGrammarPython} \\ \hline
  20909. \gray{\LtupGrammarPython} \\ \hline
  20910. \gray{\LfunGrammarPython} \\ \hline
  20911. \gray{\LlambdaGrammarPython} \\\hline
  20912. \LpolyGrammarPython \\
  20913. \begin{array}{lcl}
  20914. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20915. \end{array}
  20916. \end{array}
  20917. \]
  20918. \fi}
  20919. \end{tcolorbox}
  20920. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20921. (figure~\ref{fig:Llam-concrete-syntax}).}
  20922. \label{fig:Lpoly-concrete-syntax}
  20923. \index{subject}{Lgen@\LangPoly{} concrete syntax}
  20924. \end{figure}
  20925. \begin{figure}[tp]
  20926. \centering
  20927. \begin{tcolorbox}[colback=white]
  20928. \footnotesize
  20929. {\if\edition\racketEd
  20930. \[
  20931. \begin{array}{l}
  20932. \gray{\LintOpAST} \\ \hline
  20933. \gray{\LvarASTRacket{}} \\ \hline
  20934. \gray{\LifASTRacket{}} \\ \hline
  20935. \gray{\LwhileASTRacket{}} \\ \hline
  20936. \gray{\LtupASTRacket{}} \\ \hline
  20937. \gray{\LfunASTRacket} \\ \hline
  20938. \gray{\LlambdaASTRacket} \\ \hline
  20939. \LpolyASTRacket \\
  20940. \begin{array}{lcl}
  20941. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20942. \end{array}
  20943. \end{array}
  20944. \]
  20945. \fi}
  20946. {\if\edition\pythonEd\pythonColor
  20947. \[
  20948. \begin{array}{l}
  20949. \gray{\LintASTPython} \\ \hline
  20950. \gray{\LvarASTPython{}} \\ \hline
  20951. \gray{\LifASTPython{}} \\ \hline
  20952. \gray{\LwhileASTPython{}} \\ \hline
  20953. \gray{\LtupASTPython{}} \\ \hline
  20954. \gray{\LfunASTPython} \\ \hline
  20955. \gray{\LlambdaASTPython} \\ \hline
  20956. \LpolyASTPython \\
  20957. \begin{array}{lcl}
  20958. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20959. \end{array}
  20960. \end{array}
  20961. \]
  20962. \fi}
  20963. \end{tcolorbox}
  20964. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20965. (figure~\ref{fig:Llam-syntax}).}
  20966. \label{fig:Lpoly-syntax}
  20967. \index{subject}{Lgen@\LangPoly{} abstract syntax}
  20968. \end{figure}
  20969. By including the \code{All} type in the $\Type$ nonterminal of the
  20970. grammar we choose to make generics first class, which has interesting
  20971. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20972. not include syntax for the \code{All} type. It is inferred for functions whose
  20973. type annotations contain type variables.} Many languages with generics, such as
  20974. C++~\citep{stroustrup88:_param_types} and Standard
  20975. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20976. may be helpful to see an example of first-class generics in action. In
  20977. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20978. whose parameter is a generic function. Indeed, because the grammar for
  20979. $\Type$ includes the \code{All} type, a generic function may also be
  20980. returned from a function or stored inside a tuple. The body of
  20981. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20982. and also to an integer, which would not be possible if \code{f} were
  20983. not generic.
  20984. \begin{figure}[tbp]
  20985. \begin{tcolorbox}[colback=white]
  20986. {\if\edition\racketEd
  20987. \begin{lstlisting}
  20988. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20989. (define (apply_twice f)
  20990. (if (f #t) (f 42) (f 777)))
  20991. (: id (All (T) (T -> T)))
  20992. (define (id x) x)
  20993. (apply_twice id)
  20994. \end{lstlisting}
  20995. \fi}
  20996. {\if\edition\pythonEd\pythonColor
  20997. \begin{lstlisting}
  20998. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20999. if f(True):
  21000. return f(42)
  21001. else:
  21002. return f(777)
  21003. def id(x: T) -> T:
  21004. return x
  21005. print(apply_twice(id))
  21006. \end{lstlisting}
  21007. \fi}
  21008. \end{tcolorbox}
  21009. \caption{An example illustrating first-class generics.}
  21010. \label{fig:apply-twice}
  21011. \end{figure}
  21012. The type checker for \LangPoly{} shown in
  21013. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  21014. (compared to \LangLam{}) which we discuss in the following paragraphs.
  21015. {\if\edition\pythonEd\pythonColor
  21016. %
  21017. Regarding function definitions, if the type annotations on its
  21018. parameters contain generic variables, then the function is generic and
  21019. therefore its type is an \code{All} type wrapped around a function
  21020. type. Otherwise the function is monomorphic and its type is simply
  21021. a function type.
  21022. %
  21023. \fi}
  21024. The type checking of a function application is extended to handle the
  21025. case in which the operator expression is a generic function. In that case
  21026. the type arguments are deduced by matching the types of the parameters
  21027. with the types of the arguments.
  21028. %
  21029. The \code{match\_types} auxiliary function
  21030. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  21031. recursively descending through a parameter type \code{param\_ty} and
  21032. the corresponding argument type \code{arg\_ty}, making sure that they
  21033. are equal except when there is a type parameter in the parameter
  21034. type. Upon encountering a type parameter for the first time, the
  21035. algorithm deduces an association of the type parameter to the
  21036. corresponding part of the argument type. If it is not the first time
  21037. that the type parameter has been encountered, the algorithm looks up
  21038. its deduced type and makes sure that it is equal to the corresponding
  21039. part of the argument type. The return type of the application is the
  21040. return type of the generic function with the type parameters
  21041. replaced by the deduced type arguments, using the
  21042. \code{substitute\_type} auxiliary function, which is also listed in
  21043. figure~\ref{fig:type-check-Lpoly-aux}.
  21044. The type checker extends type equality to handle the \code{All} type.
  21045. This is not quite as simple as for other types, such as function and
  21046. tuple types, because two \code{All} types can be syntactically
  21047. different even though they are equivalent. For example,
  21048. \begin{center}
  21049. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  21050. \end{center}
  21051. is equivalent to
  21052. \begin{center}
  21053. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  21054. \end{center}
  21055. Two generic types are equal if they differ only in
  21056. the choice of the names of the type parameters. The definition of type
  21057. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  21058. parameters in one type to match the type parameters of the other type.
  21059. {\if\edition\racketEd
  21060. %
  21061. The type checker also ensures that only defined type variables appear
  21062. in type annotations. The \code{check\_well\_formed} function for which
  21063. the definition is shown in figure~\ref{fig:well-formed-types}
  21064. recursively inspects a type, making sure that each type variable has
  21065. been defined.
  21066. %
  21067. \fi}
  21068. \begin{figure}[tbp]
  21069. \begin{tcolorbox}[colback=white]
  21070. {\if\edition\racketEd
  21071. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21072. (define type-check-poly-class
  21073. (class type-check-Llambda-class
  21074. (super-new)
  21075. (inherit check-type-equal?)
  21076. (define/override (type-check-apply env e1 es)
  21077. (define-values (e^ ty) ((type-check-exp env) e1))
  21078. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  21079. ((type-check-exp env) e)))
  21080. (match ty
  21081. [`(,ty^* ... -> ,rt)
  21082. (for ([arg-ty ty*] [param-ty ty^*])
  21083. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  21084. (values e^ es^ rt)]
  21085. [`(All ,xs (,tys ... -> ,rt))
  21086. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21087. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  21088. (match_types env^^ param-ty arg-ty)))
  21089. (define targs
  21090. (for/list ([x xs])
  21091. (match (dict-ref env^^ x (lambda () #f))
  21092. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  21093. x (Apply e1 es))]
  21094. [ty ty])))
  21095. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  21096. [else (error 'type-check "expected a function, not ~a" ty)]))
  21097. (define/override ((type-check-exp env) e)
  21098. (match e
  21099. [(Lambda `([,xs : ,Ts] ...) rT body)
  21100. (for ([T Ts]) ((check_well_formed env) T))
  21101. ((check_well_formed env) rT)
  21102. ((super type-check-exp env) e)]
  21103. [(HasType e1 ty)
  21104. ((check_well_formed env) ty)
  21105. ((super type-check-exp env) e)]
  21106. [else ((super type-check-exp env) e)]))
  21107. (define/override ((type-check-def env) d)
  21108. (verbose 'type-check "poly/def" d)
  21109. (match d
  21110. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  21111. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  21112. (for ([p ps]) ((check_well_formed ts-env) p))
  21113. ((check_well_formed ts-env) rt)
  21114. (define new-env (append ts-env (map cons xs ps) env))
  21115. (define-values (body^ ty^) ((type-check-exp new-env) body))
  21116. (check-type-equal? ty^ rt body)
  21117. (Generic ts (Def f p:t* rt info body^))]
  21118. [else ((super type-check-def env) d)]))
  21119. (define/override (type-check-program p)
  21120. (match p
  21121. [(Program info body)
  21122. (type-check-program (ProgramDefsExp info '() body))]
  21123. [(ProgramDefsExp info ds body)
  21124. (define ds^ (combine-decls-defs ds))
  21125. (define new-env (for/list ([d ds^])
  21126. (cons (def-name d) (fun-def-type d))))
  21127. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  21128. (define-values (body^ ty) ((type-check-exp new-env) body))
  21129. (check-type-equal? ty 'Integer body)
  21130. (ProgramDefsExp info ds^^ body^)]))
  21131. ))
  21132. \end{lstlisting}
  21133. \fi}
  21134. {\if\edition\pythonEd\pythonColor
  21135. \begin{lstlisting}[basicstyle=\ttfamily\small]
  21136. def type_check_exp(self, e, env):
  21137. match e:
  21138. case Call(Name(f), args) if f in builtin_functions:
  21139. return super().type_check_exp(e, env)
  21140. case Call(func, args):
  21141. func_t = self.type_check_exp(func, env)
  21142. func.has_type = func_t
  21143. match func_t:
  21144. case AllType(ps, FunctionType(p_tys, rt)):
  21145. for arg in args:
  21146. arg.has_type = self.type_check_exp(arg, env)
  21147. arg_tys = [arg.has_type for arg in args]
  21148. deduced = {}
  21149. for (p, a) in zip(p_tys, arg_tys):
  21150. self.match_types(p, a, deduced, e)
  21151. return self.substitute_type(rt, deduced)
  21152. case _:
  21153. return super().type_check_exp(e, env)
  21154. case _:
  21155. return super().type_check_exp(e, env)
  21156. def type_check(self, p):
  21157. match p:
  21158. case Module(body):
  21159. env = {}
  21160. for s in body:
  21161. match s:
  21162. case FunctionDef(name, params, bod, dl, returns, comment):
  21163. params_t = [t for (x,t) in params]
  21164. ty_params = set()
  21165. for t in params_t:
  21166. ty_params |$\mid$|= self.generic_variables(t)
  21167. ty = FunctionType(params_t, returns)
  21168. if len(ty_params) > 0:
  21169. ty = AllType(list(ty_params), ty)
  21170. env[name] = ty
  21171. self.check_stmts(body, IntType(), env)
  21172. case _:
  21173. raise Exception('type_check: unexpected ' + repr(p))
  21174. \end{lstlisting}
  21175. \fi}
  21176. \end{tcolorbox}
  21177. \caption{Type checker for the \LangPoly{} language.}
  21178. \label{fig:type-check-Lpoly}
  21179. \end{figure}
  21180. \begin{figure}[tbp]
  21181. \begin{tcolorbox}[colback=white]
  21182. {\if\edition\racketEd
  21183. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21184. (define/override (type-equal? t1 t2)
  21185. (match* (t1 t2)
  21186. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21187. (define env (map cons xs ys))
  21188. (type-equal? (substitute_type env T1) T2)]
  21189. [(other wise)
  21190. (super type-equal? t1 t2)]))
  21191. (define/public (match_types env pt at)
  21192. (match* (pt at)
  21193. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21194. [('Void 'Void) env] [('Any 'Any) env]
  21195. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21196. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21197. (match_types env^ pt1 at1))]
  21198. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21199. (define env^ (match_types env prt art))
  21200. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21201. (match_types env^^ pt1 at1))]
  21202. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21203. (define env^ (append (map cons pxs axs) env))
  21204. (match_types env^ pt1 at1)]
  21205. [((? symbol? x) at)
  21206. (match (dict-ref env x (lambda () #f))
  21207. [#f (error 'type-check "undefined type variable ~a" x)]
  21208. ['Type (cons (cons x at) env)]
  21209. [t^ (check-type-equal? at t^ 'matching) env])]
  21210. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21211. (define/public (substitute_type env pt)
  21212. (match pt
  21213. ['Integer 'Integer] ['Boolean 'Boolean]
  21214. ['Void 'Void] ['Any 'Any]
  21215. [`(Vector ,ts ...)
  21216. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21217. [`(,ts ... -> ,rt)
  21218. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21219. [`(All ,xs ,t)
  21220. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21221. [(? symbol? x) (dict-ref env x)]
  21222. [else (error 'type-check "expected a type not ~a" pt)]))
  21223. (define/public (combine-decls-defs ds)
  21224. (match ds
  21225. ['() '()]
  21226. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21227. (unless (equal? name f)
  21228. (error 'type-check "name mismatch, ~a != ~a" name f))
  21229. (match type
  21230. [`(All ,xs (,ps ... -> ,rt))
  21231. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21232. (cons (Generic xs (Def name params^ rt info body))
  21233. (combine-decls-defs ds^))]
  21234. [`(,ps ... -> ,rt)
  21235. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21236. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21237. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21238. [`(,(Def f params rt info body) . ,ds^)
  21239. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21240. \end{lstlisting}
  21241. \fi}
  21242. {\if\edition\pythonEd\pythonColor
  21243. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21244. def match_types(self, param_ty, arg_ty, deduced, e):
  21245. match (param_ty, arg_ty):
  21246. case (GenericVar(id), _):
  21247. if id in deduced:
  21248. self.check_type_equal(arg_ty, deduced[id], e)
  21249. else:
  21250. deduced[id] = arg_ty
  21251. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21252. rename = {ap: GenericVar(p) for (ap,p) in zip(arg_ps, ps)}
  21253. new_arg_ty = self.substitute_type(arg_ty, rename)
  21254. self.match_types(ty, new_arg_ty, deduced, e)
  21255. case (TupleType(ps), TupleType(ts)):
  21256. for (p, a) in zip(ps, ts):
  21257. self.match_types(p, a, deduced, e)
  21258. case (ListType(p), ListType(a)):
  21259. self.match_types(p, a, deduced, e)
  21260. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21261. for (pp, ap) in zip(pps, aps):
  21262. self.match_types(pp, ap, deduced, e)
  21263. self.match_types(prt, art, deduced, e)
  21264. case (IntType(), IntType()):
  21265. pass
  21266. case (BoolType(), BoolType()):
  21267. pass
  21268. case _:
  21269. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21270. def substitute_type(self, ty, var_map):
  21271. match ty:
  21272. case GenericVar(id):
  21273. return var_map[id]
  21274. case AllType(ps, ty):
  21275. new_map = copy.deepcopy(var_map)
  21276. for p in ps:
  21277. new_map[p] = GenericVar(p)
  21278. return AllType(ps, self.substitute_type(ty, new_map))
  21279. case TupleType(ts):
  21280. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21281. case ListType(ty):
  21282. return ListType(self.substitute_type(ty, var_map))
  21283. case FunctionType(pts, rt):
  21284. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21285. self.substitute_type(rt, var_map))
  21286. case IntType():
  21287. return IntType()
  21288. case BoolType():
  21289. return BoolType()
  21290. case _:
  21291. raise Exception('substitute_type: unexpected ' + repr(ty))
  21292. def check_type_equal(self, t1, t2, e):
  21293. match (t1, t2):
  21294. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21295. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21296. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21297. case (_, _):
  21298. return super().check_type_equal(t1, t2, e)
  21299. \end{lstlisting}
  21300. \fi}
  21301. \end{tcolorbox}
  21302. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21303. \label{fig:type-check-Lpoly-aux}
  21304. \end{figure}
  21305. {\if\edition\racketEd
  21306. \begin{figure}[tbp]
  21307. \begin{tcolorbox}[colback=white]
  21308. \begin{lstlisting}
  21309. (define/public ((check_well_formed env) ty)
  21310. (match ty
  21311. ['Integer (void)]
  21312. ['Boolean (void)]
  21313. ['Void (void)]
  21314. [(? symbol? a)
  21315. (match (dict-ref env a (lambda () #f))
  21316. ['Type (void)]
  21317. [else (error 'type-check "undefined type variable ~a" a)])]
  21318. [`(Vector ,ts ...)
  21319. (for ([t ts]) ((check_well_formed env) t))]
  21320. [`(,ts ... -> ,t)
  21321. (for ([t ts]) ((check_well_formed env) t))
  21322. ((check_well_formed env) t)]
  21323. [`(All ,xs ,t)
  21324. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21325. ((check_well_formed env^) t)]
  21326. [else (error 'type-check "unrecognized type ~a" ty)]))
  21327. \end{lstlisting}
  21328. \end{tcolorbox}
  21329. \caption{Well-formed types.}
  21330. \label{fig:well-formed-types}
  21331. \end{figure}
  21332. \fi}
  21333. % TODO: interpreter for R'_10
  21334. \clearpage
  21335. \section{Compiling Generics}
  21336. \label{sec:compiling-poly}
  21337. Broadly speaking, there are four approaches to compiling generics, as
  21338. follows:
  21339. \begin{description}
  21340. \item[Monomorphization] generates a different version of a generic
  21341. function for each set of type arguments with which it is used,
  21342. producing type-specialized code. This approach results in the most
  21343. efficient code but requires whole-program compilation (no separate
  21344. compilation) and may increase code size. Unfortunately,
  21345. monomorphization is incompatible with first-class generics because
  21346. it is not always possible to determine which generic functions are
  21347. used with which type arguments during compilation. (It can be done
  21348. at runtime with just-in-time compilation.) Monomorphization is
  21349. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21350. generic functions in NESL~\citep{Blelloch:1993aa} and
  21351. ML~\citep{Weeks:2006aa}.
  21352. \item[Uniform representation] generates one version of each generic
  21353. function and requires all values to have a common \emph{boxed} format,
  21354. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21355. generic and monomorphic code is compiled similarly to code in a
  21356. dynamically typed language (like \LangDyn{}), in which primitive
  21357. operators require their arguments to be projected from \CANYTY{} and
  21358. their results to be injected into \CANYTY{}. (In object-oriented
  21359. languages, the projection is accomplished via virtual method
  21360. dispatch.) The uniform representation approach is compatible with
  21361. separate compilation and with first-class generics. However, it
  21362. produces the least efficient code because it introduces overhead in
  21363. the entire program. This approach is used in
  21364. Java~\citep{Bracha:1998fk},
  21365. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21366. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21367. \item[Mixed representation] generates one version of each generic
  21368. function, using a boxed representation for type variables. However,
  21369. monomorphic code is compiled as usual (as in \LangLam{}), and
  21370. conversions are performed at the boundaries between monomorphic code
  21371. and polymorphic code (for example, when a generic function is instantiated
  21372. and called). This approach is compatible with separate compilation
  21373. and first-class generics and maintains efficiency in monomorphic
  21374. code. The trade-off is increased overhead at the boundary between
  21375. monomorphic and generic code. This approach is used in
  21376. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21377. Java 5 with the addition of autoboxing.
  21378. \item[Type passing] uses the unboxed representation in both
  21379. monomorphic and generic code. Each generic function is compiled to a
  21380. single function with extra parameters that describe the type
  21381. arguments. The type information is used by the generated code to
  21382. determine how to access the unboxed values at runtime. This approach is
  21383. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21384. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21385. compilation and first-class generics and maintains the
  21386. efficiency for monomorphic code. There is runtime overhead in
  21387. polymorphic code from dispatching on type information.
  21388. \end{description}
  21389. In this chapter we use the mixed representation approach, partly
  21390. because of its favorable attributes and partly because it is
  21391. straightforward to implement using the tools that we have already
  21392. built to support gradual typing. The work of compiling generic
  21393. functions is performed in two passes, \code{resolve} and
  21394. \code{erase\_types}, that we discuss next. The output of
  21395. \code{erase\_types} is \LangCast{}
  21396. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21397. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21398. \section{Resolve Instantiation}
  21399. \label{sec:generic-resolve}
  21400. Recall that the type checker for \LangPoly{} deduces the type
  21401. arguments at call sites to a generic function. The purpose of the
  21402. \code{resolve} pass is to turn this implicit instantiation into an
  21403. explicit one, by adding \code{inst} nodes to the syntax of the
  21404. intermediate language. An \code{inst} node records the mapping of
  21405. type parameters to type arguments. The semantics of the \code{inst}
  21406. node is to instantiate the result of its first argument, a generic
  21407. function, to produce a monomorphic function. However, because the
  21408. interpreter never analyzes type annotations, instantiation can be a
  21409. no-op and simply return the generic function.
  21410. %
  21411. The output language of the \code{resolve} pass is \LangInst{},
  21412. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21413. {\if\edition\racketEd
  21414. The \code{resolve} pass combines the type declaration and polymorphic
  21415. function into a single definition, using the \code{Poly} form, to make
  21416. polymorphic functions more convenient to process in the next pass of the
  21417. compiler.
  21418. \fi}
  21419. \newcommand{\LinstASTRacket}{
  21420. \begin{array}{lcl}
  21421. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21422. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21423. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21424. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21425. \end{array}
  21426. }
  21427. \newcommand{\LinstASTPython}{
  21428. \begin{array}{lcl}
  21429. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21430. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21431. \end{array}
  21432. }
  21433. \begin{figure}[tp]
  21434. \centering
  21435. \begin{tcolorbox}[colback=white]
  21436. \small
  21437. {\if\edition\racketEd
  21438. \[
  21439. \begin{array}{l}
  21440. \gray{\LintOpAST} \\ \hline
  21441. \gray{\LvarASTRacket{}} \\ \hline
  21442. \gray{\LifASTRacket{}} \\ \hline
  21443. \gray{\LwhileASTRacket{}} \\ \hline
  21444. \gray{\LtupASTRacket{}} \\ \hline
  21445. \gray{\LfunASTRacket} \\ \hline
  21446. \gray{\LlambdaASTRacket} \\ \hline
  21447. \LinstASTRacket \\
  21448. \begin{array}{lcl}
  21449. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21450. \end{array}
  21451. \end{array}
  21452. \]
  21453. \fi}
  21454. {\if\edition\pythonEd\pythonColor
  21455. \[
  21456. \begin{array}{l}
  21457. \gray{\LintASTPython} \\ \hline
  21458. \gray{\LvarASTPython{}} \\ \hline
  21459. \gray{\LifASTPython{}} \\ \hline
  21460. \gray{\LwhileASTPython{}} \\ \hline
  21461. \gray{\LtupASTPython{}} \\ \hline
  21462. \gray{\LfunASTPython} \\ \hline
  21463. \gray{\LlambdaASTPython} \\ \hline
  21464. \LinstASTPython \\
  21465. \begin{array}{lcl}
  21466. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21467. \end{array}
  21468. \end{array}
  21469. \]
  21470. \fi}
  21471. \end{tcolorbox}
  21472. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21473. (figure~\ref{fig:Llam-syntax}).}
  21474. \label{fig:Lpoly-prime-syntax}
  21475. \index{subject}{Linst@\LangInst{} abstract syntax}
  21476. \end{figure}
  21477. The output of the \code{resolve} pass on the generic \code{map}
  21478. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21479. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21480. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21481. \begin{figure}[tbp]
  21482. % poly_test_2.rkt
  21483. \begin{tcolorbox}[colback=white]
  21484. {\if\edition\racketEd
  21485. \begin{lstlisting}
  21486. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21487. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21488. (define (inc [x : Integer]) : Integer (+ x 1))
  21489. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21490. (Integer))
  21491. inc (vector 0 41)) 1)
  21492. \end{lstlisting}
  21493. \fi}
  21494. {\if\edition\pythonEd\pythonColor
  21495. \begin{lstlisting}
  21496. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21497. return (f(tup[0]), f(tup[1]))
  21498. def add1(x : int) -> int:
  21499. return x + 1
  21500. t = inst(map, {T: int})(add1, (0, 41))
  21501. print(t[1])
  21502. \end{lstlisting}
  21503. \fi}
  21504. \end{tcolorbox}
  21505. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21506. \label{fig:map-resolve}
  21507. \end{figure}
  21508. \section{Erase Generic Types}
  21509. \label{sec:erase_types}
  21510. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21511. represent type variables. For example, figure~\ref{fig:map-erase}
  21512. shows the output of the \code{erase\_types} pass on the generic
  21513. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21514. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21515. \code{All} types are removed from the type of \code{map}.
  21516. \begin{figure}[tbp]
  21517. \begin{tcolorbox}[colback=white]
  21518. {\if\edition\racketEd
  21519. \begin{lstlisting}
  21520. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21521. : (Vector Any Any)
  21522. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21523. (define (inc [x : Integer]) : Integer (+ x 1))
  21524. (vector-ref ((cast map
  21525. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21526. ((Integer -> Integer) (Vector Integer Integer)
  21527. -> (Vector Integer Integer)))
  21528. inc (vector 0 41)) 1)
  21529. \end{lstlisting}
  21530. \fi}
  21531. {\if\edition\pythonEd\pythonColor
  21532. \begin{lstlisting}
  21533. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21534. return (f(tup[0]), f(tup[1]))
  21535. def add1(x : int) -> int:
  21536. return (x + 1)
  21537. def main() -> int:
  21538. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21539. print(t[1])
  21540. return 0
  21541. \end{lstlisting}
  21542. {\small
  21543. where\\
  21544. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21545. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21546. }
  21547. \fi}
  21548. \end{tcolorbox}
  21549. \caption{The generic \code{map} example after type erasure.}
  21550. \label{fig:map-erase}
  21551. \end{figure}
  21552. This process of type erasure creates a challenge at points of
  21553. instantiation. For example, consider the instantiation of
  21554. \code{map} shown in figure~\ref{fig:map-resolve}.
  21555. The type of \code{map} is
  21556. %
  21557. {\if\edition\racketEd
  21558. \begin{lstlisting}
  21559. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21560. \end{lstlisting}
  21561. \fi}
  21562. {\if\edition\pythonEd\pythonColor
  21563. \begin{lstlisting}
  21564. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21565. \end{lstlisting}
  21566. \fi}
  21567. %
  21568. \noindent and it is instantiated to
  21569. %
  21570. {\if\edition\racketEd
  21571. \begin{lstlisting}
  21572. ((Integer -> Integer) (Vector Integer Integer)
  21573. -> (Vector Integer Integer))
  21574. \end{lstlisting}
  21575. \fi}
  21576. {\if\edition\pythonEd\pythonColor
  21577. \begin{lstlisting}
  21578. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21579. \end{lstlisting}
  21580. \fi}
  21581. %
  21582. \noindent After erasure, the type of \code{map} is
  21583. %
  21584. {\if\edition\racketEd
  21585. \begin{lstlisting}
  21586. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21587. \end{lstlisting}
  21588. \fi}
  21589. {\if\edition\pythonEd\pythonColor
  21590. \begin{lstlisting}
  21591. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21592. \end{lstlisting}
  21593. \fi}
  21594. %
  21595. \noindent but we need to convert it to the instantiated type. This is
  21596. easy to do in the language \LangCast{} with a single \code{cast}. In
  21597. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21598. \code{map} has been compiled to a \code{cast} from the type of
  21599. \code{map} to the instantiated type. The source and the target type of
  21600. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21601. is the case because both the source and target are obtained from the
  21602. same generic type of \code{map}, replacing the type parameters with
  21603. \CANYTY{} in the former and with the deduced type arguments in the
  21604. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21605. To implement the \code{erase\_types} pass, we first recommend defining
  21606. a recursive function that translates types, named
  21607. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21608. follows.
  21609. %
  21610. {\if\edition\racketEd
  21611. \begin{lstlisting}
  21612. |$T$|
  21613. |$\Rightarrow$|
  21614. Any
  21615. \end{lstlisting}
  21616. \fi}
  21617. {\if\edition\pythonEd\pythonColor
  21618. \begin{lstlisting}
  21619. GenericVar(|$T$|)
  21620. |$\Rightarrow$|
  21621. Any
  21622. \end{lstlisting}
  21623. \fi}
  21624. %
  21625. \noindent The \code{erase\_type} function also removes the generic
  21626. \code{All} types.
  21627. %
  21628. {\if\edition\racketEd
  21629. \begin{lstlisting}
  21630. (All |$xs$| |$T_1$|)
  21631. |$\Rightarrow$|
  21632. |$T'_1$|
  21633. \end{lstlisting}
  21634. \fi}
  21635. {\if\edition\pythonEd\pythonColor
  21636. \begin{lstlisting}
  21637. AllType(|$xs$|, |$T_1$|)
  21638. |$\Rightarrow$|
  21639. |$T'_1$|
  21640. \end{lstlisting}
  21641. \fi}
  21642. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21643. $T_1$.
  21644. %
  21645. In this compiler pass, apply the \code{erase\_type} function to all
  21646. the type annotations in the program.
  21647. Regarding the translation of expressions, the case for \code{Inst} is
  21648. the interesting one. We translate it into a \code{Cast}, as shown
  21649. next.
  21650. The type of the subexpression $e$ is a generic type of the form
  21651. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21652. The source type of the cast is the erasure of $T$, the type $T_s$.
  21653. %
  21654. {\if\edition\racketEd
  21655. %
  21656. The target type $T_t$ is the result of substituting the argument types
  21657. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21658. erasure.
  21659. %
  21660. \begin{lstlisting}
  21661. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21662. |$\Rightarrow$|
  21663. (Cast |$e'$| |$T_s$| |$T_t$|)
  21664. \end{lstlisting}
  21665. %
  21666. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21667. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21668. \fi}
  21669. {\if\edition\pythonEd\pythonColor
  21670. %
  21671. The target type $T_t$ is the result of substituting the deduced
  21672. argument types $d$ in $T$ and then performing type erasure.
  21673. %
  21674. \begin{lstlisting}
  21675. Inst(|$e$|, |$d$|)
  21676. |$\Rightarrow$|
  21677. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21678. \end{lstlisting}
  21679. %
  21680. where
  21681. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21682. \fi}
  21683. Finally, each generic function is translated to a regular
  21684. function in which type erasure has been applied to all the type
  21685. annotations and the body.
  21686. %% \begin{lstlisting}
  21687. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21688. %% |$\Rightarrow$|
  21689. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21690. %% \end{lstlisting}
  21691. \begin{exercise}\normalfont\normalsize
  21692. Implement a compiler for the polymorphic language \LangPoly{} by
  21693. extending and adapting your compiler for \LangGrad{}. Create six new
  21694. test programs that use polymorphic functions. Some of them should
  21695. make use of first-class generics.
  21696. \end{exercise}
  21697. \begin{figure}[tbp]
  21698. \begin{tcolorbox}[colback=white]
  21699. {\if\edition\racketEd
  21700. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21701. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21702. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21703. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21704. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21705. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21706. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21707. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21708. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21709. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21710. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21711. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21712. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21713. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21714. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21715. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21716. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21717. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21718. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21719. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21720. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21721. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21722. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21723. \path[->,bend left=15] (Lpoly) edge [above] node
  21724. {\ttfamily\footnotesize resolve} (Lpolyp);
  21725. \path[->,bend left=15] (Lpolyp) edge [above] node
  21726. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21727. \path[->,bend left=15] (Lgradualp) edge [above] node
  21728. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21729. \path[->,bend left=15] (Llambdapp) edge [left] node
  21730. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21731. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21732. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21733. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21734. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21735. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21736. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21737. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21738. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21739. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21740. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21741. \path[->,bend left=15] (F1-1) edge [above] node
  21742. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21743. \path[->,bend left=15] (F1-2) edge [above] node
  21744. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21745. \path[->,bend left=15] (F1-3) edge [left] node
  21746. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21747. \path[->,bend left=15] (F1-4) edge [below] node
  21748. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21749. \path[->,bend right=15] (F1-5) edge [above] node
  21750. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21751. \path[->,bend right=15] (F1-6) edge [above] node
  21752. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21753. \path[->,bend right=15] (C3-2) edge [right] node
  21754. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21755. \path[->,bend right=15] (x86-2) edge [right] node
  21756. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21757. \path[->,bend right=15] (x86-2-1) edge [below] node
  21758. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21759. \path[->,bend right=15] (x86-2-2) edge [right] node
  21760. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21761. \path[->,bend left=15] (x86-3) edge [above] node
  21762. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21763. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21764. \end{tikzpicture}
  21765. \fi}
  21766. {\if\edition\pythonEd\pythonColor
  21767. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21768. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21769. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21770. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21771. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21772. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21773. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21774. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21775. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21776. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21777. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21778. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21779. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21780. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21781. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21782. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21783. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21784. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21785. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21786. \path[->,bend left=15] (Lgradual) edge [above] node
  21787. {\ttfamily\footnotesize shrink} (Lgradual2);
  21788. \path[->,bend left=15] (Lgradual2) edge [above] node
  21789. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21790. \path[->,bend left=15] (Lgradual3) edge [above] node
  21791. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21792. \path[->,bend left=15] (Lgradual4) edge [left] node
  21793. {\ttfamily\footnotesize resolve} (Lgradualr);
  21794. \path[->,bend left=15] (Lgradualr) edge [below] node
  21795. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21796. \path[->,bend right=15] (Llambdapp) edge [above] node
  21797. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21798. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21799. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21800. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21801. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21802. \path[->,bend right=15] (F1-1) edge [below] node
  21803. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21804. \path[->,bend right=15] (F1-2) edge [below] node
  21805. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21806. \path[->,bend left=15] (F1-3) edge [above] node
  21807. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21808. \path[->,bend left=15] (F1-5) edge [left] node
  21809. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21810. \path[->,bend left=5] (F1-6) edge [below] node
  21811. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21812. \path[->,bend right=15] (C3-2) edge [right] node
  21813. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21814. \path[->,bend right=15] (x86-2) edge [below] node
  21815. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21816. \path[->,bend right=15] (x86-3) edge [below] node
  21817. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21818. \path[->,bend left=15] (x86-4) edge [above] node
  21819. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21820. \end{tikzpicture}
  21821. \fi}
  21822. \end{tcolorbox}
  21823. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21824. \label{fig:Lpoly-passes}
  21825. \end{figure}
  21826. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21827. needed to compile \LangPoly{}.
  21828. % TODO: challenge problem: specialization of instantiations
  21829. % Further Reading
  21830. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21831. \clearpage
  21832. \appendix
  21833. \chapter{Appendix}
  21834. \setcounter{footnote}{0}
  21835. {\if\edition\racketEd
  21836. \section{Interpreters}
  21837. \label{appendix:interp}
  21838. \index{subject}{interpreter}
  21839. We provide interpreters for each of the source languages \LangInt{},
  21840. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21841. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21842. intermediate languages \LangCVar{} and \LangCIf{} are in
  21843. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21844. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21845. \key{interp.rkt} file.
  21846. \section{Utility Functions}
  21847. \label{appendix:utilities}
  21848. The utility functions described in this section are in the
  21849. \key{utilities.rkt} file of the support code.
  21850. \paragraph{\code{interp-tests}}
  21851. This function runs the compiler passes and the interpreters on each of
  21852. the specified tests to check whether each pass is correct. The
  21853. \key{interp-tests} function has the following parameters:
  21854. \begin{description}
  21855. \item[name (a string)] A name to identify the compiler.
  21856. \item[typechecker] A function of exactly one argument that either
  21857. raises an error using the \code{error} function when it encounters a
  21858. type error, or returns \code{\#f} when it encounters a type
  21859. error. If there is no type error, the type checker returns the
  21860. program.
  21861. \item[passes] A list with one entry per pass. An entry is a list
  21862. consisting of four things:
  21863. \begin{enumerate}
  21864. \item a string giving the name of the pass;
  21865. \item the function that implements the pass (a translator from AST
  21866. to AST);
  21867. \item a function that implements the interpreter (a function from
  21868. AST to result value) for the output language; and,
  21869. \item a type checker for the output language. Type checkers for
  21870. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21871. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21872. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21873. type checker entry is optional. The support code does not provide
  21874. type checkers for the x86 languages.
  21875. \end{enumerate}
  21876. \item[source-interp] An interpreter for the source language. The
  21877. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21878. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21879. \item[tests] A list of test numbers that specifies which tests to
  21880. run (explained next).
  21881. \end{description}
  21882. %
  21883. The \key{interp-tests} function assumes that the subdirectory
  21884. \key{tests} has a collection of Racket programs whose names all start
  21885. with the family name, followed by an underscore and then the test
  21886. number, and ending with the file extension \key{.rkt}. Also, for each test
  21887. program that calls \code{read} one or more times, there is a file with
  21888. the same name except that the file extension is \key{.in}, which
  21889. provides the input for the Racket program. If the test program is
  21890. expected to fail type checking, then there should be an empty file of
  21891. the same name with extension \key{.tyerr}.
  21892. \paragraph{\code{compiler-tests}}
  21893. This function runs the compiler passes to generate x86 (a \key{.s}
  21894. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21895. It runs the machine code and checks that the output is $42$. The
  21896. parameters to the \code{compiler-tests} function are similar to those
  21897. of the \code{interp-tests} function, and they consist of
  21898. \begin{itemize}
  21899. \item a compiler name (a string),
  21900. \item a type checker,
  21901. \item description of the passes,
  21902. \item name of a test-family, and
  21903. \item a list of test numbers.
  21904. \end{itemize}
  21905. \paragraph{\code{compile-file}}
  21906. This function takes a description of the compiler passes (see the
  21907. comment for \key{interp-tests}) and returns a function that, given a
  21908. program file name (a string ending in \key{.rkt}), applies all the
  21909. passes and writes the output to a file whose name is the same as the
  21910. program file name with extension \key{.rkt} replaced by \key{.s}.
  21911. \paragraph{\code{read-program}}
  21912. This function takes a file path and parses that file (it must be a
  21913. Racket program) into an abstract syntax tree.
  21914. \paragraph{\code{parse-program}}
  21915. This function takes an S-expression representation of an abstract
  21916. syntax tree and converts it into the struct-based representation.
  21917. \paragraph{\code{assert}}
  21918. This function takes two parameters, a string (\code{msg}) and Boolean
  21919. (\code{bool}), and displays the message \key{msg} if the Boolean
  21920. \key{bool} is false.
  21921. \paragraph{\code{lookup}}
  21922. % remove discussion of lookup? -Jeremy
  21923. This function takes a key and an alist and returns the first value that is
  21924. associated with the given key, if there is one. If not, an error is
  21925. triggered. The alist may contain both immutable pairs (built with
  21926. \key{cons}) and mutable pairs (built with \key{mcons}).
  21927. %The \key{map2} function ...
  21928. \fi} %\racketEd
  21929. \section{x86 Instruction Set Quick Reference}
  21930. \label{sec:x86-quick-reference}
  21931. \index{subject}{x86}
  21932. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21933. do. We write $A \to B$ to mean that the value of $A$ is written into
  21934. location $B$. Address offsets are given in bytes. The instruction
  21935. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21936. registers (such as \code{\%rax}), or memory references (such as
  21937. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21938. reference per instruction. Other operands must be immediates or
  21939. registers.
  21940. \begin{table}[tbp]
  21941. \captionabove{Quick reference for the x86 instructions used in this book.}
  21942. \label{tab:x86-instr}
  21943. \centering
  21944. \begin{tabular}{l|l}
  21945. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21946. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21947. \texttt{negq} $A$ & $- A \to A$ \\
  21948. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21949. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21950. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21951. \texttt{callq} \texttt{*}$A$ & Pushes the return address and jumps to the address in $A$. \\
  21952. \texttt{retq} & Pops the return address and jumps to it. \\
  21953. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21954. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21955. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21956. \texttt{cmpq} $A$, $B$ & \multirow{2}{3.7in}{Compare $A$ and $B$ and set the flag register ($B$ must not be an immediate).} \\
  21957. & \\
  21958. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21959. matches the condition code of the instruction; otherwise go to the
  21960. next instructions. The condition codes are \key{e} for \emph{equal},
  21961. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21962. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21963. \texttt{jl} $L$ & \\
  21964. \texttt{jle} $L$ & \\
  21965. \texttt{jg} $L$ & \\
  21966. \texttt{jge} $L$ & \\
  21967. \texttt{jmp} $L$ & Jump to label $L$. \\
  21968. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21969. \texttt{movzbq} $A$, $B$ &
  21970. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21971. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21972. and the extra bytes of $B$ are set to zero.} \\
  21973. & \\
  21974. & \\
  21975. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21976. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21977. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21978. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21979. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21980. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21981. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21982. description of the condition codes. $A$ must be a single byte register
  21983. (e.g., \texttt{al} or \texttt{cl}).} \\
  21984. \texttt{setl} $A$ & \\
  21985. \texttt{setle} $A$ & \\
  21986. \texttt{setg} $A$ & \\
  21987. \texttt{setge} $A$ &
  21988. \end{tabular}
  21989. \end{table}
  21990. \backmatter
  21991. \addtocontents{toc}{\vspace{11pt}}
  21992. \cleardoublepage % needed for right page number in TOC for References
  21993. %% \nocite{*} is a way to get all the entries in the .bib file to
  21994. %% print in the bibliography:
  21995. \nocite{*}\let\bibname\refname
  21996. \addcontentsline{toc}{fmbm}{\refname}
  21997. \printbibliography
  21998. %\printindex{authors}{Author Index}
  21999. \printindex{subject}{Index}
  22000. \end{document}
  22001. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  22002. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  22003. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  22004. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  22005. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  22006. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  22007. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  22008. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  22009. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  22010. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  22011. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  22012. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  22013. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  22014. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  22015. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  22016. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  22017. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  22018. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  22019. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  22020. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  22021. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  22022. % LocalWords: eq prog rcl definitional Evaluator os Earley's mul
  22023. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  22024. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  22025. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  22026. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  22027. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  22028. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  22029. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  22030. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  22031. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  22032. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  22033. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  22034. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  22035. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  22036. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  22037. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  22038. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  22039. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  22040. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  22041. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  22042. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  22043. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  22044. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  22045. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  22046. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  22047. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  22048. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  22049. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  22050. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  22051. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  22052. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  22053. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  22054. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  22055. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  22056. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  22057. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  22058. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  22059. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  22060. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  22061. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  22062. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  22063. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  22064. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  22065. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  22066. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  22067. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  22068. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  22069. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  22070. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  22071. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  22072. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  22073. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  22074. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  22075. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  22076. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  22077. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  22078. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  22079. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  22080. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  22081. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  22082. % LocalWords: pseudocode underapproximation underapproximations LALR
  22083. % LocalWords: semilattices overapproximate incrementing Earley docs
  22084. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  22085. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  22086. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  22087. % LocalWords: LC partialevaluation pythonEd TOC TrappedError