book.tex 820 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  32. %% For multiple indices:
  33. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  34. \makeindex{subject}
  35. %\makeindex{authors}
  36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  37. \if\edition\racketEd
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  42. deletekeywords={read,mapping,vector},
  43. escapechar=|,
  44. columns=flexible,
  45. %moredelim=[is][\color{red}]{~}{~},
  46. showstringspaces=false
  47. }
  48. \fi
  49. \if\edition\pythonEd
  50. \lstset{%
  51. language=Python,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={match,case,bool,int,let},
  54. deletekeywords={},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. %%% Any shortcut own defined macros place here
  62. %% sample of author macro:
  63. \input{defs}
  64. \newtheorem{exercise}[theorem]{Exercise}
  65. \numberwithin{theorem}{chapter}
  66. \numberwithin{definition}{chapter}
  67. \numberwithin{equation}{chapter}
  68. % Adjusted settings
  69. \setlength{\columnsep}{4pt}
  70. %% \begingroup
  71. %% \setlength{\intextsep}{0pt}%
  72. %% \setlength{\columnsep}{0pt}%
  73. %% \begin{wrapfigure}{r}{0.5\textwidth}
  74. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  75. %% \caption{Basic layout}
  76. %% \end{wrapfigure}
  77. %% \lipsum[1]
  78. %% \endgroup
  79. \newbox\oiintbox
  80. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  81. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  82. \def\oiint{\copy\oiintbox}
  83. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  84. %\usepackage{showframe}
  85. \def\ShowFrameLinethickness{0.125pt}
  86. \addbibresource{book.bib}
  87. \if\edition\pythonEd
  88. \addbibresource{python.bib}
  89. \fi
  90. \begin{document}
  91. \frontmatter
  92. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  93. \HalfTitle{Essentials of Compilation}
  94. \halftitlepage
  95. \clearemptydoublepage
  96. \Title{Essentials of Compilation}
  97. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  98. %\edition{First Edition}
  99. \BookAuthor{Jeremy G. Siek}
  100. \imprint{The MIT Press\\
  101. Cambridge, Massachusetts\\
  102. London, England}
  103. \begin{copyrightpage}
  104. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  105. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  106. Subject to such license, all rights are reserved. \\[2ex]
  107. \includegraphics{CCBY-logo}
  108. The MIT Press would like to thank the anonymous peer reviewers who
  109. provided comments on drafts of this book. The generous work of
  110. academic experts is essential for establishing the authority and
  111. quality of our publications. We acknowledge with gratitude the
  112. contributions of these otherwise uncredited readers.
  113. This book was set in Times LT Std Roman by the author. Printed and
  114. bound in the United States of America.
  115. Library of Congress Cataloging-in-Publication Data is available.
  116. ISBN:
  117. 10 9 8 7 6 5 4 3 2 1
  118. %% Jeremy G. Siek. Available for free viewing
  119. %% or personal downloading under the
  120. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  121. %% license.
  122. %% Copyright in this monograph has been licensed exclusively to The MIT
  123. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  124. %% version to the public in 2022. All inquiries regarding rights should
  125. %% be addressed to The MIT Press, Rights and Permissions Department.
  126. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  127. %% All rights reserved. No part of this book may be reproduced in any
  128. %% form by any electronic or mechanical means (including photocopying,
  129. %% recording, or information storage and retrieval) without permission in
  130. %% writing from the publisher.
  131. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  132. %% United States of America.
  133. %% Library of Congress Cataloging-in-Publication Data is available.
  134. %% ISBN:
  135. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  136. \end{copyrightpage}
  137. \dedication{This book is dedicated to Katie, my partner in everything,
  138. my children, who grew up during the writing of this book, and the
  139. programming language students at Indiana University, whose
  140. thoughtful questions made this a better book.}
  141. %% \begin{epigraphpage}
  142. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  143. %% \textit{Book Name if any}}
  144. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  145. %% \end{epigraphpage}
  146. \tableofcontents
  147. %\listoffigures
  148. %\listoftables
  149. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  150. \chapter*{Preface}
  151. \addcontentsline{toc}{fmbm}{Preface}
  152. There is a magical moment when a programmer presses the run button
  153. and the software begins to execute. Somehow a program written in a
  154. high-level language is running on a computer that is capable only of
  155. shuffling bits. Here we reveal the wizardry that makes that moment
  156. possible. Beginning with the groundbreaking work of Backus and
  157. colleagues in the 1950s, computer scientists developed techniques for
  158. constructing programs called \emph{compilers} that automatically
  159. translate high-level programs into machine code.
  160. We take you on a journey through constructing your own compiler for a
  161. small but powerful language. Along the way we explain the essential
  162. concepts, algorithms, and data structures that underlie compilers. We
  163. develop your understanding of how programs are mapped onto computer
  164. hardware, which is helpful in reasoning about properties at the
  165. junction of hardware and software, such as execution time, software
  166. errors, and security vulnerabilities. For those interested in
  167. pursuing compiler construction as a career, our goal is to provide a
  168. stepping-stone to advanced topics such as just-in-time compilation,
  169. program analysis, and program optimization. For those interested in
  170. designing and implementing programming languages, we connect language
  171. design choices to their impact on the compiler and the generated code.
  172. A compiler is typically organized as a sequence of stages that
  173. progressively translate a program to the code that runs on
  174. hardware. We take this approach to the extreme by partitioning our
  175. compiler into a large number of \emph{nanopasses}, each of which
  176. performs a single task. This enables the testing of each pass in
  177. isolation and focuses our attention, making the compiler far easier to
  178. understand.
  179. The most familiar approach to describing compilers is to dedicate each
  180. chapter to one pass. The problem with that approach is that it
  181. obfuscates how language features motivate design choices in a
  182. compiler. We instead take an \emph{incremental} approach in which we
  183. build a complete compiler in each chapter, starting with a small input
  184. language that includes only arithmetic and variables. We add new
  185. language features in subsequent chapters, extending the compiler as
  186. necessary.
  187. Our choice of language features is designed to elicit fundamental
  188. concepts and algorithms used in compilers.
  189. \begin{itemize}
  190. \item We begin with integer arithmetic and local variables in
  191. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  192. the fundamental tools of compiler construction: \emph{abstract
  193. syntax trees} and \emph{recursive functions}.
  194. {\if\edition\pythonEd
  195. \item In Chapter~\ref{ch:parsing} we learn how to use the Lark
  196. parser framework to create a parser for the language of integer
  197. arithmetic and local variables. We learn about the parsing
  198. algorithms inside Lark, including Earley and LALR(1).
  199. %
  200. \fi}
  201. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  202. \emph{graph coloring} to assign variables to machine registers.
  203. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  204. motivates an elegant recursive algorithm for translating them into
  205. conditional \code{goto} statements.
  206. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  207. variables}. This elicits the need for \emph{dataflow
  208. analysis} in the register allocator.
  209. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  210. \emph{garbage collection}.
  211. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  212. without lexical scoping, similar to functions in the C programming
  213. language~\citep{Kernighan:1988nx}. The reader learns about the
  214. procedure call stack and \emph{calling conventions} and how they interact
  215. with register allocation and garbage collection. The chapter also
  216. describes how to generate efficient tail calls.
  217. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  218. scoping, that is, \emph{lambda} expressions. The reader learns about
  219. \emph{closure conversion}, in which lambdas are translated into a
  220. combination of functions and tuples.
  221. % Chapter about classes and objects?
  222. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  223. point the input languages are statically typed. The reader extends
  224. the statically typed language with an \code{Any} type that serves
  225. as a target for compiling the dynamically typed language.
  226. %% {\if\edition\pythonEd
  227. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  228. %% \emph{classes}.
  229. %% \fi}
  230. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  231. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  232. in which different regions of a program may be static or dynamically
  233. typed. The reader implements runtime support for \emph{proxies} that
  234. allow values to safely move between regions.
  235. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  236. leveraging the \code{Any} type and type casts developed in chapters
  237. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  238. \end{itemize}
  239. There are many language features that we do not include. Our choices
  240. balance the incidental complexity of a feature versus the fundamental
  241. concepts that it exposes. For example, we include tuples and not
  242. records because although they both elicit the study of heap allocation and
  243. garbage collection, records come with more incidental complexity.
  244. Since 2009, drafts of this book have served as the textbook for
  245. sixteen week compiler courses for upper-level undergraduates and
  246. first-year graduate students at the University of Colorado and Indiana
  247. University.
  248. %
  249. Students come into the course having learned the basics of
  250. programming, data structures and algorithms, and discrete
  251. mathematics.
  252. %
  253. At the beginning of the course, students form groups of two to four
  254. people. The groups complete approximately one chapter every two
  255. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  256. according to the students interests while respecting the dependencies
  257. between chapters shown in
  258. Figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  259. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  260. implementation of efficient tail calls.
  261. %
  262. The last two weeks of the course involve a final project in which
  263. students design and implement a compiler extension of their choosing.
  264. The last few chapters can be used in support of these projects. Many
  265. chapters include a challenge problem that we assign to the graduate
  266. students. For compiler courses at universities on the quarter system
  267. (about ten weeks in length), we recommend completing the course
  268. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  269. some scaffolding code to the students for each compiler pass.
  270. %
  271. The course can be adapted to emphasize functional languages by
  272. skipping chapter~\ref{ch:Lwhile} (loops) and including
  273. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  274. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  275. %
  276. %% \python{A course that emphasizes object-oriented languages would
  277. %% include Chapter~\ref{ch:Lobject}.}
  278. This book has been used in compiler courses at California Polytechnic
  279. State University, Portland State University, Rose–Hulman Institute of
  280. Technology, University of Freiburg, University of Massachusetts
  281. Lowell, and the University of Vermont.
  282. \begin{figure}[tp]
  283. \begin{tcolorbox}[colback=white]
  284. {\if\edition\racketEd
  285. \begin{tikzpicture}[baseline=(current bounding box.center)]
  286. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  287. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  288. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  289. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  290. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  291. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  292. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  293. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  294. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  295. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  296. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  297. \path[->] (C1) edge [above] node {} (C2);
  298. \path[->] (C2) edge [above] node {} (C3);
  299. \path[->] (C3) edge [above] node {} (C4);
  300. \path[->] (C4) edge [above] node {} (C5);
  301. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  302. \path[->] (C5) edge [above] node {} (C7);
  303. \path[->] (C6) edge [above] node {} (C7);
  304. \path[->] (C4) edge [above] node {} (C8);
  305. \path[->] (C4) edge [above] node {} (C9);
  306. \path[->] (C7) edge [above] node {} (C10);
  307. \path[->] (C8) edge [above] node {} (C10);
  308. \path[->] (C10) edge [above] node {} (C11);
  309. \end{tikzpicture}
  310. \fi}
  311. {\if\edition\pythonEd
  312. \begin{tikzpicture}[baseline=(current bounding box.center)]
  313. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  314. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  315. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  316. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  317. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  318. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  319. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  320. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  321. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  322. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  323. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  324. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  325. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  326. \path[->] (Prelim) edge [above] node {} (Var);
  327. \path[->] (Var) edge [above] node {} (Reg);
  328. \path[->] (Var) edge [above] node {} (Parse);
  329. \path[->] (Reg) edge [above] node {} (Cond);
  330. \path[->] (Cond) edge [above] node {} (Tuple);
  331. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  332. \path[->] (Cond) edge [above] node {} (Fun);
  333. \path[->] (Tuple) edge [above] node {} (Lam);
  334. \path[->] (Fun) edge [above] node {} (Lam);
  335. \path[->] (Cond) edge [above] node {} (Dyn);
  336. \path[->] (Cond) edge [above] node {} (Loop);
  337. \path[->] (Lam) edge [above] node {} (Gradual);
  338. \path[->] (Dyn) edge [above] node {} (Gradual);
  339. % \path[->] (Dyn) edge [above] node {} (CO);
  340. \path[->] (Gradual) edge [above] node {} (Generic);
  341. \end{tikzpicture}
  342. \fi}
  343. \end{tcolorbox}
  344. \caption{Diagram of chapter dependencies.}
  345. \label{fig:chapter-dependences}
  346. \end{figure}
  347. \racket{
  348. We use the \href{https://racket-lang.org/}{Racket} language both for
  349. the implementation of the compiler and for the input language, so the
  350. reader should be proficient with Racket or Scheme. There are many
  351. excellent resources for learning Scheme and
  352. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  353. }
  354. \python{
  355. This edition of the book uses \href{https://www.python.org/}{Python}
  356. both for the implementation of the compiler and for the input language, so the
  357. reader should be proficient with Python. There are many
  358. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  359. }
  360. The support code for this book is in the GitHub repository at
  361. the following location:
  362. \begin{center}\small\texttt
  363. https://github.com/IUCompilerCourse/
  364. \end{center}
  365. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  366. is helpful but not necessary for the reader to have taken a computer
  367. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  368. assembly language that are needed in the compiler.
  369. %
  370. We follow the System V calling
  371. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  372. that we generate works with the runtime system (written in C) when it
  373. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  374. operating systems on Intel hardware.
  375. %
  376. On the Windows operating system, \code{gcc} uses the Microsoft x64
  377. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  378. assembly code that we generate does \emph{not} work with the runtime
  379. system on Windows. One workaround is to use a virtual machine with
  380. Linux as the guest operating system.
  381. \section*{Acknowledgments}
  382. The tradition of compiler construction at Indiana University goes back
  383. to research and courses on programming languages by Daniel Friedman in
  384. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  385. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  386. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  387. the compiler course and continued the development of Chez Scheme.
  388. %
  389. The compiler course evolved to incorporate novel pedagogical ideas
  390. while also including elements of real-world compilers. One of
  391. Friedman's ideas was to split the compiler into many small
  392. passes. Another idea, called ``the game,'' was to test the code
  393. generated by each pass using interpreters.
  394. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  395. developed infrastructure to support this approach and evolved the
  396. course to use even smaller
  397. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  398. design decisions in this book are inspired by the assignment
  399. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  400. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  401. organization of the course made it difficult for students to
  402. understand the rationale for the compiler design. Ghuloum proposed the
  403. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  404. based.
  405. We thank the many students who served as teaching assistants for the
  406. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  407. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  408. garbage collector and x86 interpreter, Michael Vollmer for work on
  409. efficient tail calls, and Michael Vitousek for help with the first
  410. offering of the incremental compiler course at IU.
  411. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  412. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  413. Michael Wollowski for teaching courses based on drafts of this book
  414. and for their feedback. We thank the National Science Foundation for
  415. the grants that helped to support this work: Grant Numbers 1518844,
  416. 1763922, and 1814460.
  417. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  418. course in the early 2000s and especially for finding the bug that
  419. sent our garbage collector on a wild goose chase!
  420. \mbox{}\\
  421. \noindent Jeremy G. Siek \\
  422. Bloomington, Indiana
  423. \mainmatter
  424. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  425. \chapter{Preliminaries}
  426. \label{ch:trees-recur}
  427. \setcounter{footnote}{0}
  428. In this chapter we review the basic tools needed to implement a
  429. compiler. Programs are typically input by a programmer as text, that
  430. is, a sequence of characters. The program-as-text representation is
  431. called \emph{concrete syntax}. We use concrete syntax to concisely
  432. write down and talk about programs. Inside the compiler, we use
  433. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  434. that efficiently supports the operations that the compiler needs to
  435. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  436. syntax}\index{subject}{abstract syntax
  437. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  438. The process of translating from concrete syntax to abstract syntax is
  439. called \emph{parsing}\python{ and is studied in
  440. chapter~\ref{ch:parsing}}.
  441. \racket{This book does not cover the theory and implementation of parsing.
  442. We refer the readers interested in parsing to the thorough treatment
  443. of parsing by \citet{Aho:2006wb}.}%
  444. %
  445. \racket{A parser is provided in the support code for translating from
  446. concrete to abstract syntax.}%
  447. %
  448. \python{For now we use Python's \code{ast} module to translate from concrete
  449. to abstract syntax.}
  450. ASTs can be represented inside the compiler in many different ways,
  451. depending on the programming language used to write the compiler.
  452. %
  453. \racket{We use Racket's
  454. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  455. feature to represent ASTs (section~\ref{sec:ast}).}
  456. %
  457. \python{We use Python classes and objects to represent ASTs, especially the
  458. classes defined in the standard \code{ast} module for the Python
  459. source language.}
  460. %
  461. We use grammars to define the abstract syntax of programming languages
  462. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  463. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  464. recursive functions to construct and deconstruct ASTs
  465. (section~\ref{sec:recursion}). This chapter provides a brief
  466. introduction to these components.
  467. \racket{\index{subject}{struct}}
  468. \python{\index{subject}{class}\index{subject}{object}}
  469. \section{Abstract Syntax Trees}
  470. \label{sec:ast}
  471. Compilers use abstract syntax trees to represent programs because they
  472. often need to ask questions such as, for a given part of a program,
  473. what kind of language feature is it? What are its subparts? Consider
  474. the program on the left and the diagram of its AST on the
  475. right~\eqref{eq:arith-prog}. This program is an addition operation
  476. that has two subparts, a \racket{read}\python{input} operation and a
  477. negation. The negation has another subpart, the integer constant
  478. \code{8}. By using a tree to represent the program, we can easily
  479. follow the links to go from one part of a program to its subparts.
  480. \begin{center}
  481. \begin{minipage}{0.4\textwidth}
  482. \if\edition\racketEd
  483. \begin{lstlisting}
  484. (+ (read) (- 8))
  485. \end{lstlisting}
  486. \fi
  487. \if\edition\pythonEd
  488. \begin{lstlisting}
  489. input_int() + -8
  490. \end{lstlisting}
  491. \fi
  492. \end{minipage}
  493. \begin{minipage}{0.4\textwidth}
  494. \begin{equation}
  495. \begin{tikzpicture}
  496. \node[draw] (plus) at (0 , 0) {\key{+}};
  497. \node[draw] (read) at (-1, -1) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  498. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  499. \node[draw] (8) at (1 , -2) {\key{8}};
  500. \draw[->] (plus) to (read);
  501. \draw[->] (plus) to (minus);
  502. \draw[->] (minus) to (8);
  503. \end{tikzpicture}
  504. \label{eq:arith-prog}
  505. \end{equation}
  506. \end{minipage}
  507. \end{center}
  508. We use the standard terminology for trees to describe ASTs: each
  509. rectangle above is called a \emph{node}. The arrows connect a node to its
  510. \emph{children}, which are also nodes. The top-most node is the
  511. \emph{root}. Every node except for the root has a \emph{parent} (the
  512. node of which it is the child). If a node has no children, it is a
  513. \emph{leaf} node; otherwise it is an \emph{internal} node.
  514. \index{subject}{node}
  515. \index{subject}{children}
  516. \index{subject}{root}
  517. \index{subject}{parent}
  518. \index{subject}{leaf}
  519. \index{subject}{internal node}
  520. %% Recall that an \emph{symbolic expression} (S-expression) is either
  521. %% \begin{enumerate}
  522. %% \item an atom, or
  523. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  524. %% where $e_1$ and $e_2$ are each an S-expression.
  525. %% \end{enumerate}
  526. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  527. %% null value \code{'()}, etc. We can create an S-expression in Racket
  528. %% simply by writing a backquote (called a quasi-quote in Racket)
  529. %% followed by the textual representation of the S-expression. It is
  530. %% quite common to use S-expressions to represent a list, such as $a, b
  531. %% ,c$ in the following way:
  532. %% \begin{lstlisting}
  533. %% `(a . (b . (c . ())))
  534. %% \end{lstlisting}
  535. %% Each element of the list is in the first slot of a pair, and the
  536. %% second slot is either the rest of the list or the null value, to mark
  537. %% the end of the list. Such lists are so common that Racket provides
  538. %% special notation for them that removes the need for the periods
  539. %% and so many parenthesis:
  540. %% \begin{lstlisting}
  541. %% `(a b c)
  542. %% \end{lstlisting}
  543. %% The following expression creates an S-expression that represents AST
  544. %% \eqref{eq:arith-prog}.
  545. %% \begin{lstlisting}
  546. %% `(+ (read) (- 8))
  547. %% \end{lstlisting}
  548. %% When using S-expressions to represent ASTs, the convention is to
  549. %% represent each AST node as a list and to put the operation symbol at
  550. %% the front of the list. The rest of the list contains the children. So
  551. %% in the above case, the root AST node has operation \code{`+} and its
  552. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  553. %% diagram \eqref{eq:arith-prog}.
  554. %% To build larger S-expressions one often needs to splice together
  555. %% several smaller S-expressions. Racket provides the comma operator to
  556. %% splice an S-expression into a larger one. For example, instead of
  557. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  558. %% we could have first created an S-expression for AST
  559. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  560. %% S-expression.
  561. %% \begin{lstlisting}
  562. %% (define ast1.4 `(- 8))
  563. %% (define ast1_1 `(+ (read) ,ast1.4))
  564. %% \end{lstlisting}
  565. %% In general, the Racket expression that follows the comma (splice)
  566. %% can be any expression that produces an S-expression.
  567. {\if\edition\racketEd
  568. We define a Racket \code{struct} for each kind of node. For this
  569. chapter we require just two kinds of nodes: one for integer constants
  570. and one for primitive operations. The following is the \code{struct}
  571. definition for integer constants.\footnote{All the AST structures are
  572. defined in the file \code{utilities.rkt} in the support code.}
  573. \begin{lstlisting}
  574. (struct Int (value))
  575. \end{lstlisting}
  576. An integer node contains just one thing: the integer value.
  577. We establish the convention that \code{struct} names, such
  578. as \code{Int}, are capitalized.
  579. To create an AST node for the integer $8$, we write \INT{8}.
  580. \begin{lstlisting}
  581. (define eight (Int 8))
  582. \end{lstlisting}
  583. We say that the value created by \INT{8} is an
  584. \emph{instance} of the
  585. \code{Int} structure.
  586. The following is the \code{struct} definition for primitive operations.
  587. \begin{lstlisting}
  588. (struct Prim (op args))
  589. \end{lstlisting}
  590. A primitive operation node includes an operator symbol \code{op} and a
  591. list of child arguments called \code{args}. For example, to create an
  592. AST that negates the number $8$, we write the following.
  593. \begin{lstlisting}
  594. (define neg-eight (Prim '- (list eight)))
  595. \end{lstlisting}
  596. Primitive operations may have zero or more children. The \code{read}
  597. operator has zero:
  598. \begin{lstlisting}
  599. (define rd (Prim 'read '()))
  600. \end{lstlisting}
  601. The addition operator has two children:
  602. \begin{lstlisting}
  603. (define ast1_1 (Prim '+ (list rd neg-eight)))
  604. \end{lstlisting}
  605. We have made a design choice regarding the \code{Prim} structure.
  606. Instead of using one structure for many different operations
  607. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  608. structure for each operation, as follows:
  609. \begin{lstlisting}
  610. (struct Read ())
  611. (struct Add (left right))
  612. (struct Neg (value))
  613. \end{lstlisting}
  614. The reason that we choose to use just one structure is that many parts
  615. of the compiler can use the same code for the different primitive
  616. operators, so we might as well just write that code once by using a
  617. single structure.
  618. %
  619. \fi}
  620. {\if\edition\pythonEd
  621. We use a Python \code{class} for each kind of node.
  622. The following is the class definition for
  623. constants from the Python \code{ast} module.
  624. \begin{lstlisting}
  625. class Constant:
  626. def __init__(self, value):
  627. self.value = value
  628. \end{lstlisting}
  629. An integer constant node includes just one thing: the integer value.
  630. To create an AST node for the integer $8$, we write \INT{8}.
  631. \begin{lstlisting}
  632. eight = Constant(8)
  633. \end{lstlisting}
  634. We say that the value created by \INT{8} is an
  635. \emph{instance} of the \code{Constant} class.
  636. The following is the class definition for unary operators.
  637. \begin{lstlisting}
  638. class UnaryOp:
  639. def __init__(self, op, operand):
  640. self.op = op
  641. self.operand = operand
  642. \end{lstlisting}
  643. The specific operation is specified by the \code{op} parameter. For
  644. example, the class \code{USub} is for unary subtraction.
  645. (More unary operators are introduced in later chapters.) To create an AST that
  646. negates the number $8$, we write the following.
  647. \begin{lstlisting}
  648. neg_eight = UnaryOp(USub(), eight)
  649. \end{lstlisting}
  650. The call to the \code{input\_int} function is represented by the
  651. \code{Call} and \code{Name} classes.
  652. \begin{lstlisting}
  653. class Call:
  654. def __init__(self, func, args):
  655. self.func = func
  656. self.args = args
  657. class Name:
  658. def __init__(self, id):
  659. self.id = id
  660. \end{lstlisting}
  661. To create an AST node that calls \code{input\_int}, we write
  662. \begin{lstlisting}
  663. read = Call(Name('input_int'), [])
  664. \end{lstlisting}
  665. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  666. the \code{BinOp} class for binary operators.
  667. \begin{lstlisting}
  668. class BinOp:
  669. def __init__(self, left, op, right):
  670. self.op = op
  671. self.left = left
  672. self.right = right
  673. \end{lstlisting}
  674. Similar to \code{UnaryOp}, the specific operation is specified by the
  675. \code{op} parameter, which for now is just an instance of the
  676. \code{Add} class. So to create the AST
  677. node that adds negative eight to some user input, we write the following.
  678. \begin{lstlisting}
  679. ast1_1 = BinOp(read, Add(), neg_eight)
  680. \end{lstlisting}
  681. \fi}
  682. To compile a program such as \eqref{eq:arith-prog}, we need to know
  683. that the operation associated with the root node is addition and we
  684. need to be able to access its two
  685. children. \racket{Racket}\python{Python} provides pattern matching to
  686. support these kinds of queries, as we see in
  687. section~\ref{sec:pattern-matching}.
  688. We often write down the concrete syntax of a program even when we
  689. actually have in mind the AST, because the concrete syntax is more
  690. concise. We recommend that you always think of programs as abstract
  691. syntax trees.
  692. \section{Grammars}
  693. \label{sec:grammar}
  694. \index{subject}{integer}
  695. \index{subject}{literal}
  696. %\index{subject}{constant}
  697. A programming language can be thought of as a \emph{set} of programs.
  698. The set is infinite (that is, one can always create larger programs),
  699. so one cannot simply describe a language by listing all the
  700. programs in the language. Instead we write down a set of rules, a
  701. \emph{context-free grammar}, for building programs. Grammars are often used to
  702. define the concrete syntax of a language, but they can also be used to
  703. describe the abstract syntax. We write our rules in a variant of
  704. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  705. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  706. we describe a small language, named \LangInt{}, that consists of
  707. integers and arithmetic operations.\index{subject}{grammar}
  708. \index{subject}{context-free grammar}
  709. The first grammar rule for the abstract syntax of \LangInt{} says that an
  710. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  711. \begin{equation}
  712. \Exp ::= \INT{\Int} \label{eq:arith-int}
  713. \end{equation}
  714. %
  715. Each rule has a left-hand side and a right-hand side.
  716. If you have an AST node that matches the
  717. right-hand side, then you can categorize it according to the
  718. left-hand side.
  719. %
  720. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  721. are \emph{terminal} symbols and must literally appear in the program for the
  722. rule to be applicable.\index{subject}{terminal}
  723. %
  724. Our grammars do not mention \emph{white space}, that is, delimiter
  725. characters like spaces, tabs, and new lines. White space may be
  726. inserted between symbols for disambiguation and to improve
  727. readability. \index{subject}{white space}
  728. %
  729. A name such as $\Exp$ that is defined by the grammar rules is a
  730. \emph{nonterminal}. \index{subject}{nonterminal}
  731. %
  732. The name $\Int$ is also a nonterminal, but instead of defining it with
  733. a grammar rule, we define it with the following explanation. An
  734. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  735. $-$ (for negative integers), such that the sequence of decimals
  736. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  737. enables the representation of integers using 63 bits, which simplifies
  738. several aspects of compilation.
  739. %
  740. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  741. datatype on a 64-bit machine.}
  742. %
  743. \python{In contrast, integers in Python have unlimited precision, but
  744. the techniques needed to handle unlimited precision fall outside the
  745. scope of this book.}
  746. The second grammar rule is the \READOP{} operation, which receives an
  747. input integer from the user of the program.
  748. \begin{equation}
  749. \Exp ::= \READ{} \label{eq:arith-read}
  750. \end{equation}
  751. The third rule categorizes the negation of an $\Exp$ node as an
  752. $\Exp$.
  753. \begin{equation}
  754. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  755. \end{equation}
  756. We can apply these rules to categorize the ASTs that are in the
  757. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  758. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  759. following AST is an $\Exp$.
  760. \begin{center}
  761. \begin{minipage}{0.5\textwidth}
  762. \NEG{\INT{\code{8}}}
  763. \end{minipage}
  764. \begin{minipage}{0.25\textwidth}
  765. \begin{equation}
  766. \begin{tikzpicture}
  767. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  768. \node[draw, circle] (8) at (0, -1.2) {$8$};
  769. \draw[->] (minus) to (8);
  770. \end{tikzpicture}
  771. \label{eq:arith-neg8}
  772. \end{equation}
  773. \end{minipage}
  774. \end{center}
  775. The next two grammar rules are for addition and subtraction expressions:
  776. \begin{align}
  777. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  778. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  779. \end{align}
  780. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  781. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  782. \eqref{eq:arith-read}, and we have already categorized
  783. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  784. to show that
  785. \[
  786. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  787. \]
  788. is an $\Exp$ in the \LangInt{} language.
  789. If you have an AST for which these rules do not apply, then the
  790. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  791. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  792. because there is no rule for the \key{*} operator. Whenever we
  793. define a language with a grammar, the language includes only those
  794. programs that are justified by the grammar rules.
  795. {\if\edition\pythonEd
  796. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  797. There is a statement for printing the value of an expression
  798. \[
  799. \Stmt{} ::= \PRINT{\Exp}
  800. \]
  801. and a statement that evaluates an expression but ignores the result.
  802. \[
  803. \Stmt{} ::= \EXPR{\Exp}
  804. \]
  805. \fi}
  806. {\if\edition\racketEd
  807. The last grammar rule for \LangInt{} states that there is a
  808. \code{Program} node to mark the top of the whole program:
  809. \[
  810. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  811. \]
  812. The \code{Program} structure is defined as follows:
  813. \begin{lstlisting}
  814. (struct Program (info body))
  815. \end{lstlisting}
  816. where \code{body} is an expression. In further chapters, the \code{info}
  817. part is used to store auxiliary information, but for now it is
  818. just the empty list.
  819. \fi}
  820. {\if\edition\pythonEd
  821. The last grammar rule for \LangInt{} states that there is a
  822. \code{Module} node to mark the top of the whole program:
  823. \[
  824. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  825. \]
  826. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  827. this case, a list of statements.
  828. %
  829. The \code{Module} class is defined as follows
  830. \begin{lstlisting}
  831. class Module:
  832. def __init__(self, body):
  833. self.body = body
  834. \end{lstlisting}
  835. where \code{body} is a list of statements.
  836. \fi}
  837. It is common to have many grammar rules with the same left-hand side
  838. but different right-hand sides, such as the rules for $\Exp$ in the
  839. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  840. combine several right-hand sides into a single rule.
  841. The concrete syntax for \LangInt{} is shown in
  842. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  843. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  844. %
  845. \racket{The \code{read-program} function provided in
  846. \code{utilities.rkt} of the support code reads a program from a file
  847. (the sequence of characters in the concrete syntax of Racket) and
  848. parses it into an abstract syntax tree. Refer to the description of
  849. \code{read-program} in appendix~\ref{appendix:utilities} for more
  850. details.}
  851. %
  852. \python{The \code{parse} function in Python's \code{ast} module
  853. converts the concrete syntax (represented as a string) into an
  854. abstract syntax tree.}
  855. \newcommand{\LintGrammarRacket}{
  856. \begin{array}{rcl}
  857. \Type &::=& \key{Integer} \\
  858. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  859. \MID \CSUB{\Exp}{\Exp}
  860. \end{array}
  861. }
  862. \newcommand{\LintASTRacket}{
  863. \begin{array}{rcl}
  864. \Type &::=& \key{Integer} \\
  865. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  866. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  867. \end{array}
  868. }
  869. \newcommand{\LintGrammarPython}{
  870. \begin{array}{rcl}
  871. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  872. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  873. \end{array}
  874. }
  875. \newcommand{\LintASTPython}{
  876. \begin{array}{rcl}
  877. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  878. \itm{unaryop} &::= & \code{USub()} \\
  879. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  880. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  881. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  882. \end{array}
  883. }
  884. \begin{figure}[tp]
  885. \begin{tcolorbox}[colback=white]
  886. {\if\edition\racketEd
  887. \[
  888. \begin{array}{l}
  889. \LintGrammarRacket \\
  890. \begin{array}{rcl}
  891. \LangInt{} &::=& \Exp
  892. \end{array}
  893. \end{array}
  894. \]
  895. \fi}
  896. {\if\edition\pythonEd
  897. \[
  898. \begin{array}{l}
  899. \LintGrammarPython \\
  900. \begin{array}{rcl}
  901. \LangInt{} &::=& \Stmt^{*}
  902. \end{array}
  903. \end{array}
  904. \]
  905. \fi}
  906. \end{tcolorbox}
  907. \caption{The concrete syntax of \LangInt{}.}
  908. \label{fig:r0-concrete-syntax}
  909. \end{figure}
  910. \begin{figure}[tp]
  911. \begin{tcolorbox}[colback=white]
  912. {\if\edition\racketEd
  913. \[
  914. \begin{array}{l}
  915. \LintASTRacket{} \\
  916. \begin{array}{rcl}
  917. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  918. \end{array}
  919. \end{array}
  920. \]
  921. \fi}
  922. {\if\edition\pythonEd
  923. \[
  924. \begin{array}{l}
  925. \LintASTPython\\
  926. \begin{array}{rcl}
  927. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  928. \end{array}
  929. \end{array}
  930. \]
  931. \fi}
  932. \end{tcolorbox}
  933. \python{
  934. \index{subject}{Constant@\texttt{Constant}}
  935. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  936. \index{subject}{USub@\texttt{USub}}
  937. \index{subject}{inputint@\texttt{input\_int}}
  938. \index{subject}{Call@\texttt{Call}}
  939. \index{subject}{Name@\texttt{Name}}
  940. \index{subject}{BinOp@\texttt{BinOp}}
  941. \index{subject}{Add@\texttt{Add}}
  942. \index{subject}{Sub@\texttt{Sub}}
  943. \index{subject}{print@\texttt{print}}
  944. \index{subject}{Expr@\texttt{Expr}}
  945. \index{subject}{Module@\texttt{Module}}
  946. }
  947. \caption{The abstract syntax of \LangInt{}.}
  948. \label{fig:r0-syntax}
  949. \end{figure}
  950. \section{Pattern Matching}
  951. \label{sec:pattern-matching}
  952. As mentioned in section~\ref{sec:ast}, compilers often need to access
  953. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  954. provides the \texttt{match} feature to access the parts of a value.
  955. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  956. \begin{center}
  957. \begin{minipage}{0.5\textwidth}
  958. {\if\edition\racketEd
  959. \begin{lstlisting}
  960. (match ast1_1
  961. [(Prim op (list child1 child2))
  962. (print op)])
  963. \end{lstlisting}
  964. \fi}
  965. {\if\edition\pythonEd
  966. \begin{lstlisting}
  967. match ast1_1:
  968. case BinOp(child1, op, child2):
  969. print(op)
  970. \end{lstlisting}
  971. \fi}
  972. \end{minipage}
  973. \end{center}
  974. {\if\edition\racketEd
  975. %
  976. In this example, the \texttt{match} form checks whether the AST
  977. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  978. three pattern variables \texttt{op}, \texttt{child1}, and
  979. \texttt{child2}. In general, a match clause consists of a
  980. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  981. recursively defined to be a pattern variable, a structure name
  982. followed by a pattern for each of the structure's arguments, or an
  983. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  984. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  985. and chapter 9 of The Racket
  986. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  987. for complete descriptions of \code{match}.)
  988. %
  989. The body of a match clause may contain arbitrary Racket code. The
  990. pattern variables can be used in the scope of the body, such as
  991. \code{op} in \code{(print op)}.
  992. %
  993. \fi}
  994. %
  995. %
  996. {\if\edition\pythonEd
  997. %
  998. In the above example, the \texttt{match} form checks whether the AST
  999. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1000. three pattern variables \texttt{child1}, \texttt{op}, and
  1001. \texttt{child2}, and then prints out the operator. In general, each
  1002. \code{case} consists of a \emph{pattern} and a
  1003. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  1004. to be either a pattern variable, a class name followed by a pattern
  1005. for each of its constructor's arguments, or other literals such as
  1006. strings, lists, etc.
  1007. %
  1008. The body of each \code{case} may contain arbitrary Python code. The
  1009. pattern variables can be used in the body, such as \code{op} in
  1010. \code{print(op)}.
  1011. %
  1012. \fi}
  1013. A \code{match} form may contain several clauses, as in the following
  1014. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1015. the AST. The \code{match} proceeds through the clauses in order,
  1016. checking whether the pattern can match the input AST. The body of the
  1017. first clause that matches is executed. The output of \code{leaf} for
  1018. several ASTs is shown on the right side of the following:
  1019. \begin{center}
  1020. \begin{minipage}{0.6\textwidth}
  1021. {\if\edition\racketEd
  1022. \begin{lstlisting}
  1023. (define (leaf arith)
  1024. (match arith
  1025. [(Int n) #t]
  1026. [(Prim 'read '()) #t]
  1027. [(Prim '- (list e1)) #f]
  1028. [(Prim '+ (list e1 e2)) #f]
  1029. [(Prim '- (list e1 e2)) #f]))
  1030. (leaf (Prim 'read '()))
  1031. (leaf (Prim '- (list (Int 8))))
  1032. (leaf (Int 8))
  1033. \end{lstlisting}
  1034. \fi}
  1035. {\if\edition\pythonEd
  1036. \begin{lstlisting}
  1037. def leaf(arith):
  1038. match arith:
  1039. case Constant(n):
  1040. return True
  1041. case Call(Name('input_int'), []):
  1042. return True
  1043. case UnaryOp(USub(), e1):
  1044. return False
  1045. case BinOp(e1, Add(), e2):
  1046. return False
  1047. case BinOp(e1, Sub(), e2):
  1048. return False
  1049. print(leaf(Call(Name('input_int'), [])))
  1050. print(leaf(UnaryOp(USub(), eight)))
  1051. print(leaf(Constant(8)))
  1052. \end{lstlisting}
  1053. \fi}
  1054. \end{minipage}
  1055. \vrule
  1056. \begin{minipage}{0.25\textwidth}
  1057. {\if\edition\racketEd
  1058. \begin{lstlisting}
  1059. #t
  1060. #f
  1061. #t
  1062. \end{lstlisting}
  1063. \fi}
  1064. {\if\edition\pythonEd
  1065. \begin{lstlisting}
  1066. True
  1067. False
  1068. True
  1069. \end{lstlisting}
  1070. \fi}
  1071. \end{minipage}
  1072. \end{center}
  1073. When constructing a \code{match} expression, we refer to the grammar
  1074. definition to identify which nonterminal we are expecting to match
  1075. against, and then we make sure that (1) we have one
  1076. \racket{clause}\python{case} for each alternative of that nonterminal
  1077. and (2) the pattern in each \racket{clause}\python{case}
  1078. corresponds to the corresponding right-hand side of a grammar
  1079. rule. For the \code{match} in the \code{leaf} function, we refer to
  1080. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1081. nonterminal has four alternatives, so the \code{match} has four
  1082. \racket{clauses}\python{cases}. The pattern in each
  1083. \racket{clause}\python{case} corresponds to the right-hand side of a
  1084. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1085. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1086. translating from grammars to patterns, replace nonterminals such as
  1087. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1088. \code{e2}).
  1089. \section{Recursive Functions}
  1090. \label{sec:recursion}
  1091. \index{subject}{recursive function}
  1092. Programs are inherently recursive. For example, an expression is often
  1093. made of smaller expressions. Thus, the natural way to process an
  1094. entire program is to use a recursive function. As a first example of
  1095. such a recursive function, we define the function \code{is\_exp} as
  1096. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1097. value and determine whether or not it is an expression in \LangInt{}.
  1098. %
  1099. We say that a function is defined by \emph{structural recursion} if
  1100. it is defined using a sequence of match \racket{clauses}\python{cases}
  1101. that correspond to a grammar and the body of each
  1102. \racket{clause}\python{case} makes a recursive call on each child
  1103. node.\footnote{This principle of structuring code according to the
  1104. data definition is advocated in the book \emph{How to Design
  1105. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1106. second function, named \code{stmt}, that recognizes whether a value
  1107. is a \LangInt{} statement.} \python{Finally, }
  1108. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1109. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1110. In general, we can write one recursive function to handle each
  1111. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1112. two examples at the bottom of the figure, the first is in
  1113. \LangInt{} and the second is not.
  1114. \begin{figure}[tp]
  1115. \begin{tcolorbox}[colback=white]
  1116. {\if\edition\racketEd
  1117. \begin{lstlisting}
  1118. (define (is_exp ast)
  1119. (match ast
  1120. [(Int n) #t]
  1121. [(Prim 'read '()) #t]
  1122. [(Prim '- (list e)) (is_exp e)]
  1123. [(Prim '+ (list e1 e2))
  1124. (and (is_exp e1) (is_exp e2))]
  1125. [(Prim '- (list e1 e2))
  1126. (and (is_exp e1) (is_exp e2))]
  1127. [else #f]))
  1128. (define (is_Lint ast)
  1129. (match ast
  1130. [(Program '() e) (is_exp e)]
  1131. [else #f]))
  1132. (is_Lint (Program '() ast1_1)
  1133. (is_Lint (Program '()
  1134. (Prim '* (list (Prim 'read '())
  1135. (Prim '+ (list (Int 8)))))))
  1136. \end{lstlisting}
  1137. \fi}
  1138. {\if\edition\pythonEd
  1139. \begin{lstlisting}
  1140. def is_exp(e):
  1141. match e:
  1142. case Constant(n):
  1143. return True
  1144. case Call(Name('input_int'), []):
  1145. return True
  1146. case UnaryOp(USub(), e1):
  1147. return is_exp(e1)
  1148. case BinOp(e1, Add(), e2):
  1149. return is_exp(e1) and is_exp(e2)
  1150. case BinOp(e1, Sub(), e2):
  1151. return is_exp(e1) and is_exp(e2)
  1152. case _:
  1153. return False
  1154. def stmt(s):
  1155. match s:
  1156. case Expr(Call(Name('print'), [e])):
  1157. return is_exp(e)
  1158. case Expr(e):
  1159. return is_exp(e)
  1160. case _:
  1161. return False
  1162. def is_Lint(p):
  1163. match p:
  1164. case Module(body):
  1165. return all([stmt(s) for s in body])
  1166. case _:
  1167. return False
  1168. print(is_Lint(Module([Expr(ast1_1)])))
  1169. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1170. UnaryOp(Add(), Constant(8))))])))
  1171. \end{lstlisting}
  1172. \fi}
  1173. \end{tcolorbox}
  1174. \caption{Example of recursive functions for \LangInt{}. These functions
  1175. recognize whether an AST is in \LangInt{}.}
  1176. \label{fig:exp-predicate}
  1177. \end{figure}
  1178. %% You may be tempted to merge the two functions into one, like this:
  1179. %% \begin{center}
  1180. %% \begin{minipage}{0.5\textwidth}
  1181. %% \begin{lstlisting}
  1182. %% (define (Lint ast)
  1183. %% (match ast
  1184. %% [(Int n) #t]
  1185. %% [(Prim 'read '()) #t]
  1186. %% [(Prim '- (list e)) (Lint e)]
  1187. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1188. %% [(Program '() e) (Lint e)]
  1189. %% [else #f]))
  1190. %% \end{lstlisting}
  1191. %% \end{minipage}
  1192. %% \end{center}
  1193. %% %
  1194. %% Sometimes such a trick will save a few lines of code, especially when
  1195. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1196. %% \emph{not} recommended because it can get you into trouble.
  1197. %% %
  1198. %% For example, the above function is subtly wrong:
  1199. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1200. %% returns true when it should return false.
  1201. \section{Interpreters}
  1202. \label{sec:interp_Lint}
  1203. \index{subject}{interpreter}
  1204. The behavior of a program is defined by the specification of the
  1205. programming language.
  1206. %
  1207. \racket{For example, the Scheme language is defined in the report by
  1208. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1209. reference manual~\citep{plt-tr}.}
  1210. %
  1211. \python{For example, the Python language is defined in the Python
  1212. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1213. %
  1214. In this book we use interpreters to specify each language that we
  1215. consider. An interpreter that is designated as the definition of a
  1216. language is called a \emph{definitional
  1217. interpreter}~\citep{reynolds72:_def_interp}.
  1218. \index{subject}{definitional interpreter} We warm up by creating a
  1219. definitional interpreter for the \LangInt{} language. This interpreter
  1220. serves as a second example of structural recursion. The definition of the
  1221. \code{interp\_Lint} function is shown in
  1222. figure~\ref{fig:interp_Lint}.
  1223. %
  1224. \racket{The body of the function is a match on the input program
  1225. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1226. which in turn has one match clause per grammar rule for \LangInt{}
  1227. expressions.}
  1228. %
  1229. \python{The body of the function matches on the \code{Module} AST node
  1230. and then invokes \code{interp\_stmt} on each statement in the
  1231. module. The \code{interp\_stmt} function includes a case for each
  1232. grammar rule of the \Stmt{} nonterminal and it calls
  1233. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1234. function includes a case for each grammar rule of the \Exp{}
  1235. nonterminal.}
  1236. \begin{figure}[tp]
  1237. \begin{tcolorbox}[colback=white]
  1238. {\if\edition\racketEd
  1239. \begin{lstlisting}
  1240. (define (interp_exp e)
  1241. (match e
  1242. [(Int n) n]
  1243. [(Prim 'read '())
  1244. (define r (read))
  1245. (cond [(fixnum? r) r]
  1246. [else (error 'interp_exp "read expected an integer" r)])]
  1247. [(Prim '- (list e))
  1248. (define v (interp_exp e))
  1249. (fx- 0 v)]
  1250. [(Prim '+ (list e1 e2))
  1251. (define v1 (interp_exp e1))
  1252. (define v2 (interp_exp e2))
  1253. (fx+ v1 v2)]
  1254. [(Prim '- (list e1 e2))
  1255. (define v1 ((interp-exp env) e1))
  1256. (define v2 ((interp-exp env) e2))
  1257. (fx- v1 v2)]))
  1258. (define (interp_Lint p)
  1259. (match p
  1260. [(Program '() e) (interp_exp e)]))
  1261. \end{lstlisting}
  1262. \fi}
  1263. {\if\edition\pythonEd
  1264. \begin{lstlisting}
  1265. def interp_exp(e):
  1266. match e:
  1267. case BinOp(left, Add(), right):
  1268. l = interp_exp(left); r = interp_exp(right)
  1269. return l + r
  1270. case BinOp(left, Sub(), right):
  1271. l = interp_exp(left); r = interp_exp(right)
  1272. return l - r
  1273. case UnaryOp(USub(), v):
  1274. return - interp_exp(v)
  1275. case Constant(value):
  1276. return value
  1277. case Call(Name('input_int'), []):
  1278. return int(input())
  1279. def interp_stmt(s):
  1280. match s:
  1281. case Expr(Call(Name('print'), [arg])):
  1282. print(interp_exp(arg))
  1283. case Expr(value):
  1284. interp_exp(value)
  1285. def interp_Lint(p):
  1286. match p:
  1287. case Module(body):
  1288. for s in body:
  1289. interp_stmt(s)
  1290. \end{lstlisting}
  1291. \fi}
  1292. \end{tcolorbox}
  1293. \caption{Interpreter for the \LangInt{} language.}
  1294. \label{fig:interp_Lint}
  1295. \end{figure}
  1296. Let us consider the result of interpreting a few \LangInt{} programs. The
  1297. following program adds two integers:
  1298. {\if\edition\racketEd
  1299. \begin{lstlisting}
  1300. (+ 10 32)
  1301. \end{lstlisting}
  1302. \fi}
  1303. {\if\edition\pythonEd
  1304. \begin{lstlisting}
  1305. print(10 + 32)
  1306. \end{lstlisting}
  1307. \fi}
  1308. %
  1309. \noindent The result is \key{42}, the answer to life, the universe,
  1310. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1311. the Galaxy} by Douglas Adams.}
  1312. %
  1313. We wrote this program in concrete syntax, whereas the parsed
  1314. abstract syntax is
  1315. {\if\edition\racketEd
  1316. \begin{lstlisting}
  1317. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1318. \end{lstlisting}
  1319. \fi}
  1320. {\if\edition\pythonEd
  1321. \begin{lstlisting}
  1322. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1323. \end{lstlisting}
  1324. \fi}
  1325. The following program demonstrates that expressions may be nested within
  1326. each other, in this case nesting several additions and negations.
  1327. {\if\edition\racketEd
  1328. \begin{lstlisting}
  1329. (+ 10 (- (+ 12 20)))
  1330. \end{lstlisting}
  1331. \fi}
  1332. {\if\edition\pythonEd
  1333. \begin{lstlisting}
  1334. print(10 + -(12 + 20))
  1335. \end{lstlisting}
  1336. \fi}
  1337. %
  1338. \noindent What is the result of this program?
  1339. {\if\edition\racketEd
  1340. As mentioned previously, the \LangInt{} language does not support
  1341. arbitrarily large integers but only $63$-bit integers, so we
  1342. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1343. in Racket.
  1344. Suppose that
  1345. \[
  1346. n = 999999999999999999
  1347. \]
  1348. which indeed fits in $63$ bits. What happens when we run the
  1349. following program in our interpreter?
  1350. \begin{lstlisting}
  1351. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1352. \end{lstlisting}
  1353. It produces the following error:
  1354. \begin{lstlisting}
  1355. fx+: result is not a fixnum
  1356. \end{lstlisting}
  1357. We establish the convention that if running the definitional
  1358. interpreter on a program produces an error, then the meaning of that
  1359. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1360. error is a \code{trapped-error}. A compiler for the language is under
  1361. no obligation regarding programs with unspecified behavior; it does
  1362. not have to produce an executable, and if it does, that executable can
  1363. do anything. On the other hand, if the error is a
  1364. \code{trapped-error}, then the compiler must produce an executable and
  1365. it is required to report that an error occurred. To signal an error,
  1366. exit with a return code of \code{255}. The interpreters in chapters
  1367. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1368. \code{trapped-error}.
  1369. \fi}
  1370. % TODO: how to deal with too-large integers in the Python interpreter?
  1371. %% This convention applies to the languages defined in this
  1372. %% book, as a way to simplify the student's task of implementing them,
  1373. %% but this convention is not applicable to all programming languages.
  1374. %%
  1375. The last feature of the \LangInt{} language, the \READOP{} operation,
  1376. prompts the user of the program for an integer. Recall that program
  1377. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1378. \code{8}. So, if we run {\if\edition\racketEd
  1379. \begin{lstlisting}
  1380. (interp_Lint (Program '() ast1_1))
  1381. \end{lstlisting}
  1382. \fi}
  1383. {\if\edition\pythonEd
  1384. \begin{lstlisting}
  1385. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1386. \end{lstlisting}
  1387. \fi}
  1388. \noindent and if the input is \code{50}, the result is \code{42}.
  1389. We include the \READOP{} operation in \LangInt{} so that a clever
  1390. student cannot implement a compiler for \LangInt{} that simply runs
  1391. the interpreter during compilation to obtain the output and then
  1392. generates the trivial code to produce the output.\footnote{Yes, a
  1393. clever student did this in the first instance of this course!}
  1394. The job of a compiler is to translate a program in one language into a
  1395. program in another language so that the output program behaves the
  1396. same way as the input program. This idea is depicted in the
  1397. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1398. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1399. Given a compiler that translates from language $\mathcal{L}_1$ to
  1400. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1401. compiler must translate it into some program $P_2$ such that
  1402. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1403. same input $i$ yields the same output $o$.
  1404. \begin{equation} \label{eq:compile-correct}
  1405. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1406. \node (p1) at (0, 0) {$P_1$};
  1407. \node (p2) at (3, 0) {$P_2$};
  1408. \node (o) at (3, -2.5) {$o$};
  1409. \path[->] (p1) edge [above] node {compile} (p2);
  1410. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1411. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1412. \end{tikzpicture}
  1413. \end{equation}
  1414. In the next section we see our first example of a compiler.
  1415. \section{Example Compiler: A Partial Evaluator}
  1416. \label{sec:partial-evaluation}
  1417. In this section we consider a compiler that translates \LangInt{}
  1418. programs into \LangInt{} programs that may be more efficient. The
  1419. compiler eagerly computes the parts of the program that do not depend
  1420. on any inputs, a process known as \emph{partial
  1421. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1422. For example, given the following program
  1423. {\if\edition\racketEd
  1424. \begin{lstlisting}
  1425. (+ (read) (- (+ 5 3)))
  1426. \end{lstlisting}
  1427. \fi}
  1428. {\if\edition\pythonEd
  1429. \begin{lstlisting}
  1430. print(input_int() + -(5 + 3) )
  1431. \end{lstlisting}
  1432. \fi}
  1433. \noindent our compiler translates it into the program
  1434. {\if\edition\racketEd
  1435. \begin{lstlisting}
  1436. (+ (read) -8)
  1437. \end{lstlisting}
  1438. \fi}
  1439. {\if\edition\pythonEd
  1440. \begin{lstlisting}
  1441. print(input_int() + -8)
  1442. \end{lstlisting}
  1443. \fi}
  1444. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1445. evaluator for the \LangInt{} language. The output of the partial evaluator
  1446. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1447. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1448. whereas the code for partially evaluating the negation and addition
  1449. operations is factored into three auxiliary functions:
  1450. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1451. functions is the output of partially evaluating the children.
  1452. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1453. arguments are integers and if they are, perform the appropriate
  1454. arithmetic. Otherwise, they create an AST node for the arithmetic
  1455. operation.
  1456. \begin{figure}[tp]
  1457. \begin{tcolorbox}[colback=white]
  1458. {\if\edition\racketEd
  1459. \begin{lstlisting}
  1460. (define (pe_neg r)
  1461. (match r
  1462. [(Int n) (Int (fx- 0 n))]
  1463. [else (Prim '- (list r))]))
  1464. (define (pe_add r1 r2)
  1465. (match* (r1 r2)
  1466. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1467. [(_ _) (Prim '+ (list r1 r2))]))
  1468. (define (pe_sub r1 r2)
  1469. (match* (r1 r2)
  1470. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1471. [(_ _) (Prim '- (list r1 r2))]))
  1472. (define (pe_exp e)
  1473. (match e
  1474. [(Int n) (Int n)]
  1475. [(Prim 'read '()) (Prim 'read '())]
  1476. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1477. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1478. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1479. (define (pe_Lint p)
  1480. (match p
  1481. [(Program '() e) (Program '() (pe_exp e))]))
  1482. \end{lstlisting}
  1483. \fi}
  1484. {\if\edition\pythonEd
  1485. \begin{lstlisting}
  1486. def pe_neg(r):
  1487. match r:
  1488. case Constant(n):
  1489. return Constant(-n)
  1490. case _:
  1491. return UnaryOp(USub(), r)
  1492. def pe_add(r1, r2):
  1493. match (r1, r2):
  1494. case (Constant(n1), Constant(n2)):
  1495. return Constant(n1 + n2)
  1496. case _:
  1497. return BinOp(r1, Add(), r2)
  1498. def pe_sub(r1, r2):
  1499. match (r1, r2):
  1500. case (Constant(n1), Constant(n2)):
  1501. return Constant(n1 - n2)
  1502. case _:
  1503. return BinOp(r1, Sub(), r2)
  1504. def pe_exp(e):
  1505. match e:
  1506. case BinOp(left, Add(), right):
  1507. return pe_add(pe_exp(left), pe_exp(right))
  1508. case BinOp(left, Sub(), right):
  1509. return pe_sub(pe_exp(left), pe_exp(right))
  1510. case UnaryOp(USub(), v):
  1511. return pe_neg(pe_exp(v))
  1512. case Constant(value):
  1513. return e
  1514. case Call(Name('input_int'), []):
  1515. return e
  1516. def pe_stmt(s):
  1517. match s:
  1518. case Expr(Call(Name('print'), [arg])):
  1519. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1520. case Expr(value):
  1521. return Expr(pe_exp(value))
  1522. def pe_P_int(p):
  1523. match p:
  1524. case Module(body):
  1525. new_body = [pe_stmt(s) for s in body]
  1526. return Module(new_body)
  1527. \end{lstlisting}
  1528. \fi}
  1529. \end{tcolorbox}
  1530. \caption{A partial evaluator for \LangInt{}.}
  1531. \label{fig:pe-arith}
  1532. \end{figure}
  1533. To gain some confidence that the partial evaluator is correct, we can
  1534. test whether it produces programs that produce the same result as the
  1535. input programs. That is, we can test whether it satisfies the diagram
  1536. of \eqref{eq:compile-correct}.
  1537. %
  1538. {\if\edition\racketEd
  1539. The following code runs the partial evaluator on several examples and
  1540. tests the output program. The \texttt{parse-program} and
  1541. \texttt{assert} functions are defined in
  1542. appendix~\ref{appendix:utilities}.\\
  1543. \begin{minipage}{1.0\textwidth}
  1544. \begin{lstlisting}
  1545. (define (test_pe p)
  1546. (assert "testing pe_Lint"
  1547. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1548. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1549. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1550. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1551. \end{lstlisting}
  1552. \end{minipage}
  1553. \fi}
  1554. % TODO: python version of testing the PE
  1555. \begin{exercise}\normalfont\normalsize
  1556. Create three programs in the \LangInt{} language and test whether
  1557. partially evaluating them with \code{pe\_Lint} and then
  1558. interpreting them with \code{interp\_Lint} gives the same result
  1559. as directly interpreting them with \code{interp\_Lint}.
  1560. \end{exercise}
  1561. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1562. \chapter{Integers and Variables}
  1563. \label{ch:Lvar}
  1564. \setcounter{footnote}{0}
  1565. This chapter covers compiling a subset of
  1566. \racket{Racket}\python{Python} to x86-64 assembly
  1567. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1568. integer arithmetic and local variables. We often refer to x86-64
  1569. simply as x86. The chapter first describes the \LangVar{} language
  1570. (section~\ref{sec:s0}) and then introduces x86 assembly
  1571. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1572. discuss only the instructions needed for compiling \LangVar{}. We
  1573. introduce more x86 instructions in subsequent chapters. After
  1574. introducing \LangVar{} and x86, we reflect on their differences and
  1575. create a plan to break down the translation from \LangVar{} to x86
  1576. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1577. the chapter gives detailed hints regarding each step. We aim to give
  1578. enough hints that the well-prepared reader, together with a few
  1579. friends, can implement a compiler from \LangVar{} to x86 in a short
  1580. time. To suggest the scale of this first compiler, we note that the
  1581. instructor solution for the \LangVar{} compiler is approximately
  1582. \racket{500}\python{300} lines of code.
  1583. \section{The \LangVar{} Language}
  1584. \label{sec:s0}
  1585. \index{subject}{variable}
  1586. The \LangVar{} language extends the \LangInt{} language with
  1587. variables. The concrete syntax of the \LangVar{} language is defined
  1588. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1589. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1590. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1591. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1592. \key{-} is a unary operator, and \key{+} is a binary operator.
  1593. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1594. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1595. the top of the program.
  1596. %% The $\itm{info}$
  1597. %% field of the \key{Program} structure contains an \emph{association
  1598. %% list} (a list of key-value pairs) that is used to communicate
  1599. %% auxiliary data from one compiler pass the next.
  1600. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1601. exhibit several compilation techniques.
  1602. \newcommand{\LvarGrammarRacket}{
  1603. \begin{array}{rcl}
  1604. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1605. \end{array}
  1606. }
  1607. \newcommand{\LvarASTRacket}{
  1608. \begin{array}{rcl}
  1609. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1610. \end{array}
  1611. }
  1612. \newcommand{\LvarGrammarPython}{
  1613. \begin{array}{rcl}
  1614. \Exp &::=& \Var{} \\
  1615. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1616. \end{array}
  1617. }
  1618. \newcommand{\LvarASTPython}{
  1619. \begin{array}{rcl}
  1620. \Exp{} &::=& \VAR{\Var{}} \\
  1621. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1622. \end{array}
  1623. }
  1624. \begin{figure}[tp]
  1625. \centering
  1626. \begin{tcolorbox}[colback=white]
  1627. {\if\edition\racketEd
  1628. \[
  1629. \begin{array}{l}
  1630. \gray{\LintGrammarRacket{}} \\ \hline
  1631. \LvarGrammarRacket{} \\
  1632. \begin{array}{rcl}
  1633. \LangVarM{} &::=& \Exp
  1634. \end{array}
  1635. \end{array}
  1636. \]
  1637. \fi}
  1638. {\if\edition\pythonEd
  1639. \[
  1640. \begin{array}{l}
  1641. \gray{\LintGrammarPython} \\ \hline
  1642. \LvarGrammarPython \\
  1643. \begin{array}{rcl}
  1644. \LangVarM{} &::=& \Stmt^{*}
  1645. \end{array}
  1646. \end{array}
  1647. \]
  1648. \fi}
  1649. \end{tcolorbox}
  1650. \caption{The concrete syntax of \LangVar{}.}
  1651. \label{fig:Lvar-concrete-syntax}
  1652. \end{figure}
  1653. \begin{figure}[tp]
  1654. \centering
  1655. \begin{tcolorbox}[colback=white]
  1656. {\if\edition\racketEd
  1657. \[
  1658. \begin{array}{l}
  1659. \gray{\LintASTRacket{}} \\ \hline
  1660. \LvarASTRacket \\
  1661. \begin{array}{rcl}
  1662. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1663. \end{array}
  1664. \end{array}
  1665. \]
  1666. \fi}
  1667. {\if\edition\pythonEd
  1668. \[
  1669. \begin{array}{l}
  1670. \gray{\LintASTPython}\\ \hline
  1671. \LvarASTPython \\
  1672. \begin{array}{rcl}
  1673. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1674. \end{array}
  1675. \end{array}
  1676. \]
  1677. \fi}
  1678. \end{tcolorbox}
  1679. \caption{The abstract syntax of \LangVar{}.}
  1680. \label{fig:Lvar-syntax}
  1681. \end{figure}
  1682. {\if\edition\racketEd
  1683. Let us dive further into the syntax and semantics of the \LangVar{}
  1684. language. The \key{let} feature defines a variable for use within its
  1685. body and initializes the variable with the value of an expression.
  1686. The abstract syntax for \key{let} is shown in
  1687. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1688. \begin{lstlisting}
  1689. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1690. \end{lstlisting}
  1691. For example, the following program initializes \code{x} to $32$ and then
  1692. evaluates the body \code{(+ 10 x)}, producing $42$.
  1693. \begin{lstlisting}
  1694. (let ([x (+ 12 20)]) (+ 10 x))
  1695. \end{lstlisting}
  1696. \fi}
  1697. %
  1698. {\if\edition\pythonEd
  1699. %
  1700. The \LangVar{} language includes assignment statements, which define a
  1701. variable for use in later statements and initializes the variable with
  1702. the value of an expression. The abstract syntax for assignment is
  1703. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1704. assignment is \index{subject}{Assign@\texttt{Assign}}
  1705. \begin{lstlisting}
  1706. |$\itm{var}$| = |$\itm{exp}$|
  1707. \end{lstlisting}
  1708. For example, the following program initializes the variable \code{x}
  1709. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1710. \begin{lstlisting}
  1711. x = 12 + 20
  1712. print(10 + x)
  1713. \end{lstlisting}
  1714. \fi}
  1715. {\if\edition\racketEd
  1716. %
  1717. When there are multiple \key{let}s for the same variable, the closest
  1718. enclosing \key{let} is used. That is, variable definitions overshadow
  1719. prior definitions. Consider the following program with two \key{let}s
  1720. that define two variables named \code{x}. Can you figure out the
  1721. result?
  1722. \begin{lstlisting}
  1723. (let ([x 32]) (+ (let ([x 10]) x) x))
  1724. \end{lstlisting}
  1725. For the purposes of depicting which variable occurrences correspond to
  1726. which definitions, the following shows the \code{x}'s annotated with
  1727. subscripts to distinguish them. Double check that your answer for the
  1728. previous program is the same as your answer for this annotated version
  1729. of the program.
  1730. \begin{lstlisting}
  1731. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1732. \end{lstlisting}
  1733. The initializing expression is always evaluated before the body of the
  1734. \key{let}, so in the following, the \key{read} for \code{x} is
  1735. performed before the \key{read} for \code{y}. Given the input
  1736. $52$ then $10$, the following produces $42$ (not $-42$).
  1737. \begin{lstlisting}
  1738. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1739. \end{lstlisting}
  1740. \fi}
  1741. \subsection{Extensible Interpreters via Method Overriding}
  1742. \label{sec:extensible-interp}
  1743. To prepare for discussing the interpreter of \LangVar{}, we explain
  1744. why we implement it in an object-oriented style. Throughout this book
  1745. we define many interpreters, one for each language that we
  1746. study. Because each language builds on the prior one, there is a lot
  1747. of commonality between these interpreters. We want to write down the
  1748. common parts just once instead of many times. A naive interpreter for
  1749. \LangVar{} would handle the \racket{cases for variables and
  1750. \code{let}} \python{case for variables} but dispatch to an
  1751. interpreter for \LangInt{} in the rest of the cases. The following
  1752. code sketches this idea. (We explain the \code{env} parameter in
  1753. section~\ref{sec:interp-Lvar}.)
  1754. \begin{center}
  1755. {\if\edition\racketEd
  1756. \begin{minipage}{0.45\textwidth}
  1757. \begin{lstlisting}
  1758. (define ((interp_Lint env) e)
  1759. (match e
  1760. [(Prim '- (list e1))
  1761. (fx- 0 ((interp_Lint env) e1))]
  1762. ...))
  1763. \end{lstlisting}
  1764. \end{minipage}
  1765. \begin{minipage}{0.45\textwidth}
  1766. \begin{lstlisting}
  1767. (define ((interp_Lvar env) e)
  1768. (match e
  1769. [(Var x)
  1770. (dict-ref env x)]
  1771. [(Let x e body)
  1772. (define v ((interp_exp env) e))
  1773. (define env^ (dict-set env x v))
  1774. ((interp_exp env^) body)]
  1775. [else ((interp_Lint env) e)]))
  1776. \end{lstlisting}
  1777. \end{minipage}
  1778. \fi}
  1779. {\if\edition\pythonEd
  1780. \begin{minipage}{0.45\textwidth}
  1781. \begin{lstlisting}
  1782. def interp_Lint(e, env):
  1783. match e:
  1784. case UnaryOp(USub(), e1):
  1785. return - interp_Lint(e1, env)
  1786. ...
  1787. \end{lstlisting}
  1788. \end{minipage}
  1789. \begin{minipage}{0.45\textwidth}
  1790. \begin{lstlisting}
  1791. def interp_Lvar(e, env):
  1792. match e:
  1793. case Name(id):
  1794. return env[id]
  1795. case _:
  1796. return interp_Lint(e, env)
  1797. \end{lstlisting}
  1798. \end{minipage}
  1799. \fi}
  1800. \end{center}
  1801. The problem with this naive approach is that it does not handle
  1802. situations in which an \LangVar{} feature, such as a variable, is
  1803. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1804. in the following program.
  1805. {\if\edition\racketEd
  1806. \begin{lstlisting}
  1807. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1808. \end{lstlisting}
  1809. \fi}
  1810. {\if\edition\pythonEd
  1811. \begin{minipage}{0.96\textwidth}
  1812. \begin{lstlisting}
  1813. y = 10
  1814. print(-y)
  1815. \end{lstlisting}
  1816. \end{minipage}
  1817. \fi}
  1818. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1819. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1820. then it recursively calls \code{interp\_Lint} again on its argument.
  1821. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1822. an error!
  1823. To make our interpreters extensible we need something called
  1824. \emph{open recursion}\index{subject}{open recursion}, in which the
  1825. tying of the recursive knot is delayed until the functions are
  1826. composed. Object-oriented languages provide open recursion via method
  1827. overriding\index{subject}{method overriding}. The following code uses
  1828. method overriding to interpret \LangInt{} and \LangVar{} using
  1829. %
  1830. \racket{the
  1831. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1832. \index{subject}{class} feature of Racket.}
  1833. %
  1834. \python{a Python \code{class} definition.}
  1835. %
  1836. We define one class for each language and define a method for
  1837. interpreting expressions inside each class. The class for \LangVar{}
  1838. inherits from the class for \LangInt{}, and the method
  1839. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1840. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1841. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1842. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1843. \code{interp\_exp} in \LangInt{}.
  1844. \begin{center}
  1845. \hspace{-20pt}
  1846. {\if\edition\racketEd
  1847. \begin{minipage}{0.45\textwidth}
  1848. \begin{lstlisting}
  1849. (define interp-Lint-class
  1850. (class object%
  1851. (define/public ((interp_exp env) e)
  1852. (match e
  1853. [(Prim '- (list e))
  1854. (fx- 0 ((interp_exp env) e))]
  1855. ...))
  1856. ...))
  1857. \end{lstlisting}
  1858. \end{minipage}
  1859. \begin{minipage}{0.45\textwidth}
  1860. \begin{lstlisting}
  1861. (define interp-Lvar-class
  1862. (class interp-Lint-class
  1863. (define/override ((interp_exp env) e)
  1864. (match e
  1865. [(Var x)
  1866. (dict-ref env x)]
  1867. [(Let x e body)
  1868. (define v ((interp_exp env) e))
  1869. (define env^ (dict-set env x v))
  1870. ((interp_exp env^) body)]
  1871. [else
  1872. (super (interp_exp env) e)]))
  1873. ...
  1874. ))
  1875. \end{lstlisting}
  1876. \end{minipage}
  1877. \fi}
  1878. {\if\edition\pythonEd
  1879. \begin{minipage}{0.45\textwidth}
  1880. \begin{lstlisting}
  1881. class InterpLint:
  1882. def interp_exp(e):
  1883. match e:
  1884. case UnaryOp(USub(), e1):
  1885. return -self.interp_exp(e1)
  1886. ...
  1887. ...
  1888. \end{lstlisting}
  1889. \end{minipage}
  1890. \begin{minipage}{0.45\textwidth}
  1891. \begin{lstlisting}
  1892. def InterpLvar(InterpLint):
  1893. def interp_exp(e):
  1894. match e:
  1895. case Name(id):
  1896. return env[id]
  1897. case _:
  1898. return super().interp_exp(e)
  1899. ...
  1900. \end{lstlisting}
  1901. \end{minipage}
  1902. \fi}
  1903. \end{center}
  1904. Getting back to the troublesome example, repeated here
  1905. {\if\edition\racketEd
  1906. \begin{lstlisting}
  1907. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1908. \end{lstlisting}
  1909. \fi}
  1910. {\if\edition\pythonEd
  1911. \begin{lstlisting}
  1912. y = 10
  1913. print(-y)
  1914. \end{lstlisting}
  1915. \fi}
  1916. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1917. \racket{on this expression,}
  1918. \python{on the \code{-y} expression,}
  1919. %
  1920. which we call \code{e0}, by creating an object of the \LangVar{} class
  1921. and calling the \code{interp\_exp} method
  1922. {\if\edition\racketEd
  1923. \begin{lstlisting}
  1924. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1925. \end{lstlisting}
  1926. \fi}
  1927. {\if\edition\pythonEd
  1928. \begin{lstlisting}
  1929. InterpLvar().interp_exp(e0)
  1930. \end{lstlisting}
  1931. \fi}
  1932. \noindent To process the \code{-} operator, the default case of
  1933. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1934. method in \LangInt{}. But then for the recursive method call, it
  1935. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1936. \code{Var} node is handled correctly. Thus, method overriding gives us
  1937. the open recursion that we need to implement our interpreters in an
  1938. extensible way.
  1939. \subsection{Definitional Interpreter for \LangVar{}}
  1940. \label{sec:interp-Lvar}
  1941. Having justified the use of classes and methods to implement
  1942. interpreters, we revisit the definitional interpreter for \LangInt{}
  1943. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1944. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1945. The interpreter for \LangVar{} adds two new \key{match} cases for
  1946. variables and \racket{\key{let}}\python{assignment}. For
  1947. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1948. value bound to a variable to all the uses of the variable. To
  1949. accomplish this, we maintain a mapping from variables to values called
  1950. an \emph{environment}\index{subject}{environment}.
  1951. %
  1952. We use
  1953. %
  1954. \racket{an association list (alist) }%
  1955. %
  1956. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1957. %
  1958. to represent the environment.
  1959. %
  1960. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1961. and the \code{racket/dict} package.}
  1962. %
  1963. The \code{interp\_exp} function takes the current environment,
  1964. \code{env}, as an extra parameter. When the interpreter encounters a
  1965. variable, it looks up the corresponding value in the dictionary.
  1966. %
  1967. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1968. initializing expression, extends the environment with the result
  1969. value bound to the variable, using \code{dict-set}, then evaluates
  1970. the body of the \key{Let}.}
  1971. %
  1972. \python{When the interpreter encounters an assignment, it evaluates
  1973. the initializing expression and then associates the resulting value
  1974. with the variable in the environment.}
  1975. \begin{figure}[tp]
  1976. \begin{tcolorbox}[colback=white]
  1977. {\if\edition\racketEd
  1978. \begin{lstlisting}
  1979. (define interp-Lint-class
  1980. (class object%
  1981. (super-new)
  1982. (define/public ((interp_exp env) e)
  1983. (match e
  1984. [(Int n) n]
  1985. [(Prim 'read '())
  1986. (define r (read))
  1987. (cond [(fixnum? r) r]
  1988. [else (error 'interp_exp "expected an integer" r)])]
  1989. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1990. [(Prim '+ (list e1 e2))
  1991. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1992. [(Prim '- (list e1 e2))
  1993. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1994. (define/public (interp_program p)
  1995. (match p
  1996. [(Program '() e) ((interp_exp '()) e)]))
  1997. ))
  1998. \end{lstlisting}
  1999. \fi}
  2000. {\if\edition\pythonEd
  2001. \begin{lstlisting}
  2002. class InterpLint:
  2003. def interp_exp(self, e, env):
  2004. match e:
  2005. case BinOp(left, Add(), right):
  2006. return self.interp_exp(left, env) + self.interp_exp(right, env)
  2007. case BinOp(left, Sub(), right):
  2008. return self.interp_exp(left, env) - self.interp_exp(right, env)
  2009. case UnaryOp(USub(), v):
  2010. return - self.interp_exp(v, env)
  2011. case Constant(value):
  2012. return value
  2013. case Call(Name('input_int'), []):
  2014. return int(input())
  2015. def interp_stmts(self, ss, env):
  2016. if len(ss) == 0:
  2017. return
  2018. match ss[0]:
  2019. case Expr(Call(Name('print'), [arg])):
  2020. print(self.interp_exp(arg, env), end='')
  2021. return self.interp_stmts(ss[1:], env)
  2022. case Expr(value):
  2023. self.interp_exp(value, env)
  2024. return self.interp_stmts(ss[1:], env)
  2025. def interp(self, p):
  2026. match p:
  2027. case Module(body):
  2028. self.interp_stmts(body, {})
  2029. def interp_Lint(p):
  2030. return InterpLint().interp(p)
  2031. \end{lstlisting}
  2032. \fi}
  2033. \end{tcolorbox}
  2034. \caption{Interpreter for \LangInt{} as a class.}
  2035. \label{fig:interp-Lint-class}
  2036. \end{figure}
  2037. \begin{figure}[tp]
  2038. \begin{tcolorbox}[colback=white]
  2039. {\if\edition\racketEd
  2040. \begin{lstlisting}
  2041. (define interp-Lvar-class
  2042. (class interp-Lint-class
  2043. (super-new)
  2044. (define/override ((interp_exp env) e)
  2045. (match e
  2046. [(Var x) (dict-ref env x)]
  2047. [(Let x e body)
  2048. (define new-env (dict-set env x ((interp_exp env) e)))
  2049. ((interp_exp new-env) body)]
  2050. [else ((super interp-exp env) e)]))
  2051. ))
  2052. (define (interp_Lvar p)
  2053. (send (new interp-Lvar-class) interp_program p))
  2054. \end{lstlisting}
  2055. \fi}
  2056. {\if\edition\pythonEd
  2057. \begin{lstlisting}
  2058. class InterpLvar(InterpLint):
  2059. def interp_exp(self, e, env):
  2060. match e:
  2061. case Name(id):
  2062. return env[id]
  2063. case _:
  2064. return super().interp_exp(e, env)
  2065. def interp_stmts(self, ss, env):
  2066. if len(ss) == 0:
  2067. return
  2068. match ss[0]:
  2069. case Assign([lhs], value):
  2070. env[lhs.id] = self.interp_exp(value, env)
  2071. return self.interp_stmts(ss[1:], env)
  2072. case _:
  2073. return super().interp_stmts(ss, env)
  2074. def interp_Lvar(p):
  2075. return InterpLvar().interp(p)
  2076. \end{lstlisting}
  2077. \fi}
  2078. \end{tcolorbox}
  2079. \caption{Interpreter for the \LangVar{} language.}
  2080. \label{fig:interp-Lvar}
  2081. \end{figure}
  2082. {\if\edition\racketEd
  2083. \begin{figure}[tp]
  2084. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2085. \small
  2086. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2087. An \emph{association list} (called an alist) is a list of key-value pairs.
  2088. For example, we can map people to their ages with an alist
  2089. \index{subject}{alist}\index{subject}{association list}
  2090. \begin{lstlisting}[basicstyle=\ttfamily]
  2091. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2092. \end{lstlisting}
  2093. The \emph{dictionary} interface is for mapping keys to values.
  2094. Every alist implements this interface. \index{subject}{dictionary}
  2095. The package
  2096. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2097. provides many functions for working with dictionaries, such as
  2098. \begin{description}
  2099. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2100. returns the value associated with the given $\itm{key}$.
  2101. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2102. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2103. and otherwise is the same as $\itm{dict}$.
  2104. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2105. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2106. of keys and values in $\itm{dict}$. For example, the following
  2107. creates a new alist in which the ages are incremented:
  2108. \end{description}
  2109. \vspace{-10pt}
  2110. \begin{lstlisting}[basicstyle=\ttfamily]
  2111. (for/list ([(k v) (in-dict ages)])
  2112. (cons k (add1 v)))
  2113. \end{lstlisting}
  2114. \end{tcolorbox}
  2115. %\end{wrapfigure}
  2116. \caption{Association lists implement the dictionary interface.}
  2117. \label{fig:alist}
  2118. \end{figure}
  2119. \fi}
  2120. The goal for this chapter is to implement a compiler that translates
  2121. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2122. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2123. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2124. That is, they output the same integer $n$. We depict this correctness
  2125. criteria in the following diagram:
  2126. \[
  2127. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2128. \node (p1) at (0, 0) {$P_1$};
  2129. \node (p2) at (4, 0) {$P_2$};
  2130. \node (o) at (4, -2) {$n$};
  2131. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2132. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2133. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2134. \end{tikzpicture}
  2135. \]
  2136. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2137. compiling \LangVar{}.
  2138. \section{The \LangXInt{} Assembly Language}
  2139. \label{sec:x86}
  2140. \index{subject}{x86}
  2141. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2142. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2143. assembler.
  2144. %
  2145. A program begins with a \code{main} label followed by a sequence of
  2146. instructions. The \key{globl} directive makes the \key{main} procedure
  2147. externally visible so that the operating system can call it.
  2148. %
  2149. An x86 program is stored in the computer's memory. For our purposes,
  2150. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2151. values. The computer has a \emph{program counter}
  2152. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2153. \code{rip} register that points to the address of the next instruction
  2154. to be executed. For most instructions, the program counter is
  2155. incremented after the instruction is executed so that it points to the
  2156. next instruction in memory. Most x86 instructions take two operands,
  2157. each of which is an integer constant (called an \emph{immediate
  2158. value}\index{subject}{immediate value}), a
  2159. \emph{register}\index{subject}{register}, or a memory location.
  2160. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2161. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2162. && \key{r8} \MID \key{r9} \MID \key{r10}
  2163. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2164. \MID \key{r14} \MID \key{r15}}
  2165. \newcommand{\GrammarXInt}{
  2166. \begin{array}{rcl}
  2167. \Reg &::=& \allregisters{} \\
  2168. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2169. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2170. \key{subq} \; \Arg\key{,} \Arg \MID
  2171. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2172. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2173. \key{callq} \; \mathit{label} \MID
  2174. \key{retq} \MID
  2175. \key{jmp}\,\itm{label} \MID \\
  2176. && \itm{label}\key{:}\; \Instr
  2177. \end{array}
  2178. }
  2179. \begin{figure}[tp]
  2180. \begin{tcolorbox}[colback=white]
  2181. {\if\edition\racketEd
  2182. \[
  2183. \begin{array}{l}
  2184. \GrammarXInt \\
  2185. \begin{array}{lcl}
  2186. \LangXIntM{} &::= & \key{.globl main}\\
  2187. & & \key{main:} \; \Instr\ldots
  2188. \end{array}
  2189. \end{array}
  2190. \]
  2191. \fi}
  2192. {\if\edition\pythonEd
  2193. \[
  2194. \begin{array}{lcl}
  2195. \Reg &::=& \allregisters{} \\
  2196. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2197. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2198. \key{subq} \; \Arg\key{,} \Arg \MID
  2199. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2200. && \key{callq} \; \mathit{label} \MID
  2201. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2202. \LangXIntM{} &::= & \key{.globl main}\\
  2203. & & \key{main:} \; \Instr^{*}
  2204. \end{array}
  2205. \]
  2206. \fi}
  2207. \end{tcolorbox}
  2208. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2209. \label{fig:x86-int-concrete}
  2210. \end{figure}
  2211. A register is a special kind of variable that holds a 64-bit
  2212. value. There are 16 general-purpose registers in the computer; their
  2213. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2214. written with a percent sign, \key{\%}, followed by the register name,
  2215. for example \key{\%rax}.
  2216. An immediate value is written using the notation \key{\$}$n$ where $n$
  2217. is an integer.
  2218. %
  2219. %
  2220. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2221. which obtains the address stored in register $r$ and then adds $n$
  2222. bytes to the address. The resulting address is used to load or to store
  2223. to memory depending on whether it occurs as a source or destination
  2224. argument of an instruction.
  2225. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2226. the source $s$ and destination $d$, applies the arithmetic operation,
  2227. and then writes the result to the destination $d$. \index{subject}{instruction}
  2228. %
  2229. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2230. stores the result in $d$.
  2231. %
  2232. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2233. specified by the label, and $\key{retq}$ returns from a procedure to
  2234. its caller.
  2235. %
  2236. We discuss procedure calls in more detail further in this chapter and
  2237. in chapter~\ref{ch:Lfun}.
  2238. %
  2239. The last letter \key{q} indicates that these instructions operate on
  2240. quadwords which are 64-bit values.
  2241. %
  2242. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2243. counter to the address of the instruction immediately after the
  2244. specified label.}
  2245. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2246. all the x86 instructions used in this book.
  2247. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2248. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2249. \lstinline{movq $10, %rax}
  2250. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2251. adds $32$ to the $10$ in \key{rax} and
  2252. puts the result, $42$, into \key{rax}.
  2253. %
  2254. The last instruction \key{retq} finishes the \key{main} function by
  2255. returning the integer in \key{rax} to the operating system. The
  2256. operating system interprets this integer as the program's exit
  2257. code. By convention, an exit code of 0 indicates that a program has
  2258. completed successfully, and all other exit codes indicate various
  2259. errors.
  2260. %
  2261. \racket{However, in this book we return the result of the program
  2262. as the exit code.}
  2263. \begin{figure}[tbp]
  2264. \begin{minipage}{0.45\textwidth}
  2265. \begin{tcolorbox}[colback=white]
  2266. \begin{lstlisting}
  2267. .globl main
  2268. main:
  2269. movq $10, %rax
  2270. addq $32, %rax
  2271. retq
  2272. \end{lstlisting}
  2273. \end{tcolorbox}
  2274. \end{minipage}
  2275. \caption{An x86 program that computes
  2276. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2277. \label{fig:p0-x86}
  2278. \end{figure}
  2279. We exhibit the use of memory for storing intermediate results in the
  2280. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2281. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2282. uses a region of memory called the \emph{procedure call stack}
  2283. (\emph{stack} for
  2284. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2285. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2286. for each procedure call. The memory layout for an individual frame is
  2287. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2288. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2289. address of the item at the top of the stack. In general, we use the
  2290. term \emph{pointer}\index{subject}{pointer} for something that
  2291. contains an address. The stack grows downward in memory, so we
  2292. increase the size of the stack by subtracting from the stack pointer.
  2293. In the context of a procedure call, the \emph{return
  2294. address}\index{subject}{return address} is the location of the
  2295. instruction that immediately follows the call instruction on the
  2296. caller side. The function call instruction, \code{callq}, pushes the
  2297. return address onto the stack prior to jumping to the procedure. The
  2298. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2299. pointer} and is used to access variables that are stored in the
  2300. frame of the current procedure call. The base pointer of the caller
  2301. is stored immediately after the return address.
  2302. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2303. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2304. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2305. $-16\key{(\%rbp)}$, and so on.
  2306. \begin{figure}[tbp]
  2307. \begin{minipage}{0.66\textwidth}
  2308. \begin{tcolorbox}[colback=white]
  2309. {\if\edition\racketEd
  2310. \begin{lstlisting}
  2311. start:
  2312. movq $10, -8(%rbp)
  2313. negq -8(%rbp)
  2314. movq -8(%rbp), %rax
  2315. addq $52, %rax
  2316. jmp conclusion
  2317. .globl main
  2318. main:
  2319. pushq %rbp
  2320. movq %rsp, %rbp
  2321. subq $16, %rsp
  2322. jmp start
  2323. conclusion:
  2324. addq $16, %rsp
  2325. popq %rbp
  2326. retq
  2327. \end{lstlisting}
  2328. \fi}
  2329. {\if\edition\pythonEd
  2330. \begin{lstlisting}
  2331. .globl main
  2332. main:
  2333. pushq %rbp
  2334. movq %rsp, %rbp
  2335. subq $16, %rsp
  2336. movq $10, -8(%rbp)
  2337. negq -8(%rbp)
  2338. movq -8(%rbp), %rax
  2339. addq $52, %rax
  2340. addq $16, %rsp
  2341. popq %rbp
  2342. retq
  2343. \end{lstlisting}
  2344. \fi}
  2345. \end{tcolorbox}
  2346. \end{minipage}
  2347. \caption{An x86 program that computes
  2348. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2349. \label{fig:p1-x86}
  2350. \end{figure}
  2351. \begin{figure}[tbp]
  2352. \begin{minipage}{0.66\textwidth}
  2353. \begin{tcolorbox}[colback=white]
  2354. \centering
  2355. \begin{tabular}{|r|l|} \hline
  2356. Position & Contents \\ \hline
  2357. $8$(\key{\%rbp}) & return address \\
  2358. $0$(\key{\%rbp}) & old \key{rbp} \\
  2359. $-8$(\key{\%rbp}) & variable $1$ \\
  2360. $-16$(\key{\%rbp}) & variable $2$ \\
  2361. \ldots & \ldots \\
  2362. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2363. \end{tabular}
  2364. \end{tcolorbox}
  2365. \end{minipage}
  2366. \caption{Memory layout of a frame.}
  2367. \label{fig:frame}
  2368. \end{figure}
  2369. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2370. is transferred from the operating system to the \code{main} function.
  2371. The operating system issues a \code{callq main} instruction that
  2372. pushes its return address on the stack and then jumps to
  2373. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2374. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2375. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2376. out of alignment (because the \code{callq} pushed the return address).
  2377. The first three instructions are the typical
  2378. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2379. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2380. pointer \code{rsp} and then saves the base pointer of the caller at
  2381. address \code{rsp} on the stack. The next instruction \code{movq
  2382. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2383. which is pointing to the location of the old base pointer. The
  2384. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2385. make enough room for storing variables. This program needs one
  2386. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2387. 16-byte-aligned, and then we are ready to make calls to other functions.
  2388. \racket{The last instruction of the prelude is \code{jmp start}, which
  2389. transfers control to the instructions that were generated from the
  2390. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2391. \racket{The first instruction under the \code{start} label is}
  2392. %
  2393. \python{The first instruction after the prelude is}
  2394. %
  2395. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2396. %
  2397. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2398. $1$ to $-10$.
  2399. %
  2400. The next instruction moves the $-10$ from variable $1$ into the
  2401. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2402. the value in \code{rax}, updating its contents to $42$.
  2403. \racket{The three instructions under the label \code{conclusion} are the
  2404. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2405. %
  2406. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2407. \code{main} function consists of the last three instructions.}
  2408. %
  2409. The first two restore the \code{rsp} and \code{rbp} registers to their
  2410. states at the beginning of the procedure. In particular,
  2411. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2412. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2413. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2414. \key{retq}, jumps back to the procedure that called this one and adds
  2415. $8$ to the stack pointer.
  2416. Our compiler needs a convenient representation for manipulating x86
  2417. programs, so we define an abstract syntax for x86, shown in
  2418. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2419. \LangXInt{}.
  2420. %
  2421. {\if\edition\pythonEd%
  2422. The main difference between this and the concrete syntax of \LangXInt{}
  2423. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2424. names, and register names are explicitly represented by strings.
  2425. \fi} %
  2426. {\if\edition\racketEd
  2427. The main difference between this and the concrete syntax of \LangXInt{}
  2428. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2429. front of every instruction. Instead instructions are grouped into
  2430. \emph{basic blocks}\index{subject}{basic block} with a
  2431. label associated with every basic block; this is why the \key{X86Program}
  2432. struct includes an alist mapping labels to basic blocks. The reason for this
  2433. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2434. introduce conditional branching. The \code{Block} structure includes
  2435. an $\itm{info}$ field that is not needed in this chapter but becomes
  2436. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2437. $\itm{info}$ field should contain an empty list.
  2438. \fi}
  2439. %
  2440. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2441. node includes an integer for representing the arity of the function,
  2442. that is, the number of arguments, which is helpful to know during
  2443. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2444. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2445. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2446. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2447. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2448. \MID \skey{r14} \MID \skey{r15}}
  2449. \newcommand{\ASTXIntRacket}{
  2450. \begin{array}{lcl}
  2451. \Reg &::=& \allregisters{} \\
  2452. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2453. \MID \DEREF{\Reg}{\Int} \\
  2454. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2455. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2456. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2457. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2458. &\MID& \PUSHQ{\Arg}
  2459. \MID \POPQ{\Arg} \\
  2460. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2461. \MID \RETQ{}
  2462. \MID \JMP{\itm{label}} \\
  2463. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2464. \end{array}
  2465. }
  2466. \begin{figure}[tp]
  2467. \begin{tcolorbox}[colback=white]
  2468. \small
  2469. {\if\edition\racketEd
  2470. \[\arraycolsep=3pt
  2471. \begin{array}{l}
  2472. \ASTXIntRacket \\
  2473. \begin{array}{lcl}
  2474. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2475. \end{array}
  2476. \end{array}
  2477. \]
  2478. \fi}
  2479. {\if\edition\pythonEd
  2480. \[
  2481. \begin{array}{lcl}
  2482. \Reg &::=& \allastregisters{} \\
  2483. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2484. \MID \DEREF{\Reg}{\Int} \\
  2485. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2486. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2487. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2488. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2489. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2490. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2491. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2492. \end{array}
  2493. \]
  2494. \fi}
  2495. \end{tcolorbox}
  2496. \caption{The abstract syntax of \LangXInt{} assembly.}
  2497. \label{fig:x86-int-ast}
  2498. \end{figure}
  2499. \section{Planning the Trip to x86}
  2500. \label{sec:plan-s0-x86}
  2501. To compile one language to another, it helps to focus on the
  2502. differences between the two languages because the compiler will need
  2503. to bridge those differences. What are the differences between \LangVar{}
  2504. and x86 assembly? Here are some of the most important ones:
  2505. \begin{enumerate}
  2506. \item x86 arithmetic instructions typically have two arguments and
  2507. update the second argument in place. In contrast, \LangVar{}
  2508. arithmetic operations take two arguments and produce a new value.
  2509. An x86 instruction may have at most one memory-accessing argument.
  2510. Furthermore, some x86 instructions place special restrictions on
  2511. their arguments.
  2512. \item An argument of an \LangVar{} operator can be a deeply nested
  2513. expression, whereas x86 instructions restrict their arguments to be
  2514. integer constants, registers, and memory locations.
  2515. {\if\edition\racketEd
  2516. \item The order of execution in x86 is explicit in the syntax, which
  2517. is a sequence of instructions and jumps to labeled positions,
  2518. whereas in \LangVar{} the order of evaluation is a left-to-right
  2519. depth-first traversal of the abstract syntax tree. \fi}
  2520. \item A program in \LangVar{} can have any number of variables,
  2521. whereas x86 has 16 registers and the procedure call stack.
  2522. {\if\edition\racketEd
  2523. \item Variables in \LangVar{} can shadow other variables with the
  2524. same name. In x86, registers have unique names, and memory locations
  2525. have unique addresses.
  2526. \fi}
  2527. \end{enumerate}
  2528. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2529. down the problem into several steps, which deal with these differences
  2530. one at a time. Each of these steps is called a \emph{pass} of the
  2531. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2532. %
  2533. This term indicates that each step passes over, or traverses, the AST
  2534. of the program.
  2535. %
  2536. Furthermore, we follow the nanopass approach, which means that we
  2537. strive for each pass to accomplish one clear objective rather than two
  2538. or three at the same time.
  2539. %
  2540. We begin by sketching how we might implement each pass and give each
  2541. pass a name. We then figure out an ordering of the passes and the
  2542. input/output language for each pass. The very first pass has
  2543. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2544. its output language. In between these two passes, we can choose
  2545. whichever language is most convenient for expressing the output of
  2546. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2547. \emph{intermediate languages} of our own design. Finally, to
  2548. implement each pass we write one recursive function per nonterminal in
  2549. the grammar of the input language of the pass.
  2550. \index{subject}{intermediate language}
  2551. Our compiler for \LangVar{} consists of the following passes:
  2552. %
  2553. \begin{description}
  2554. {\if\edition\racketEd
  2555. \item[\key{uniquify}] deals with the shadowing of variables by
  2556. renaming every variable to a unique name.
  2557. \fi}
  2558. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2559. of a primitive operation or function call is a variable or integer,
  2560. that is, an \emph{atomic} expression. We refer to nonatomic
  2561. expressions as \emph{complex}. This pass introduces temporary
  2562. variables to hold the results of complex
  2563. subexpressions.\index{subject}{atomic
  2564. expression}\index{subject}{complex expression}%
  2565. {\if\edition\racketEd
  2566. \item[\key{explicate\_control}] makes the execution order of the
  2567. program explicit. It converts the abstract syntax tree
  2568. representation into a graph in which each node is a labeled sequence
  2569. of statements and the edges are \code{goto} statements.
  2570. \fi}
  2571. \item[\key{select\_instructions}] handles the difference between
  2572. \LangVar{} operations and x86 instructions. This pass converts each
  2573. \LangVar{} operation to a short sequence of instructions that
  2574. accomplishes the same task.
  2575. \item[\key{assign\_homes}] replaces variables with registers or stack
  2576. locations.
  2577. \end{description}
  2578. %
  2579. {\if\edition\racketEd
  2580. %
  2581. Our treatment of \code{remove\_complex\_operands} and
  2582. \code{explicate\_control} as separate passes is an example of the
  2583. nanopass approach\footnote{For analogous decompositions of the
  2584. translation into continuation passing style, see the work of
  2585. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2586. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2587. %
  2588. \fi}
  2589. The next question is, in what order should we apply these passes? This
  2590. question can be challenging because it is difficult to know ahead of
  2591. time which orderings will be better (that is, will be easier to
  2592. implement, produce more efficient code, and so on), and therefore
  2593. ordering often involves trial and error. Nevertheless, we can plan
  2594. ahead and make educated choices regarding the ordering.
  2595. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2596. \key{uniquify}? The \key{uniquify} pass should come first because
  2597. \key{explicate\_control} changes all the \key{let}-bound variables to
  2598. become local variables whose scope is the entire program, which would
  2599. confuse variables with the same name.}
  2600. %
  2601. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2602. because the later removes the \key{let} form, but it is convenient to
  2603. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2604. %
  2605. \racket{The ordering of \key{uniquify} with respect to
  2606. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2607. \key{uniquify} to come first.}
  2608. The \key{select\_instructions} and \key{assign\_homes} passes are
  2609. intertwined.
  2610. %
  2611. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2612. passing arguments to functions and that it is preferable to assign
  2613. parameters to their corresponding registers. This suggests that it
  2614. would be better to start with the \key{select\_instructions} pass,
  2615. which generates the instructions for argument passing, before
  2616. performing register allocation.
  2617. %
  2618. On the other hand, by selecting instructions first we may run into a
  2619. dead end in \key{assign\_homes}. Recall that only one argument of an
  2620. x86 instruction may be a memory access, but \key{assign\_homes} might
  2621. be forced to assign both arguments to memory locations.
  2622. %
  2623. A sophisticated approach is to repeat the two passes until a solution
  2624. is found. However, to reduce implementation complexity we recommend
  2625. placing \key{select\_instructions} first, followed by the
  2626. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2627. that uses a reserved register to fix outstanding problems.
  2628. \begin{figure}[tbp]
  2629. \begin{tcolorbox}[colback=white]
  2630. {\if\edition\racketEd
  2631. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2632. \node (Lvar) at (0,2) {\large \LangVar{}};
  2633. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2634. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2635. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2636. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2637. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2638. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2639. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2640. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2641. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2642. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2643. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2644. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2645. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2646. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2647. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2648. \end{tikzpicture}
  2649. \fi}
  2650. {\if\edition\pythonEd
  2651. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2652. \node (Lvar) at (0,2) {\large \LangVar{}};
  2653. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2654. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2655. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2656. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2657. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2658. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2659. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  2660. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2661. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2662. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2663. \end{tikzpicture}
  2664. \fi}
  2665. \end{tcolorbox}
  2666. \caption{Diagram of the passes for compiling \LangVar{}. }
  2667. \label{fig:Lvar-passes}
  2668. \end{figure}
  2669. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2670. passes and identifies the input and output language of each pass.
  2671. %
  2672. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2673. language, which extends \LangXInt{} with an unbounded number of
  2674. program-scope variables and removes the restrictions regarding
  2675. instruction arguments.
  2676. %
  2677. The last pass, \key{prelude\_and\_conclusion}, places the program
  2678. instructions inside a \code{main} function with instructions for the
  2679. prelude and conclusion.
  2680. %
  2681. \racket{In the next section we discuss the \LangCVar{} intermediate
  2682. language that serves as the output of \code{explicate\_control}.}
  2683. %
  2684. The remainder of this chapter provides guidance on the implementation
  2685. of each of the compiler passes represented in
  2686. figure~\ref{fig:Lvar-passes}.
  2687. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2688. %% are programs that are still in the \LangVar{} language, though the
  2689. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2690. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2691. %% %
  2692. %% The output of \code{explicate\_control} is in an intermediate language
  2693. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2694. %% syntax, which we introduce in the next section. The
  2695. %% \key{select-instruction} pass translates from \LangCVar{} to
  2696. %% \LangXVar{}. The \key{assign-homes} and
  2697. %% \key{patch-instructions}
  2698. %% passes input and output variants of x86 assembly.
  2699. \newcommand{\CvarGrammarRacket}{
  2700. \begin{array}{lcl}
  2701. \Atm &::=& \Int \MID \Var \\
  2702. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2703. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2704. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2705. \end{array}
  2706. }
  2707. \newcommand{\CvarASTRacket}{
  2708. \begin{array}{lcl}
  2709. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2710. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2711. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2712. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2713. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2714. \end{array}
  2715. }
  2716. {\if\edition\racketEd
  2717. \subsection{The \LangCVar{} Intermediate Language}
  2718. The output of \code{explicate\_control} is similar to the C
  2719. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2720. categories for expressions and statements, so we name it \LangCVar{}.
  2721. This style of intermediate language is also known as
  2722. \emph{three-address code}, to emphasize that the typical form of a
  2723. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2724. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2725. The concrete syntax for \LangCVar{} is shown in
  2726. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2727. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2728. %
  2729. The \LangCVar{} language supports the same operators as \LangVar{} but
  2730. the arguments of operators are restricted to atomic
  2731. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2732. assignment statements that can be executed in sequence using the
  2733. \key{Seq} form. A sequence of statements always ends with
  2734. \key{Return}, a guarantee that is baked into the grammar rules for
  2735. \itm{tail}. The naming of this nonterminal comes from the term
  2736. \emph{tail position}\index{subject}{tail position}, which refers to an
  2737. expression that is the last one to execute within a function or
  2738. program.
  2739. A \LangCVar{} program consists of an alist mapping labels to
  2740. tails. This is more general than necessary for the present chapter, as
  2741. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2742. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2743. there is just one label, \key{start}, and the whole program is
  2744. its tail.
  2745. %
  2746. The $\itm{info}$ field of the \key{CProgram} form, after the
  2747. \code{explicate\_control} pass, contains an alist that associates the
  2748. symbol \key{locals} with a list of all the variables used in the
  2749. program. At the start of the program, these variables are
  2750. uninitialized; they become initialized on their first assignment.
  2751. \begin{figure}[tbp]
  2752. \begin{tcolorbox}[colback=white]
  2753. \[
  2754. \begin{array}{l}
  2755. \CvarGrammarRacket \\
  2756. \begin{array}{lcl}
  2757. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2758. \end{array}
  2759. \end{array}
  2760. \]
  2761. \end{tcolorbox}
  2762. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2763. \label{fig:c0-concrete-syntax}
  2764. \end{figure}
  2765. \begin{figure}[tbp]
  2766. \begin{tcolorbox}[colback=white]
  2767. \[
  2768. \begin{array}{l}
  2769. \CvarASTRacket \\
  2770. \begin{array}{lcl}
  2771. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2772. \end{array}
  2773. \end{array}
  2774. \]
  2775. \end{tcolorbox}
  2776. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2777. \label{fig:c0-syntax}
  2778. \end{figure}
  2779. The definitional interpreter for \LangCVar{} is in the support code,
  2780. in the file \code{interp-Cvar.rkt}.
  2781. \fi}
  2782. {\if\edition\racketEd
  2783. \section{Uniquify Variables}
  2784. \label{sec:uniquify-Lvar}
  2785. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2786. programs in which every \key{let} binds a unique variable name. For
  2787. example, the \code{uniquify} pass should translate the program on the
  2788. left into the program on the right.
  2789. \begin{transformation}
  2790. \begin{lstlisting}
  2791. (let ([x 32])
  2792. (+ (let ([x 10]) x) x))
  2793. \end{lstlisting}
  2794. \compilesto
  2795. \begin{lstlisting}
  2796. (let ([x.1 32])
  2797. (+ (let ([x.2 10]) x.2) x.1))
  2798. \end{lstlisting}
  2799. \end{transformation}
  2800. The following is another example translation, this time of a program
  2801. with a \key{let} nested inside the initializing expression of another
  2802. \key{let}.
  2803. \begin{transformation}
  2804. \begin{lstlisting}
  2805. (let ([x (let ([x 4])
  2806. (+ x 1))])
  2807. (+ x 2))
  2808. \end{lstlisting}
  2809. \compilesto
  2810. \begin{lstlisting}
  2811. (let ([x.2 (let ([x.1 4])
  2812. (+ x.1 1))])
  2813. (+ x.2 2))
  2814. \end{lstlisting}
  2815. \end{transformation}
  2816. We recommend implementing \code{uniquify} by creating a structurally
  2817. recursive function named \code{uniquify\_exp} that does little other
  2818. than copy an expression. However, when encountering a \key{let}, it
  2819. should generate a unique name for the variable and associate the old
  2820. name with the new name in an alist.\footnote{The Racket function
  2821. \code{gensym} is handy for generating unique variable names.} The
  2822. \code{uniquify\_exp} function needs to access this alist when it gets
  2823. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2824. for the alist.
  2825. The skeleton of the \code{uniquify\_exp} function is shown in
  2826. figure~\ref{fig:uniquify-Lvar}.
  2827. %% The function is curried so that it is
  2828. %% convenient to partially apply it to an alist and then apply it to
  2829. %% different expressions, as in the last case for primitive operations in
  2830. %% figure~\ref{fig:uniquify-Lvar}.
  2831. The
  2832. %
  2833. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2834. %
  2835. form of Racket is useful for transforming the element of a list to
  2836. produce a new list.\index{subject}{for/list}
  2837. \begin{figure}[tbp]
  2838. \begin{tcolorbox}[colback=white]
  2839. \begin{lstlisting}
  2840. (define (uniquify_exp env)
  2841. (lambda (e)
  2842. (match e
  2843. [(Var x) ___]
  2844. [(Int n) (Int n)]
  2845. [(Let x e body) ___]
  2846. [(Prim op es)
  2847. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2848. (define (uniquify p)
  2849. (match p
  2850. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2851. \end{lstlisting}
  2852. \end{tcolorbox}
  2853. \caption{Skeleton for the \key{uniquify} pass.}
  2854. \label{fig:uniquify-Lvar}
  2855. \end{figure}
  2856. \begin{exercise}
  2857. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2858. Complete the \code{uniquify} pass by filling in the blanks in
  2859. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2860. variables and for the \key{let} form in the file \code{compiler.rkt}
  2861. in the support code.
  2862. \end{exercise}
  2863. \begin{exercise}
  2864. \normalfont\normalsize
  2865. \label{ex:Lvar}
  2866. Create five \LangVar{} programs that exercise the most interesting
  2867. parts of the \key{uniquify} pass; that is, the programs should include
  2868. \key{let} forms, variables, and variables that shadow each other.
  2869. The five programs should be placed in the subdirectory named
  2870. \key{tests}, and the file names should start with \code{var\_test\_}
  2871. followed by a unique integer and end with the file extension
  2872. \key{.rkt}.
  2873. %
  2874. The \key{run-tests.rkt} script in the support code checks whether the
  2875. output programs produce the same result as the input programs. The
  2876. script uses the \key{interp-tests} function
  2877. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2878. your \key{uniquify} pass on the example programs. The \code{passes}
  2879. parameter of \key{interp-tests} is a list that should have one entry
  2880. for each pass in your compiler. For now, define \code{passes} to
  2881. contain just one entry for \code{uniquify} as follows:
  2882. \begin{lstlisting}
  2883. (define passes
  2884. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2885. \end{lstlisting}
  2886. Run the \key{run-tests.rkt} script in the support code to check
  2887. whether the output programs produce the same result as the input
  2888. programs.
  2889. \end{exercise}
  2890. \fi}
  2891. \section{Remove Complex Operands}
  2892. \label{sec:remove-complex-opera-Lvar}
  2893. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2894. into a restricted form in which the arguments of operations are atomic
  2895. expressions. Put another way, this pass removes complex
  2896. operands\index{subject}{complex operand}, such as the expression
  2897. \racket{\code{(- 10)}}\python{\code{-10}}
  2898. in the following program. This is accomplished by introducing a new
  2899. temporary variable, assigning the complex operand to the new
  2900. variable, and then using the new variable in place of the complex
  2901. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2902. right.
  2903. {\if\edition\racketEd
  2904. \begin{transformation}
  2905. % var_test_19.rkt
  2906. \begin{lstlisting}
  2907. (let ([x (+ 42 (- 10))])
  2908. (+ x 10))
  2909. \end{lstlisting}
  2910. \compilesto
  2911. \begin{lstlisting}
  2912. (let ([x (let ([tmp.1 (- 10)])
  2913. (+ 42 tmp.1))])
  2914. (+ x 10))
  2915. \end{lstlisting}
  2916. \end{transformation}
  2917. \fi}
  2918. {\if\edition\pythonEd
  2919. \begin{transformation}
  2920. \begin{lstlisting}
  2921. x = 42 + -10
  2922. print(x + 10)
  2923. \end{lstlisting}
  2924. \compilesto
  2925. \begin{lstlisting}
  2926. tmp_0 = -10
  2927. x = 42 + tmp_0
  2928. tmp_1 = x + 10
  2929. print(tmp_1)
  2930. \end{lstlisting}
  2931. \end{transformation}
  2932. \fi}
  2933. \newcommand{\LvarMonadASTRacket}{
  2934. \begin{array}{rcl}
  2935. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2936. \Exp &::=& \Atm \MID \READ{} \\
  2937. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2938. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2939. \end{array}
  2940. }
  2941. \newcommand{\LvarMonadASTPython}{
  2942. \begin{array}{rcl}
  2943. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2944. \Exp{} &::=& \Atm \MID \READ{} \\
  2945. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2946. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2947. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2948. \end{array}
  2949. }
  2950. \begin{figure}[tp]
  2951. \centering
  2952. \begin{tcolorbox}[colback=white]
  2953. {\if\edition\racketEd
  2954. \[
  2955. \begin{array}{l}
  2956. \LvarMonadASTRacket \\
  2957. \begin{array}{rcl}
  2958. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2959. \end{array}
  2960. \end{array}
  2961. \]
  2962. \fi}
  2963. {\if\edition\pythonEd
  2964. \[
  2965. \begin{array}{l}
  2966. \LvarMonadASTPython \\
  2967. \begin{array}{rcl}
  2968. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2969. \end{array}
  2970. \end{array}
  2971. \]
  2972. \fi}
  2973. \end{tcolorbox}
  2974. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2975. atomic expressions.}
  2976. \label{fig:Lvar-anf-syntax}
  2977. \end{figure}
  2978. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2979. of this pass, the language \LangVarANF{}. The only difference is that
  2980. operator arguments are restricted to be atomic expressions that are
  2981. defined by the \Atm{} nonterminal. In particular, integer constants
  2982. and variables are atomic.
  2983. The atomic expressions are pure (they do not cause or depend on side
  2984. effects) whereas complex expressions may have side effects, such as
  2985. \READ{}. A language with this separation between pure expression
  2986. versus expressions with side effects is said to be in monadic normal
  2987. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2988. in the name \LangVarANF{}. An important invariant of the
  2989. \code{remove\_complex\_operands} pass is that the relative ordering
  2990. among complex expressions is not changed, but the relative ordering
  2991. between atomic expressions and complex expressions can change and
  2992. often does. The reason that these changes are behavior preserving is
  2993. that the atomic expressions are pure.
  2994. Another well-known form for intermediate languages is the
  2995. \emph{administrative normal form}
  2996. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2997. \index{subject}{administrative normal form} \index{subject}{ANF}
  2998. %
  2999. The \LangVarANF{} language is not quite in ANF because we allow the
  3000. right-hand side of a \code{let} to be a complex expression.
  3001. {\if\edition\racketEd
  3002. We recommend implementing this pass with two mutually recursive
  3003. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3004. \code{rco\_atom} to subexpressions that need to become atomic and to
  3005. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3006. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3007. returns an expression. The \code{rco\_atom} function returns two
  3008. things: an atomic expression and an alist mapping temporary variables to
  3009. complex subexpressions. You can return multiple things from a function
  3010. using Racket's \key{values} form, and you can receive multiple things
  3011. from a function call using the \key{define-values} form.
  3012. \fi}
  3013. %
  3014. {\if\edition\pythonEd
  3015. %
  3016. We recommend implementing this pass with an auxiliary method named
  3017. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3018. Boolean that specifies whether the expression needs to become atomic
  3019. or not. The \code{rco\_exp} method should return a pair consisting of
  3020. the new expression and a list of pairs, associating new temporary
  3021. variables with their initializing expressions.
  3022. %
  3023. \fi}
  3024. {\if\edition\racketEd
  3025. %
  3026. Returning to the example program with the expression \code{(+ 42 (-
  3027. 10))}, the subexpression \code{(- 10)} should be processed using the
  3028. \code{rco\_atom} function because it is an argument of the \code{+}
  3029. operator and therefore needs to become atomic. The output of
  3030. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3031. \begin{transformation}
  3032. \begin{lstlisting}
  3033. (- 10)
  3034. \end{lstlisting}
  3035. \compilesto
  3036. \begin{lstlisting}
  3037. tmp.1
  3038. ((tmp.1 . (- 10)))
  3039. \end{lstlisting}
  3040. \end{transformation}
  3041. \fi}
  3042. %
  3043. {\if\edition\pythonEd
  3044. %
  3045. Returning to the example program with the expression \code{42 + -10},
  3046. the subexpression \code{-10} should be processed using the
  3047. \code{rco\_exp} function with \code{True} as the second argument
  3048. because \code{-10} is an argument of the \code{+} operator and
  3049. therefore needs to become atomic. The output of \code{rco\_exp}
  3050. applied to \code{-10} is as follows.
  3051. \begin{transformation}
  3052. \begin{lstlisting}
  3053. -10
  3054. \end{lstlisting}
  3055. \compilesto
  3056. \begin{lstlisting}
  3057. tmp_1
  3058. [(tmp_1, -10)]
  3059. \end{lstlisting}
  3060. \end{transformation}
  3061. %
  3062. \fi}
  3063. Take special care of programs, such as the following, that
  3064. %
  3065. \racket{bind a variable to an atomic expression.}
  3066. %
  3067. \python{assign an atomic expression to a variable.}
  3068. %
  3069. You should leave such \racket{variable bindings}\python{assignments}
  3070. unchanged, as shown in the program on the right\\
  3071. %
  3072. {\if\edition\racketEd
  3073. \begin{transformation}
  3074. % var_test_20.rkt
  3075. \begin{lstlisting}
  3076. (let ([a 42])
  3077. (let ([b a])
  3078. b))
  3079. \end{lstlisting}
  3080. \compilesto
  3081. \begin{lstlisting}
  3082. (let ([a 42])
  3083. (let ([b a])
  3084. b))
  3085. \end{lstlisting}
  3086. \end{transformation}
  3087. \fi}
  3088. {\if\edition\pythonEd
  3089. \begin{transformation}
  3090. \begin{lstlisting}
  3091. a = 42
  3092. b = a
  3093. print(b)
  3094. \end{lstlisting}
  3095. \compilesto
  3096. \begin{lstlisting}
  3097. a = 42
  3098. b = a
  3099. print(b)
  3100. \end{lstlisting}
  3101. \end{transformation}
  3102. \fi}
  3103. %
  3104. \noindent A careless implementation might produce the following output with
  3105. unnecessary temporary variables.
  3106. \begin{center}
  3107. \begin{minipage}{0.4\textwidth}
  3108. {\if\edition\racketEd
  3109. \begin{lstlisting}
  3110. (let ([tmp.1 42])
  3111. (let ([a tmp.1])
  3112. (let ([tmp.2 a])
  3113. (let ([b tmp.2])
  3114. b))))
  3115. \end{lstlisting}
  3116. \fi}
  3117. {\if\edition\pythonEd
  3118. \begin{lstlisting}
  3119. tmp_1 = 42
  3120. a = tmp_1
  3121. tmp_2 = a
  3122. b = tmp_2
  3123. print(b)
  3124. \end{lstlisting}
  3125. \fi}
  3126. \end{minipage}
  3127. \end{center}
  3128. \begin{exercise}
  3129. \normalfont\normalsize
  3130. {\if\edition\racketEd
  3131. Implement the \code{remove\_complex\_operands} function in
  3132. \code{compiler.rkt}.
  3133. %
  3134. Create three new \LangVar{} programs that exercise the interesting
  3135. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3136. regarding file names described in exercise~\ref{ex:Lvar}.
  3137. %
  3138. In the \code{run-tests.rkt} script, add the following entry to the
  3139. list of \code{passes}, and then run the script to test your compiler.
  3140. \begin{lstlisting}
  3141. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3142. \end{lstlisting}
  3143. In debugging your compiler, it is often useful to see the intermediate
  3144. programs that are output from each pass. To print the intermediate
  3145. programs, place \lstinline{(debug-level 1)} before the call to
  3146. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3147. %
  3148. {\if\edition\pythonEd
  3149. Implement the \code{remove\_complex\_operands} pass in
  3150. \code{compiler.py}, creating auxiliary functions for each
  3151. nonterminal in the grammar, i.e., \code{rco\_exp}
  3152. and \code{rco\_stmt}. We recommend you use the function
  3153. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3154. \fi}
  3155. \end{exercise}
  3156. {\if\edition\pythonEd
  3157. \begin{exercise}
  3158. \normalfont\normalsize
  3159. \label{ex:Lvar}
  3160. Create five \LangVar{} programs that exercise the most interesting
  3161. parts of the \code{remove\_complex\_operands} pass. The five programs
  3162. should be placed in the subdirectory named \key{tests}, and the file
  3163. names should start with \code{var\_test\_} followed by a unique
  3164. integer and end with the file extension \key{.py}.
  3165. %% The \key{run-tests.rkt} script in the support code checks whether the
  3166. %% output programs produce the same result as the input programs. The
  3167. %% script uses the \key{interp-tests} function
  3168. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3169. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3170. %% parameter of \key{interp-tests} is a list that should have one entry
  3171. %% for each pass in your compiler. For now, define \code{passes} to
  3172. %% contain just one entry for \code{uniquify} as shown below.
  3173. %% \begin{lstlisting}
  3174. %% (define passes
  3175. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3176. %% \end{lstlisting}
  3177. Run the \key{run-tests.py} script in the support code to check
  3178. whether the output programs produce the same result as the input
  3179. programs.
  3180. \end{exercise}
  3181. \fi}
  3182. {\if\edition\racketEd
  3183. \section{Explicate Control}
  3184. \label{sec:explicate-control-Lvar}
  3185. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3186. programs that make the order of execution explicit in their
  3187. syntax. For now this amounts to flattening \key{let} constructs into a
  3188. sequence of assignment statements. For example, consider the following
  3189. \LangVar{} program:\\
  3190. % var_test_11.rkt
  3191. \begin{minipage}{0.96\textwidth}
  3192. \begin{lstlisting}
  3193. (let ([y (let ([x 20])
  3194. (+ x (let ([x 22]) x)))])
  3195. y)
  3196. \end{lstlisting}
  3197. \end{minipage}\\
  3198. %
  3199. The output of the previous pass is shown next, on the left, and the
  3200. output of \code{explicate\_control} is on the right. Recall that the
  3201. right-hand side of a \key{let} executes before its body, so that the order
  3202. of evaluation for this program is to assign \code{20} to \code{x.1},
  3203. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3204. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3205. this ordering explicit.
  3206. \begin{transformation}
  3207. \begin{lstlisting}
  3208. (let ([y (let ([x.1 20])
  3209. (let ([x.2 22])
  3210. (+ x.1 x.2)))])
  3211. y)
  3212. \end{lstlisting}
  3213. \compilesto
  3214. \begin{lstlisting}[language=C]
  3215. start:
  3216. x.1 = 20;
  3217. x.2 = 22;
  3218. y = (+ x.1 x.2);
  3219. return y;
  3220. \end{lstlisting}
  3221. \end{transformation}
  3222. \begin{figure}[tbp]
  3223. \begin{tcolorbox}[colback=white]
  3224. \begin{lstlisting}
  3225. (define (explicate_tail e)
  3226. (match e
  3227. [(Var x) ___]
  3228. [(Int n) (Return (Int n))]
  3229. [(Let x rhs body) ___]
  3230. [(Prim op es) ___]
  3231. [else (error "explicate_tail unhandled case" e)]))
  3232. (define (explicate_assign e x cont)
  3233. (match e
  3234. [(Var x) ___]
  3235. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3236. [(Let y rhs body) ___]
  3237. [(Prim op es) ___]
  3238. [else (error "explicate_assign unhandled case" e)]))
  3239. (define (explicate_control p)
  3240. (match p
  3241. [(Program info body) ___]))
  3242. \end{lstlisting}
  3243. \end{tcolorbox}
  3244. \caption{Skeleton for the \code{explicate\_control} pass.}
  3245. \label{fig:explicate-control-Lvar}
  3246. \end{figure}
  3247. The organization of this pass depends on the notion of tail position
  3248. to which we have alluded. Here is the definition.
  3249. \begin{definition}\normalfont
  3250. The following rules define when an expression is in \emph{tail
  3251. position}\index{subject}{tail position} for the language \LangVar{}.
  3252. \begin{enumerate}
  3253. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3254. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3255. \end{enumerate}
  3256. \end{definition}
  3257. We recommend implementing \code{explicate\_control} using two
  3258. recursive functions, \code{explicate\_tail} and
  3259. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3260. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3261. function should be applied to expressions in tail position, whereas the
  3262. \code{explicate\_assign} should be applied to expressions that occur on
  3263. the right-hand side of a \key{let}.
  3264. %
  3265. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3266. input and produces a \Tail{} in \LangCVar{} (see
  3267. figure~\ref{fig:c0-syntax}).
  3268. %
  3269. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3270. the variable to which it is to be assigned to, and a \Tail{} in
  3271. \LangCVar{} for the code that comes after the assignment. The
  3272. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3273. The \code{explicate\_assign} function is in accumulator-passing style:
  3274. the \code{cont} parameter is used for accumulating the output. This
  3275. accumulator-passing style plays an important role in the way that we
  3276. generate high-quality code for conditional expressions in
  3277. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3278. continuation because it contains the generated code that should come
  3279. after the current assignment. This code organization is also related
  3280. to continuation-passing style, except that \code{cont} is not what
  3281. happens next during compilation but is what happens next in the
  3282. generated code.
  3283. \begin{exercise}\normalfont\normalsize
  3284. %
  3285. Implement the \code{explicate\_control} function in
  3286. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3287. exercise the code in \code{explicate\_control}.
  3288. %
  3289. In the \code{run-tests.rkt} script, add the following entry to the
  3290. list of \code{passes} and then run the script to test your compiler.
  3291. \begin{lstlisting}
  3292. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3293. \end{lstlisting}
  3294. \end{exercise}
  3295. \fi}
  3296. \section{Select Instructions}
  3297. \label{sec:select-Lvar}
  3298. \index{subject}{instruction selection}
  3299. In the \code{select\_instructions} pass we begin the work of
  3300. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3301. language of this pass is a variant of x86 that still uses variables,
  3302. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3303. nonterminal of the \LangXInt{} abstract syntax
  3304. (figure~\ref{fig:x86-int-ast}).
  3305. \racket{We recommend implementing the
  3306. \code{select\_instructions} with three auxiliary functions, one for
  3307. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3308. $\Tail$.}
  3309. \python{We recommend implementing an auxiliary function
  3310. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3311. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3312. same and integer constants change to immediates; that is, $\INT{n}$
  3313. changes to $\IMM{n}$.}
  3314. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3315. arithmetic operations. For example, consider the following addition
  3316. operation, on the left side. There is an \key{addq} instruction in
  3317. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3318. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3319. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3320. $\Atm_2$, respectively.
  3321. \begin{transformation}
  3322. {\if\edition\racketEd
  3323. \begin{lstlisting}
  3324. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3325. \end{lstlisting}
  3326. \fi}
  3327. {\if\edition\pythonEd
  3328. \begin{lstlisting}
  3329. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3330. \end{lstlisting}
  3331. \fi}
  3332. \compilesto
  3333. \begin{lstlisting}
  3334. movq |$\Arg_1$|, |$\itm{var}$|
  3335. addq |$\Arg_2$|, |$\itm{var}$|
  3336. \end{lstlisting}
  3337. \end{transformation}
  3338. There are also cases that require special care to avoid generating
  3339. needlessly complicated code. For example, if one of the arguments of
  3340. the addition is the same variable as the left-hand side of the
  3341. assignment, as shown next, then there is no need for the extra move
  3342. instruction. The assignment statement can be translated into a single
  3343. \key{addq} instruction, as follows.
  3344. \begin{transformation}
  3345. {\if\edition\racketEd
  3346. \begin{lstlisting}
  3347. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3348. \end{lstlisting}
  3349. \fi}
  3350. {\if\edition\pythonEd
  3351. \begin{lstlisting}
  3352. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3353. \end{lstlisting}
  3354. \fi}
  3355. \compilesto
  3356. \begin{lstlisting}
  3357. addq |$\Arg_1$|, |$\itm{var}$|
  3358. \end{lstlisting}
  3359. \end{transformation}
  3360. The \READOP{} operation does not have a direct counterpart in x86
  3361. assembly, so we provide this functionality with the function
  3362. \code{read\_int} in the file \code{runtime.c}, written in
  3363. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3364. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3365. system}, or simply the \emph{runtime} for short. When compiling your
  3366. generated x86 assembly code, you need to compile \code{runtime.c} to
  3367. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3368. \code{-c}) and link it into the executable. For our purposes of code
  3369. generation, all you need to do is translate an assignment of
  3370. \READOP{} into a call to the \code{read\_int} function followed by a
  3371. move from \code{rax} to the left-hand side variable. (Recall that the
  3372. return value of a function goes into \code{rax}.)
  3373. \begin{transformation}
  3374. {\if\edition\racketEd
  3375. \begin{lstlisting}
  3376. |$\itm{var}$| = (read);
  3377. \end{lstlisting}
  3378. \fi}
  3379. {\if\edition\pythonEd
  3380. \begin{lstlisting}
  3381. |$\itm{var}$| = input_int();
  3382. \end{lstlisting}
  3383. \fi}
  3384. \compilesto
  3385. \begin{lstlisting}
  3386. callq read_int
  3387. movq %rax, |$\itm{var}$|
  3388. \end{lstlisting}
  3389. \end{transformation}
  3390. {\if\edition\pythonEd
  3391. %
  3392. Similarly, we translate the \code{print} operation, shown below, into
  3393. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3394. In x86, the first six arguments to functions are passed in registers,
  3395. with the first argument passed in register \code{rdi}. So we move the
  3396. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3397. \code{callq} instruction.
  3398. \begin{transformation}
  3399. \begin{lstlisting}
  3400. print(|$\Atm$|)
  3401. \end{lstlisting}
  3402. \compilesto
  3403. \begin{lstlisting}
  3404. movq |$\Arg$|, %rdi
  3405. callq print_int
  3406. \end{lstlisting}
  3407. \end{transformation}
  3408. %
  3409. \fi}
  3410. {\if\edition\racketEd
  3411. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3412. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3413. assignment to the \key{rax} register followed by a jump to the
  3414. conclusion of the program (so the conclusion needs to be labeled).
  3415. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3416. recursively and then append the resulting instructions.
  3417. \fi}
  3418. {\if\edition\pythonEd
  3419. We recommend that you use the function \code{utils.label\_name()} to
  3420. transform a string into an label argument suitably suitable for, e.g.,
  3421. the target of the \code{callq} instruction. This practice makes your
  3422. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3423. all labels.
  3424. \fi}
  3425. \begin{exercise}
  3426. \normalfont\normalsize
  3427. {\if\edition\racketEd
  3428. Implement the \code{select\_instructions} pass in
  3429. \code{compiler.rkt}. Create three new example programs that are
  3430. designed to exercise all the interesting cases in this pass.
  3431. %
  3432. In the \code{run-tests.rkt} script, add the following entry to the
  3433. list of \code{passes} and then run the script to test your compiler.
  3434. \begin{lstlisting}
  3435. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3436. \end{lstlisting}
  3437. \fi}
  3438. {\if\edition\pythonEd
  3439. Implement the \key{select\_instructions} pass in
  3440. \code{compiler.py}. Create three new example programs that are
  3441. designed to exercise all the interesting cases in this pass.
  3442. Run the \code{run-tests.py} script to to check
  3443. whether the output programs produce the same result as the input
  3444. programs.
  3445. \fi}
  3446. \end{exercise}
  3447. \section{Assign Homes}
  3448. \label{sec:assign-Lvar}
  3449. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3450. \LangXVar{} programs that no longer use program variables. Thus, the
  3451. \code{assign\_homes} pass is responsible for placing all the program
  3452. variables in registers or on the stack. For runtime efficiency, it is
  3453. better to place variables in registers, but because there are only
  3454. sixteen registers, some programs must necessarily resort to placing
  3455. some variables on the stack. In this chapter we focus on the mechanics
  3456. of placing variables on the stack. We study an algorithm for placing
  3457. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3458. Consider again the following \LangVar{} program from
  3459. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3460. % var_test_20.rkt
  3461. \begin{minipage}{0.96\textwidth}
  3462. {\if\edition\racketEd
  3463. \begin{lstlisting}
  3464. (let ([a 42])
  3465. (let ([b a])
  3466. b))
  3467. \end{lstlisting}
  3468. \fi}
  3469. {\if\edition\pythonEd
  3470. \begin{lstlisting}
  3471. a = 42
  3472. b = a
  3473. print(b)
  3474. \end{lstlisting}
  3475. \fi}
  3476. \end{minipage}\\
  3477. %
  3478. The output of \code{select\_instructions} is shown next, on the left,
  3479. and the output of \code{assign\_homes} is on the right. In this
  3480. example, we assign variable \code{a} to stack location
  3481. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3482. \begin{transformation}
  3483. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3484. movq $42, a
  3485. movq a, b
  3486. movq b, %rax
  3487. \end{lstlisting}
  3488. \compilesto
  3489. %stack-space: 16
  3490. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3491. movq $42, -8(%rbp)
  3492. movq -8(%rbp), -16(%rbp)
  3493. movq -16(%rbp), %rax
  3494. \end{lstlisting}
  3495. \end{transformation}
  3496. \racket{
  3497. The \code{assign\_homes} pass should replace all variables
  3498. with stack locations.
  3499. The list of variables can be obtained from
  3500. the \code{locals-types} entry in the $\itm{info}$ of the
  3501. \code{X86Program} node. The \code{locals-types} entry is an alist
  3502. mapping all the variables in the program to their types
  3503. (for now, just \code{Integer}).
  3504. As an aside, the \code{locals-types} entry is
  3505. computed by \code{type-check-Cvar} in the support code, which
  3506. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3507. which you should propagate to the \code{X86Program} node.}
  3508. %
  3509. \python{The \code{assign\_homes} pass should replace all uses of
  3510. variables with stack locations.}
  3511. %
  3512. In the process of assigning variables to stack locations, it is
  3513. convenient for you to compute and store the size of the frame (in
  3514. bytes) in
  3515. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3516. %
  3517. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3518. %
  3519. which is needed later to generate the conclusion of the \code{main}
  3520. procedure. The x86-64 standard requires the frame size to be a
  3521. multiple of 16 bytes.\index{subject}{frame}
  3522. % TODO: store the number of variables instead? -Jeremy
  3523. \begin{exercise}\normalfont\normalsize
  3524. Implement the \code{assign\_homes} pass in
  3525. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3526. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3527. grammar. We recommend that the auxiliary functions take an extra
  3528. parameter that maps variable names to homes (stack locations for now).
  3529. %
  3530. {\if\edition\racketEd
  3531. In the \code{run-tests.rkt} script, add the following entry to the
  3532. list of \code{passes} and then run the script to test your compiler.
  3533. \begin{lstlisting}
  3534. (list "assign homes" assign-homes interp_x86-0)
  3535. \end{lstlisting}
  3536. \fi}
  3537. {\if\edition\pythonEd
  3538. Run the \code{run-tests.py} script to to check
  3539. whether the output programs produce the same result as the input
  3540. programs.
  3541. \fi}
  3542. \end{exercise}
  3543. \section{Patch Instructions}
  3544. \label{sec:patch-s0}
  3545. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3546. \LangXInt{} by making sure that each instruction adheres to the
  3547. restriction that at most one argument of an instruction may be a
  3548. memory reference.
  3549. We return to the following example.\\
  3550. \begin{minipage}{0.5\textwidth}
  3551. % var_test_20.rkt
  3552. {\if\edition\racketEd
  3553. \begin{lstlisting}
  3554. (let ([a 42])
  3555. (let ([b a])
  3556. b))
  3557. \end{lstlisting}
  3558. \fi}
  3559. {\if\edition\pythonEd
  3560. \begin{lstlisting}
  3561. a = 42
  3562. b = a
  3563. print(b)
  3564. \end{lstlisting}
  3565. \fi}
  3566. \end{minipage}\\
  3567. The \code{assign\_homes} pass produces the following translation. \\
  3568. \begin{minipage}{0.5\textwidth}
  3569. {\if\edition\racketEd
  3570. \begin{lstlisting}
  3571. movq $42, -8(%rbp)
  3572. movq -8(%rbp), -16(%rbp)
  3573. movq -16(%rbp), %rax
  3574. \end{lstlisting}
  3575. \fi}
  3576. {\if\edition\pythonEd
  3577. \begin{lstlisting}
  3578. movq 42, -8(%rbp)
  3579. movq -8(%rbp), -16(%rbp)
  3580. movq -16(%rbp), %rdi
  3581. callq print_int
  3582. \end{lstlisting}
  3583. \fi}
  3584. \end{minipage}\\
  3585. The second \key{movq} instruction is problematic because both
  3586. arguments are stack locations. We suggest fixing this problem by
  3587. moving from the source location to the register \key{rax} and then
  3588. from \key{rax} to the destination location, as follows.
  3589. \begin{lstlisting}
  3590. movq -8(%rbp), %rax
  3591. movq %rax, -16(%rbp)
  3592. \end{lstlisting}
  3593. \begin{exercise}
  3594. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3595. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3596. Create three new example programs that are
  3597. designed to exercise all the interesting cases in this pass.
  3598. %
  3599. {\if\edition\racketEd
  3600. In the \code{run-tests.rkt} script, add the following entry to the
  3601. list of \code{passes} and then run the script to test your compiler.
  3602. \begin{lstlisting}
  3603. (list "patch instructions" patch_instructions interp_x86-0)
  3604. \end{lstlisting}
  3605. \fi}
  3606. {\if\edition\pythonEd
  3607. Run the \code{run-tests.py} script to to check
  3608. whether the output programs produce the same result as the input
  3609. programs.
  3610. \fi}
  3611. \end{exercise}
  3612. \section{Generate Prelude and Conclusion}
  3613. \label{sec:print-x86}
  3614. \index{subject}{prelude}\index{subject}{conclusion}
  3615. The last step of the compiler from \LangVar{} to x86 is to generate
  3616. the \code{main} function with a prelude and conclusion wrapped around
  3617. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3618. discussed in section~\ref{sec:x86}.
  3619. When running on Mac OS X, your compiler should prefix an underscore to
  3620. all labels, e.g., changing \key{main} to \key{\_main}.
  3621. %
  3622. \racket{The Racket call \code{(system-type 'os)} is useful for
  3623. determining which operating system the compiler is running on. It
  3624. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3625. %
  3626. \python{The Python \code{platform} library includes a \code{system()}
  3627. function that returns \code{'Linux'}, \code{'Windows'}, or
  3628. \code{'Darwin'} (for Mac).}
  3629. \begin{exercise}\normalfont\normalsize
  3630. %
  3631. Implement the \key{prelude\_and\_conclusion} pass in
  3632. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3633. %
  3634. {\if\edition\racketEd
  3635. In the \code{run-tests.rkt} script, add the following entry to the
  3636. list of \code{passes} and then run the script to test your compiler.
  3637. \begin{lstlisting}
  3638. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3639. \end{lstlisting}
  3640. %
  3641. Uncomment the call to the \key{compiler-tests} function
  3642. (appendix~\ref{appendix:utilities}), which tests your complete
  3643. compiler by executing the generated x86 code. It translates the x86
  3644. AST that you produce into a string by invoking the \code{print-x86}
  3645. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3646. the provided \key{runtime.c} file to \key{runtime.o} using
  3647. \key{gcc}. Run the script to test your compiler.
  3648. %
  3649. \fi}
  3650. {\if\edition\pythonEd
  3651. %
  3652. Run the \code{run-tests.py} script to to check whether the output
  3653. programs produce the same result as the input programs. That script
  3654. translates the x86 AST that you produce into a string by invoking the
  3655. \code{repr} method that is implemented by the x86 AST classes in
  3656. \code{x86\_ast.py}.
  3657. %
  3658. \fi}
  3659. \end{exercise}
  3660. \section{Challenge: Partial Evaluator for \LangVar{}}
  3661. \label{sec:pe-Lvar}
  3662. \index{subject}{partial evaluation}
  3663. This section describes two optional challenge exercises that involve
  3664. adapting and improving the partial evaluator for \LangInt{} that was
  3665. introduced in section~\ref{sec:partial-evaluation}.
  3666. \begin{exercise}\label{ex:pe-Lvar}
  3667. \normalfont\normalsize
  3668. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3669. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3670. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3671. %
  3672. \racket{\key{let} binding}\python{assignment}
  3673. %
  3674. to the \LangInt{} language, so you will need to add cases for them in
  3675. the \code{pe\_exp}
  3676. %
  3677. \racket{function.}
  3678. %
  3679. \python{and \code{pe\_stmt} functions.}
  3680. %
  3681. Once complete, add the partial evaluation pass to the front of your
  3682. compiler, and make sure that your compiler still passes all the
  3683. tests.
  3684. \end{exercise}
  3685. \begin{exercise}
  3686. \normalfont\normalsize
  3687. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3688. \code{pe\_add} auxiliary functions with functions that know more about
  3689. arithmetic. For example, your partial evaluator should translate
  3690. {\if\edition\racketEd
  3691. \[
  3692. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3693. \code{(+ 2 (read))}
  3694. \]
  3695. \fi}
  3696. {\if\edition\pythonEd
  3697. \[
  3698. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3699. \code{2 + input\_int()}
  3700. \]
  3701. \fi}
  3702. %
  3703. To accomplish this, the \code{pe\_exp} function should produce output
  3704. in the form of the $\itm{residual}$ nonterminal of the following
  3705. grammar. The idea is that when processing an addition expression, we
  3706. can always produce one of the following: (1) an integer constant, (2)
  3707. an addition expression with an integer constant on the left-hand side
  3708. but not the right-hand side, or (3) an addition expression in which
  3709. neither subexpression is a constant.
  3710. %
  3711. {\if\edition\racketEd
  3712. \[
  3713. \begin{array}{lcl}
  3714. \itm{inert} &::=& \Var
  3715. \MID \LP\key{read}\RP
  3716. \MID \LP\key{-} ~\Var\RP
  3717. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3718. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3719. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3720. \itm{residual} &::=& \Int
  3721. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3722. \MID \itm{inert}
  3723. \end{array}
  3724. \]
  3725. \fi}
  3726. {\if\edition\pythonEd
  3727. \[
  3728. \begin{array}{lcl}
  3729. \itm{inert} &::=& \Var
  3730. \MID \key{input\_int}\LP\RP
  3731. \MID \key{-} \Var
  3732. \MID \key{-} \key{input\_int}\LP\RP
  3733. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3734. \itm{residual} &::=& \Int
  3735. \MID \Int ~ \key{+} ~ \itm{inert}
  3736. \MID \itm{inert}
  3737. \end{array}
  3738. \]
  3739. \fi}
  3740. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3741. inputs are $\itm{residual}$ expressions and they should return
  3742. $\itm{residual}$ expressions. Once the improvements are complete,
  3743. make sure that your compiler still passes all the tests. After
  3744. all, fast code is useless if it produces incorrect results!
  3745. \end{exercise}
  3746. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3747. {\if\edition\pythonEd
  3748. \chapter{Parsing}
  3749. \label{ch:parsing}
  3750. \setcounter{footnote}{0}
  3751. \index{subject}{parsing}
  3752. In this chapter we learn how to use the Lark parser
  3753. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3754. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3755. You will then be asked to use Lark to create a parser for \LangVar{}.
  3756. We also describe the parsing algorithms used inside Lark, studying the
  3757. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3758. A parser framework such as Lark takes in a specification of the
  3759. concrete syntax and an input program and produces a parse tree. Even
  3760. though a parser framework does most of the work for us, using one
  3761. properly requires some knowledge. In particular, we must learn about
  3762. its specification languages and we must learn how to deal with
  3763. ambiguity in our language specifications. Also, some algorithms, such
  3764. as LALR(1) place restrictions on the grammars they can handle, in
  3765. which case it helps to know the algorithm when trying to decipher the
  3766. error messages.
  3767. The process of parsing is traditionally subdivided into two phases:
  3768. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3769. analysis} (also called parsing). The lexical analysis phase
  3770. translates the sequence of characters into a sequence of
  3771. \emph{tokens}, that is, words consisting of several characters. The
  3772. parsing phase organizes the tokens into a \emph{parse tree} that
  3773. captures how the tokens were matched by rules in the grammar of the
  3774. language. The reason for the subdivision into two phases is to enable
  3775. the use of a faster but less powerful algorithm for lexical analysis
  3776. and the use of a slower but more powerful algorithm for parsing.
  3777. %
  3778. %% Likewise, parser generators typical come in pairs, with separate
  3779. %% generators for the lexical analyzer (or lexer for short) and for the
  3780. %% parser. A particularly influential pair of generators were
  3781. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3782. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3783. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3784. %% Compiler Compiler.
  3785. %
  3786. The Lark parser framework that we use in this chapter includes both
  3787. lexical analyzers and parsers. The next section discusses lexical
  3788. analysis and the remainder of the chapter discusses parsing.
  3789. \section{Lexical Analysis and Regular Expressions}
  3790. \label{sec:lex}
  3791. The lexical analyzers produced by Lark turn a sequence of characters
  3792. (a string) into a sequence of token objects. For example, a Lark
  3793. generated lexer for \LangInt{} converts the string
  3794. \begin{lstlisting}
  3795. 'print(1 + 3)'
  3796. \end{lstlisting}
  3797. \noindent into the following sequence of token objects
  3798. \begin{center}
  3799. \begin{minipage}{0.95\textwidth}
  3800. \begin{lstlisting}
  3801. Token('PRINT', 'print')
  3802. Token('LPAR', '(')
  3803. Token('INT', '1')
  3804. Token('PLUS', '+')
  3805. Token('INT', '3')
  3806. Token('RPAR', ')')
  3807. Token('NEWLINE', '\n')
  3808. \end{lstlisting}
  3809. \end{minipage}
  3810. \end{center}
  3811. Each token includes a field for its \code{type}, such as \code{'INT'},
  3812. and a field for its \code{value}, such as \code{'1'}.
  3813. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3814. specification language for Lark's lexer is one regular expression for
  3815. each type of token. The term \emph{regular} comes from the term
  3816. \emph{regular languages}, which are the languages that can be
  3817. recognized by a finite state machine. A \emph{regular expression} is a
  3818. pattern formed of the following core elements:\index{subject}{regular
  3819. expression}\footnote{Regular expressions traditionally include the
  3820. empty regular expression that matches any zero-length part of a
  3821. string, but Lark does not support the empty regular expression.}
  3822. \begin{itemize}
  3823. \item A single character $c$ is a regular expression and it only
  3824. matches itself. For example, the regular expression \code{a} only
  3825. matches with the string \code{'a'}.
  3826. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3827. R_2$ form a regular expression that matches any string that matches
  3828. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3829. matches the string \code{'a'} and the string \code{'c'}.
  3830. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3831. expression that matches any string that can be formed by
  3832. concatenating two strings, where the first string matches $R_1$ and
  3833. the second string matches $R_2$. For example, the regular expression
  3834. \code{(a|c)b} matches the strings \code{'ab'} and \code{'cb'}.
  3835. (Parentheses can be used to control the grouping of operators within
  3836. a regular expression.)
  3837. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3838. Kleene closure) is a regular expression that matches any string that
  3839. can be formed by concatenating zero or more strings that each match
  3840. the regular expression $R$. For example, the regular expression
  3841. \code{"((a|c)b)*"} matches the strings \code{'abcbab'} but not
  3842. \code{'abc'}.
  3843. \end{itemize}
  3844. For our convenience, Lark also accepts the following extended set of
  3845. regular expressions that are automatically translated into the core
  3846. regular expressions.
  3847. \begin{itemize}
  3848. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3849. c_n]$ is a regular expression that matches any one of the
  3850. characters. So $[c_1 c_2 \ldots c_n]$ is equivalent to
  3851. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3852. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3853. a regular expression that matches any character between $c_1$ and
  3854. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3855. letter in the alphabet.
  3856. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3857. is a regular expression that matches any string that can
  3858. be formed by concatenating one or more strings that each match $R$.
  3859. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3860. matches \code{'b'} and \code{'bzca'}.
  3861. \item A regular expression followed by a question mark $R\ttm{?}$
  3862. is a regular expression that matches any string that either
  3863. matches $R$ or that is the empty string.
  3864. For example, \code{a?b} matches both \code{'ab'} and \code{'b'}.
  3865. \item A string, such as \code{"hello"}, which matches itself,
  3866. that is, \code{'hello'}.
  3867. \end{itemize}
  3868. In a Lark grammar file, specify a name for each type of token followed
  3869. by a colon and then a regular expression surrounded by \code{/}
  3870. characters. For example, the \code{DIGIT}, \code{INT}, and
  3871. \code{NEWLINE} types of tokens are specified in the following way.
  3872. \begin{center}
  3873. \begin{minipage}{0.95\textwidth}
  3874. \begin{lstlisting}
  3875. DIGIT: /[0-9]/
  3876. INT: "-"? DIGIT+
  3877. NEWLINE: (/\r/? /\n/)+
  3878. \end{lstlisting}
  3879. \end{minipage}
  3880. \end{center}
  3881. \noindent In Lark, the regular expression operators can be used both
  3882. inside a regular expression, that is, between the \code{/} characters,
  3883. and they can be used to combine regular expressions, outside the
  3884. \code{/} characters.
  3885. \section{Grammars and Parse Trees}
  3886. \label{sec:CFG}
  3887. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3888. specify the abstract syntax of a language. We now take a closer look
  3889. at using grammar rules to specify the concrete syntax. Recall that
  3890. each rule has a left-hand side and a right-hand side where the
  3891. left-hand side is a nonterminal and the right-hand side is a pattern
  3892. that defines what can be parsed as that nonterminal.
  3893. For concrete syntax, each right-hand side expresses a pattern for a
  3894. string, instead of a pattern for an abstract syntax tree. In
  3895. particular, each right-hand side is a sequence of
  3896. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  3897. terminal or nonterminal. A \emph{terminal}\index{subject}{terminal} is
  3898. a string. The nonterminals play the same role as in the abstract
  3899. syntax, defining categories of syntax. The nonterminals of a grammar
  3900. include the tokens defined in the lexer and all the nonterminals
  3901. defined by the grammar rules.
  3902. As an example, let us take a closer look at the concrete syntax of the
  3903. \LangInt{} language, repeated here.
  3904. \[
  3905. \begin{array}{l}
  3906. \LintGrammarPython \\
  3907. \begin{array}{rcl}
  3908. \LangInt{} &::=& \Stmt^{*}
  3909. \end{array}
  3910. \end{array}
  3911. \]
  3912. The Lark syntax for grammar rules differs slightly from the variant of
  3913. BNF that we use in this book. In particular, the notation $::=$ is
  3914. replaced by a single colon and the use of typewriter font for string
  3915. literals is replaced by quotation marks. The following grammar serves
  3916. as a first draft of a Lark grammar for \LangInt{}.
  3917. \begin{center}
  3918. \begin{minipage}{0.95\textwidth}
  3919. \begin{lstlisting}[escapechar=$]
  3920. exp: INT
  3921. | "input_int" "(" ")"
  3922. | "-" exp
  3923. | exp "+" exp
  3924. | exp "-" exp
  3925. | "(" exp ")"
  3926. stmt_list:
  3927. | stmt NEWLINE stmt_list
  3928. lang_int: stmt_list
  3929. \end{lstlisting}
  3930. \end{minipage}
  3931. \end{center}
  3932. Let us begin by discussing the rule \code{exp: INT} which says that if
  3933. the lexer matches a string to \code{INT}, then the parser also
  3934. categorizes the string as an \code{exp}. Recall that in
  3935. Section~\ref{sec:grammar} we defined the corresponding \Int{}
  3936. nonterminal with an English sentence. Here we specify \code{INT} more
  3937. formally using a type of token \code{INT} and its regular expression
  3938. \code{"-"? DIGIT+}.
  3939. The rule \code{exp: exp "+" exp} says that any string that matches
  3940. \code{exp}, followed by the \code{+} character, followed by another
  3941. string that matches \code{exp}, is itself an \code{exp}. For example,
  3942. the string \code{'1+3'} is an \code{exp} because \code{'1'} and
  3943. \code{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  3944. the rule for addition applies to categorize \code{'1+3'} as an
  3945. \code{exp}. We can visualize the application of grammar rules to parse
  3946. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  3947. internal node in the tree is an application of a grammar rule and is
  3948. labeled with its left-hand side nonterminal. Each leaf node is a
  3949. substring of the input program. The parse tree for \code{'1+3'} is
  3950. shown in figure~\ref{fig:simple-parse-tree}.
  3951. \begin{figure}[tbp]
  3952. \begin{tcolorbox}[colback=white]
  3953. \centering
  3954. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  3955. \end{tcolorbox}
  3956. \caption{The parse tree for \code{'1+3'}.}
  3957. \label{fig:simple-parse-tree}
  3958. \end{figure}
  3959. The result of parsing \code{'1+3'} with this Lark grammar is the
  3960. following parse tree as represented by \code{Tree} and \code{Token}
  3961. objects.
  3962. \begin{lstlisting}
  3963. Tree('lang_int',
  3964. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  3965. Tree('exp', [Token('INT', '3')])])]),
  3966. Token('NEWLINE', '\n')])
  3967. \end{lstlisting}
  3968. The nodes that come from the lexer are \code{Token} objects whereas
  3969. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  3970. object has a \code{data} field containing the name of the nonterminal
  3971. for the grammar rule that was applied. Each \code{Tree} object also
  3972. has a \code{children} field that is a list containing trees and/or
  3973. tokens. Note that Lark does not produce nodes for string literals in
  3974. the grammar. For example, the \code{Tree} node for the addition
  3975. expression has only two children for the two integers but is missing
  3976. its middle child for the \code{"+"} terminal. This would be
  3977. problematic except that Lark provides a mechanism for customizing the
  3978. \code{data} field of each \code{Tree} node based on which rule was
  3979. applied. Next to each alternative in a grammar rule, write \code{->}
  3980. followed by a string that you would like to appear in the \code{data}
  3981. field. The following is a second draft of a Lark grammar for
  3982. \LangInt{}, this time with more specific labels on the \code{Tree}
  3983. nodes.
  3984. \begin{center}
  3985. \begin{minipage}{0.95\textwidth}
  3986. \begin{lstlisting}[escapechar=$]
  3987. exp: INT -> int
  3988. | "input_int" "(" ")" -> input_int
  3989. | "-" exp -> usub
  3990. | exp "+" exp -> add
  3991. | exp "-" exp -> sub
  3992. | "(" exp ")" -> paren
  3993. stmt: "print" "(" exp ")" -> print
  3994. | exp -> expr
  3995. stmt_list: -> empty_stmt
  3996. | stmt NEWLINE stmt_list -> add_stmt
  3997. lang_int: stmt_list -> module
  3998. \end{lstlisting}
  3999. \end{minipage}
  4000. \end{center}
  4001. Here is the resulting parse tree.
  4002. \begin{lstlisting}
  4003. Tree('module',
  4004. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4005. Tree('int', [Token('INT', '3')])])]),
  4006. Token('NEWLINE', '\n')])
  4007. \end{lstlisting}
  4008. \section{Ambiguous Grammars}
  4009. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4010. can be parsed in more than one way. For example, consider the string
  4011. \code{'1-2+3'}. This string can parsed in two different ways using
  4012. our draft grammar, resulting in the two parse trees shown in
  4013. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4014. interpreting the second parse tree would yield \code{-4} even through
  4015. the correct answer is \code{2}.
  4016. \begin{figure}[tbp]
  4017. \begin{tcolorbox}[colback=white]
  4018. \centering
  4019. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4020. \end{tcolorbox}
  4021. \caption{The two parse trees for \code{'1-2+3'}.}
  4022. \label{fig:ambig-parse-tree}
  4023. \end{figure}
  4024. To deal with this problem we can change the grammar by categorizing
  4025. the syntax in a more fine grained fashion. In this case we want to
  4026. disallow the application of the rule \code{exp: exp "-" exp} when the
  4027. child on the right is an addition. To do this we can replace the
  4028. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4029. the expressions except for addition, as in the following.
  4030. \begin{center}
  4031. \begin{minipage}{0.95\textwidth}
  4032. \begin{lstlisting}[escapechar=$]
  4033. exp: exp "-" exp_no_add -> sub
  4034. | exp "+" exp -> add
  4035. | exp_no_add
  4036. exp_no_add: INT -> int
  4037. | "input_int" "(" ")" -> input_int
  4038. | "-" exp -> usub
  4039. | exp "-" exp_no_add -> sub
  4040. | "(" exp ")" -> paren
  4041. \end{lstlisting}
  4042. \end{minipage}
  4043. \end{center}
  4044. However, there remains some ambiguity in the grammar. For example, the
  4045. string \code{'1-2-3'} can still be parsed in two different ways, as
  4046. \code{'(1-2)-3'} (correct) or \code{'1-(2-3)'} (incorrect). That is
  4047. to say, subtraction is left associative. Likewise, addition in Python
  4048. is left associative. We also need to consider the interaction of unary
  4049. subtraction with both addition and subtraction. How should we parse
  4050. \code{'-1+2'}? Unary subtraction has higher
  4051. \emph{precendence}\index{subject}{precedence} than addition and
  4052. subtraction, so \code{'-1+2'} should parse the same as \code{'(-1)+2'}
  4053. and not \code{'-(1+2)'}. The grammar in
  4054. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4055. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4056. all the other expressions, and uses \code{exp\_hi} for the second
  4057. child in the rules for addition and subtraction. Furthermore, unary
  4058. subtraction uses \code{exp\_hi} for its child.
  4059. For languages with more operators and more precedence levels, one must
  4060. refine the \code{exp} nonterminal into several nonterminals, one for
  4061. each precedence level.
  4062. \begin{figure}[tbp]
  4063. \begin{tcolorbox}[colback=white]
  4064. \centering
  4065. \begin{lstlisting}[escapechar=$]
  4066. exp: exp "+" exp_hi -> add
  4067. | exp "-" exp_hi -> sub
  4068. | exp_hi
  4069. exp_hi: INT -> int
  4070. | "input_int" "(" ")" -> input_int
  4071. | "-" exp_hi -> usub
  4072. | "(" exp ")" -> paren
  4073. stmt: "print" "(" exp ")" -> print
  4074. | exp -> expr
  4075. stmt_list: -> empty_stmt
  4076. | stmt NEWLINE stmt_list -> add_stmt
  4077. lang_int: stmt_list -> module
  4078. \end{lstlisting}
  4079. \end{tcolorbox}
  4080. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4081. \label{fig:Lint-lark-grammar}
  4082. \end{figure}
  4083. \section{From Parse Trees to Abstract Syntax Trees}
  4084. As we have seen, the output of a Lark parser is a parse tree, that is,
  4085. a tree consisting of \code{Tree} and \code{Token} nodes. So the next
  4086. step is to convert the parse tree to an abstract syntax tree. This can
  4087. be accomplished with a recursive function that inspects the
  4088. \code{data} field of each node and then constructs the corresponding
  4089. AST node, using recursion to handle its children. The following is an
  4090. excerpt of the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4091. \begin{center}
  4092. \begin{minipage}{0.95\textwidth}
  4093. \begin{lstlisting}
  4094. def parse_tree_to_ast(e):
  4095. if e.data == 'int':
  4096. return Constant(int(e.children[0].value))
  4097. elif e.data == 'input_int':
  4098. return Call(Name('input_int'), [])
  4099. elif e.data == 'add':
  4100. e1, e2 = e.children
  4101. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4102. ...
  4103. else:
  4104. raise Exception('unhandled parse tree', e)
  4105. \end{lstlisting}
  4106. \end{minipage}
  4107. \end{center}
  4108. \begin{exercise}
  4109. \normalfont\normalsize
  4110. %
  4111. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4112. default parsing algorithm (Earley) with the \code{ambiguity} option
  4113. set to \code{'explicit'} so that if your grammar is ambiguous, the
  4114. output will include multiple parse trees which will indicate to you
  4115. that there is a problem with your grammar. Your parser should ignore
  4116. white space so we recommend using Lark's \code{\%ignore} directive
  4117. as follows.
  4118. \begin{lstlisting}
  4119. WS: /[ \t\f\r\n]/+
  4120. %ignore WS
  4121. \end{lstlisting}
  4122. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4123. Lark parser instead of using the \code{parse} function from
  4124. the \code{ast} module. Test your compiler on all of the \LangVar{}
  4125. programs that you have created and create four additional programs
  4126. that test for ambiguities in your grammar.
  4127. \end{exercise}
  4128. \section{The Earley Algorithm}
  4129. \label{sec:earley}
  4130. In this section we discuss the parsing algorithm of
  4131. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4132. algorithm is powerful in that it can handle any context-free grammar,
  4133. which makes it easy to use. However, it is not the most efficient
  4134. parsing algorithm: it is $O(n^3)$ for ambiguous grammars and $O(n^2)$
  4135. for unambiguous grammars, where $n$ is the number of tokens in the
  4136. input string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr}
  4137. we learn about the LALR(1) algorithm, which is more efficient but
  4138. cannot handle all context-free grammars.
  4139. The Earley algorithm can be viewed as an interpreter; it treats the
  4140. grammar as the program being interpreted and it treats the concrete
  4141. syntax of the program-to-be-parsed as its input. The Earley algorithm
  4142. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4143. keep track of its progress and to memoize its results. The chart is an
  4144. array with one slot for each position in the input string, where
  4145. position $0$ is before the first character and position $n$ is
  4146. immediately after the last character. So the array has length $n+1$
  4147. for an input string of length $n$. Each slot in the chart contains a
  4148. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4149. with a period indicating how much of its right-hand side has already
  4150. been parsed. For example, the dotted rule
  4151. \begin{lstlisting}
  4152. exp: exp "+" . exp_hi
  4153. \end{lstlisting}
  4154. represents a partial parse that has matched an \code{exp} followed by
  4155. \code{+}, but has not yet parsed an \code{exp} to the right of
  4156. \code{+}.
  4157. %
  4158. The Earley algorithm starts with an initialization phase, and then
  4159. repeats three actions---prediction, scanning, and completion---for as
  4160. long as opportunities arise. We demonstrate the Earley algorithm on a
  4161. running example, parsing the following program:
  4162. \begin{lstlisting}
  4163. print(1 + 3)
  4164. \end{lstlisting}
  4165. The algorithm's initialization phase creates dotted rules for all the
  4166. grammar rules whose left-hand side is the start symbol and places them
  4167. in slot $0$ of the chart. We also record the starting position of the
  4168. dotted rule in parentheses on the right. For example, given the
  4169. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4170. \begin{lstlisting}
  4171. lang_int: . stmt_list (0)
  4172. \end{lstlisting}
  4173. in slot $0$ of the chart. The algorithm then proceeds with
  4174. \emph{prediction} actions in which it adds more dotted rules to the
  4175. chart based on which nonterminals come immediately after a period. In
  4176. the above, the nonterminal \code{stmt\_list} appears after a period,
  4177. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4178. period at the beginning of their right-hand sides, as follows:
  4179. \begin{lstlisting}
  4180. stmt_list: . (0)
  4181. stmt_list: . stmt NEWLINE stmt_list (0)
  4182. \end{lstlisting}
  4183. We continue to perform prediction actions as more opportunities
  4184. arise. For example, the \code{stmt} nonterminal now appears after a
  4185. period, so we add all the rules for \code{stmt}.
  4186. \begin{lstlisting}
  4187. stmt: . "print" "(" exp ")" (0)
  4188. stmt: . exp (0)
  4189. \end{lstlisting}
  4190. This reveals yet more opportunities for prediction, so we add the grammar
  4191. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4192. \begin{lstlisting}[escapechar=$]
  4193. exp: . exp "+" exp_hi (0)
  4194. exp: . exp "-" exp_hi (0)
  4195. exp: . exp_hi (0)
  4196. exp_hi: . INT (0)
  4197. exp_hi: . "input_int" "(" ")" (0)
  4198. exp_hi: . "-" exp_hi (0)
  4199. exp_hi: . "(" exp ")" (0)
  4200. \end{lstlisting}
  4201. We have exhausted the opportunities for prediction, so the algorithm
  4202. proceeds to \emph{scanning}, in which we inspect the next input token
  4203. and look for a dotted rule at the current position that has a matching
  4204. terminal immediately following the period. In our running example, the
  4205. first input token is \code{"print"} so we identify the rule in slot
  4206. $0$ of the chart where \code{"print"} follows the period:
  4207. \begin{lstlisting}
  4208. stmt: . "print" "(" exp ")" (0)
  4209. \end{lstlisting}
  4210. We advance the period past \code{"print"} and add the resulting rule
  4211. to slot $1$ of the chart:
  4212. \begin{lstlisting}
  4213. stmt: "print" . "(" exp ")" (0)
  4214. \end{lstlisting}
  4215. If the new dotted rule had a nonterminal after the period, we would
  4216. need to carry out a prediction action, adding more dotted rules into
  4217. slot $1$. That is not the case, so we continue scanning. The next
  4218. input token is \code{"("}, so we add the following to slot $2$ of the
  4219. chart.
  4220. \begin{lstlisting}
  4221. stmt: "print" "(" . exp ")" (0)
  4222. \end{lstlisting}
  4223. Now we have a nonterminal after the period, so we carry out several
  4224. prediction actions, adding dotted rules for \code{exp} and
  4225. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4226. starting position $2$.
  4227. \begin{lstlisting}[escapechar=$]
  4228. exp: . exp "+" exp_hi (2)
  4229. exp: . exp "-" exp_hi (2)
  4230. exp: . exp_hi (2)
  4231. exp_hi: . INT (2)
  4232. exp_hi: . "input_int" "(" ")" (2)
  4233. exp_hi: . "-" exp_hi (2)
  4234. exp_hi: . "(" exp ")" (2)
  4235. \end{lstlisting}
  4236. With this prediction complete, we return to scanning, noting that the
  4237. next input token is \code{"1"} which the lexer parses as an
  4238. \code{INT}. There is a matching rule in slot $2$:
  4239. \begin{lstlisting}
  4240. exp_hi: . INT (2)
  4241. \end{lstlisting}
  4242. so we advance the period and put the following rule is slot $3$.
  4243. \begin{lstlisting}
  4244. exp_hi: INT . (2)
  4245. \end{lstlisting}
  4246. This brings us to \emph{completion} actions. When the period reaches
  4247. the end of a dotted rule, we recognize that the substring
  4248. has matched the nonterminal on the left-hand side of the rule, in this case
  4249. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4250. rules in slot $2$ (the starting position for the finished rule) if
  4251. the period is immediately followed by \code{exp\_hi}. So we identify
  4252. \begin{lstlisting}
  4253. exp: . exp_hi (2)
  4254. \end{lstlisting}
  4255. and add the following dotted rule to slot $3$
  4256. \begin{lstlisting}
  4257. exp: exp_hi . (2)
  4258. \end{lstlisting}
  4259. This triggers another completion step for the nonterminal \code{exp},
  4260. adding two more dotted rules to slot $3$.
  4261. \begin{lstlisting}[escapechar=$]
  4262. exp: exp . "+" exp_hi (2)
  4263. exp: exp . "-" exp_hi (2)
  4264. \end{lstlisting}
  4265. Returning to scanning, the next input token is \code{"+"}, so
  4266. we add the following to slot $4$.
  4267. \begin{lstlisting}[escapechar=$]
  4268. exp: exp "+" . exp_hi (2)
  4269. \end{lstlisting}
  4270. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4271. the following dotted rules to slot $4$ of the chart.
  4272. \begin{lstlisting}[escapechar=$]
  4273. exp_hi: . INT (4)
  4274. exp_hi: . "input_int" "(" ")" (4)
  4275. exp_hi: . "-" exp_hi (4)
  4276. exp_hi: . "(" exp ")" (4)
  4277. \end{lstlisting}
  4278. The next input token is \code{"3"} which the lexer categorized as an
  4279. \code{INT}, so we advance the period past \code{INT} for the rules in
  4280. slot $4$, of which there is just one, and put the following in slot $5$.
  4281. \begin{lstlisting}[escapechar=$]
  4282. exp_hi: INT . (4)
  4283. \end{lstlisting}
  4284. The period at the end of the rule triggers a completion action for the
  4285. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4286. So we advance the period and put the following in slot $5$.
  4287. \begin{lstlisting}[escapechar=$]
  4288. exp: exp "+" exp_hi . (2)
  4289. \end{lstlisting}
  4290. This triggers another completion action for the rules in slot $2$ that
  4291. have a period before \code{exp}.
  4292. \begin{lstlisting}[escapechar=$]
  4293. stmt: "print" "(" exp . ")" (0)
  4294. exp: exp . "+" exp_hi (2)
  4295. exp: exp . "-" exp_hi (2)
  4296. \end{lstlisting}
  4297. We scan the next input token \code{")"}, placing the following dotted
  4298. rule in slot $6$.
  4299. \begin{lstlisting}[escapechar=$]
  4300. stmt: "print" "(" exp ")" . (0)
  4301. \end{lstlisting}
  4302. This triggers the completion of \code{stmt} in slot $0$
  4303. \begin{lstlisting}
  4304. stmt_list: stmt . NEWLINE stmt_list (0)
  4305. \end{lstlisting}
  4306. The last input token is a \code{NEWLINE}, so we advance the period
  4307. and place the new dotted rule in slot $7$.
  4308. \begin{lstlisting}
  4309. stmt_list: stmt NEWLINE . stmt_list (0)
  4310. \end{lstlisting}
  4311. We are close to the end of parsing the input!
  4312. The period is before the \code{stmt\_list} nonterminal, so we
  4313. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4314. \begin{lstlisting}
  4315. stmt_list: . (7)
  4316. stmt_list: . stmt NEWLINE stmt_list (7)
  4317. stmt: . "print" "(" exp ")" (7)
  4318. stmt: . exp (7)
  4319. \end{lstlisting}
  4320. There is immediately an opportunity for completion of \code{stmt\_list},
  4321. so we add the following to slot $7$.
  4322. \begin{lstlisting}
  4323. stmt_list: stmt NEWLINE stmt_list . (0)
  4324. \end{lstlisting}
  4325. This triggers another completion action for \code{stmt\_list} in slot $0$
  4326. \begin{lstlisting}
  4327. lang_int: stmt_list . (0)
  4328. \end{lstlisting}
  4329. which in turn completes \code{lang\_int}, the start symbol of the
  4330. grammar, so the parsing of the input is complete.
  4331. For reference, we now give a general description of the Earley
  4332. algorithm.
  4333. \begin{enumerate}
  4334. \item The algorithm begins by initializing slot $0$ of the chart with the
  4335. grammar rule for the start symbol, placing a period at the beginning
  4336. of the right-hand side, and recording its starting position as $0$.
  4337. \item The algorithm repeatedly applies the following three kinds of
  4338. actions for as long as there are opportunities to do so.
  4339. \begin{itemize}
  4340. \item Prediction: if there is a rule in slot $k$ whose period comes
  4341. before a nonterminal, add the rules for that nonterminal into slot
  4342. $k$, placing a period at the beginning of their right-hand sides
  4343. and recording their starting position as $k$.
  4344. \item Scanning: If the token at position $k$ of the input string
  4345. matches the symbol after the period in a dotted rule in slot $k$
  4346. of the chart, advance the period in the dotted rule, adding
  4347. the result to slot $k+1$.
  4348. \item Completion: If a dotted rule in slot $k$ has a period at the
  4349. end, inspect the rules in the slot corresponding to the starting
  4350. position of the completed rule. If any of those rules have a
  4351. nonterminal following their period that matches the left-hand side
  4352. of the completed rule, then advance their period, placing the new
  4353. dotted rule in slot $k$.
  4354. \end{itemize}
  4355. While repeating these three actions, take care to never add
  4356. duplicate dotted rules to the chart.
  4357. \end{enumerate}
  4358. We have described how the Earley algorithm recognizes that an input
  4359. string matches a grammar, but we have not described how it builds a
  4360. parse tree. The basic idea is simple, but building parse trees in an
  4361. efficient way is more complex, requiring a data structure called a
  4362. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4363. to attach a partial parse tree to every dotted rule in the chart.
  4364. Initially, the tree node associated with a dotted rule has no
  4365. children. As the period moves to the right, the nodes from the
  4366. subparses are added as children to the tree node.
  4367. As mentioned at the beginning of this section, the Earley algorithm is
  4368. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4369. files that contain thousands of tokens in a reasonable amount of time,
  4370. but not millions.
  4371. %
  4372. In the next section we discuss the LALR(1) parsing algorithm, which is
  4373. efficient enough to use with even the largest of input files.
  4374. \section{The LALR(1) Algorithm}
  4375. \label{sec:lalr}
  4376. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4377. two phase approach in which it first compiles the grammar into a state
  4378. machine and then runs the state machine to parse an input string. The
  4379. second phase has time complexity $O(n)$ where $n$ is the number of
  4380. tokens in the input, so LALR(1) is the best one could hope for with
  4381. respect to efficiency.
  4382. %
  4383. A particularly influential implementation of LALR(1) is the
  4384. \texttt{yacc} parser generator by \citet{Johnson:1979qy}, which stands
  4385. for Yet Another Compiler Compiler.
  4386. %
  4387. The LALR(1) state machine uses a stack to record its progress in
  4388. parsing the input string. Each element of the stack is a pair: a
  4389. state number and a grammar symbol (a terminal or nonterminal). The
  4390. symbol characterizes the input that has been parsed so-far and the
  4391. state number is used to remember how to proceed once the next
  4392. symbol-worth of input has been parsed. Each state in the machine
  4393. represents where the parser stands in the parsing process with respect
  4394. to certain grammar rules. In particular, each state is associated with
  4395. a set of dotted rules.
  4396. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4397. (also called parse table) for the following simple but ambiguous
  4398. grammar:
  4399. \begin{lstlisting}[escapechar=$]
  4400. exp: INT
  4401. | exp "+" exp
  4402. stmt: "print" exp
  4403. start: stmt
  4404. \end{lstlisting}
  4405. Consider state 1 in Figure~\ref{fig:shift-reduce}. The parser has just
  4406. read in a \lstinline{"print"} token, so the top of the stack is
  4407. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4408. the input according to grammar rule 1, which is signified by showing
  4409. rule 1 with a period after the \code{"print"} token and before the
  4410. \code{exp} nonterminal. There are several rules that could apply next,
  4411. both rule 2 and 3, so state 1 also shows those rules with a period at
  4412. the beginning of their right-hand sides. The edges between states
  4413. indicate which transitions the machine should make depending on the
  4414. next input token. So, for example, if the next input token is
  4415. \code{INT} then the parser will push \code{INT} and the target state 4
  4416. on the stack and transition to state 4. Suppose we are now at the end
  4417. of the input. In state 4 it says we should reduce by rule 3, so we pop
  4418. from the stack the same number of items as the number of symbols in
  4419. the right-hand side of the rule, in this case just one. We then
  4420. momentarily jump to the state at the top of the stack (state 1) and
  4421. then follow the goto edge that corresponds to the left-hand side of
  4422. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4423. state 3. (A slightly longer example parse is shown in
  4424. Figure~\ref{fig:shift-reduce}.)
  4425. \begin{figure}[htbp]
  4426. \centering
  4427. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4428. \caption{An LALR(1) parse table and a trace of an example run.}
  4429. \label{fig:shift-reduce}
  4430. \end{figure}
  4431. In general, the algorithm works as follows. Set the current state to
  4432. state $0$. Then repeat the following, looking at the next input token.
  4433. \begin{itemize}
  4434. \item If there there is a shift edge for the input token in the
  4435. current state, push the edge's target state and the input token on
  4436. the stack and proceed to the edge's target state.
  4437. \item If there is a reduce action for the input token in the current
  4438. state, pop $k$ elements from the stack, where $k$ is the number of
  4439. symbols in the right-hand side of the rule being reduced. Jump to
  4440. the state at the top of the stack and then follow the goto edge for
  4441. the nonterminal that matches the left-hand side of the rule that we
  4442. reducing by. Push the edge's target state and the nonterminal on the
  4443. stack.
  4444. \end{itemize}
  4445. Notice that in state 6 of Figure~\ref{fig:shift-reduce} there is both
  4446. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4447. algorithm does not know which action to take in this case. When a
  4448. state has both a shift and a reduce action for the same token, we say
  4449. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4450. will arise, for example, when trying to parse the input
  4451. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2}
  4452. the parser will be in state 6, and it will not know whether to
  4453. reduce to form an \code{exp} of \lstinline{1 + 2}, or whether it
  4454. should proceed by shifting the next \lstinline{+} from the input.
  4455. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4456. arises when there are two reduce actions in a state for the same
  4457. token. To understand which grammars gives rise to shift/reduce and
  4458. reduce/reduce conflicts, it helps to know how the parse table is
  4459. generated from the grammar, which we discuss next.
  4460. The parse table is generated one state at a time. State 0 represents
  4461. the start of the parser. We add the grammar rule for the start symbol
  4462. to this state with a period at the beginning of the right-hand side,
  4463. similar to the initialization phase of the Earley parser. If the
  4464. period appears immediately before another nonterminal, we add all the
  4465. rules with that nonterminal on the left-hand side. Again, we place a
  4466. period at the beginning of the right-hand side of each the new
  4467. rules. This process, called \emph{state closure}, is continued
  4468. until there are no more rules to add (similar to the prediction
  4469. actions of an Earley parser). We then examine each dotted rule in the
  4470. current state $I$. Suppose a dotted rule has the form $A ::=
  4471. s_1.\,X s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4472. are sequences of symbols. We create a new state, call it $J$. If $X$
  4473. is a terminal, we create a shift edge from $I$ to $J$ (analogous to
  4474. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4475. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4476. state $J$. We start by adding all dotted rules from state $I$ that
  4477. have the form $B ::= s_1.\,Xs_2$ (where $B$ is any nonterminal and
  4478. $s_1$ and $s_2$ are arbitrary sequences of symbols), but with
  4479. the period moved past the $X$. (This is analogous to completion in
  4480. the Earley algorithm.) We then perform state closure on $J$. This
  4481. process repeats until there are no more states or edges to add.
  4482. We then mark states as accepting states if they have a dotted rule
  4483. that is the start rule with a period at the end. Also, to add
  4484. in the reduce actions, we look for any state containing a dotted rule
  4485. with a period at the end. Let $n$ be the rule number for this dotted
  4486. rule. We then put a reduce $n$ action into that state for every token
  4487. $Y$. For example, in Figure~\ref{fig:shift-reduce} state 4 has an
  4488. dotted rule with a period at the end. We therefore put a reduce by
  4489. rule 3 action into state 4 for every
  4490. token.
  4491. When inserting reduce actions, take care to spot any shift/reduce or
  4492. reduce/reduce conflicts. If there are any, abort the construction of
  4493. the parse table.
  4494. \begin{exercise}
  4495. \normalfont\normalsize
  4496. %
  4497. On a piece of paper, walk through the parse table generation process
  4498. for the grammar at the top of figure~\ref{fig:shift-reduce} and check
  4499. your results against parse table in figure~\ref{fig:shift-reduce}.
  4500. \end{exercise}
  4501. \begin{exercise}
  4502. \normalfont\normalsize
  4503. %
  4504. Change the parser in your compiler for \LangVar{} to set the
  4505. \code{parser} option of Lark to \code{'lalr'}. Test your compiler on
  4506. all the \LangVar{} programs that you have created. In doing so, Lark
  4507. may signal an error due to shift/reduce or reduce/reduce conflicts
  4508. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4509. remove those conflicts.
  4510. \end{exercise}
  4511. \section{Further Reading}
  4512. In this chapter we have just scratched the surface of the field of
  4513. parsing, with the study of a very general but less efficient algorithm
  4514. (Earley) and with a more limited but highly efficient algorithm
  4515. (LALR). There are many more algorithms, and classes of grammars, that
  4516. fall between these two ends of the spectrum. We recommend the reader
  4517. to \citet{Aho:2006wb} for a thorough treatment of parsing.
  4518. Regarding lexical analysis, we described the specification language,
  4519. the regular expressions, but not the algorithms for recognizing them.
  4520. In short, regular expressions can be translated to nondeterministic
  4521. finite automata, which in turn are translated to finite automata. We
  4522. refer the reader again to \citet{Aho:2006wb} for all the details on
  4523. lexical analysis.
  4524. \fi}
  4525. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4526. \chapter{Register Allocation}
  4527. \label{ch:register-allocation-Lvar}
  4528. \setcounter{footnote}{0}
  4529. \index{subject}{register allocation}
  4530. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4531. storing variables on the procedure call stack. The CPU may require tens
  4532. to hundreds of cycles to access a location on the stack, whereas
  4533. accessing a register takes only a single cycle. In this chapter we
  4534. improve the efficiency of our generated code by storing some variables
  4535. in registers. The goal of register allocation is to fit as many
  4536. variables into registers as possible. Some programs have more
  4537. variables than registers, so we cannot always map each variable to a
  4538. different register. Fortunately, it is common for different variables
  4539. to be in use during different periods of time during program
  4540. execution, and in those cases we can map multiple variables to the
  4541. same register.
  4542. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4543. example. The source program is on the left and the output of
  4544. instruction selection is on the right. The program is almost
  4545. completely in the x86 assembly language, but it still uses variables.
  4546. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4547. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4548. the other hand, is used only after this point, so \code{x} and
  4549. \code{z} could share the same register.
  4550. \begin{figure}
  4551. \begin{tcolorbox}[colback=white]
  4552. \begin{minipage}{0.45\textwidth}
  4553. Example \LangVar{} program:
  4554. % var_test_28.rkt
  4555. {\if\edition\racketEd
  4556. \begin{lstlisting}
  4557. (let ([v 1])
  4558. (let ([w 42])
  4559. (let ([x (+ v 7)])
  4560. (let ([y x])
  4561. (let ([z (+ x w)])
  4562. (+ z (- y)))))))
  4563. \end{lstlisting}
  4564. \fi}
  4565. {\if\edition\pythonEd
  4566. \begin{lstlisting}
  4567. v = 1
  4568. w = 42
  4569. x = v + 7
  4570. y = x
  4571. z = x + w
  4572. print(z + (- y))
  4573. \end{lstlisting}
  4574. \fi}
  4575. \end{minipage}
  4576. \begin{minipage}{0.45\textwidth}
  4577. After instruction selection:
  4578. {\if\edition\racketEd
  4579. \begin{lstlisting}
  4580. locals-types:
  4581. x : Integer, y : Integer,
  4582. z : Integer, t : Integer,
  4583. v : Integer, w : Integer
  4584. start:
  4585. movq $1, v
  4586. movq $42, w
  4587. movq v, x
  4588. addq $7, x
  4589. movq x, y
  4590. movq x, z
  4591. addq w, z
  4592. movq y, t
  4593. negq t
  4594. movq z, %rax
  4595. addq t, %rax
  4596. jmp conclusion
  4597. \end{lstlisting}
  4598. \fi}
  4599. {\if\edition\pythonEd
  4600. \begin{lstlisting}
  4601. movq $1, v
  4602. movq $42, w
  4603. movq v, x
  4604. addq $7, x
  4605. movq x, y
  4606. movq x, z
  4607. addq w, z
  4608. movq y, tmp_0
  4609. negq tmp_0
  4610. movq z, tmp_1
  4611. addq tmp_0, tmp_1
  4612. movq tmp_1, %rdi
  4613. callq print_int
  4614. \end{lstlisting}
  4615. \fi}
  4616. \end{minipage}
  4617. \end{tcolorbox}
  4618. \caption{A running example for register allocation.}
  4619. \label{fig:reg-eg}
  4620. \end{figure}
  4621. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4622. compute where a variable is in use. Once we have that information, we
  4623. compute which variables are in use at the same time, i.e., which ones
  4624. \emph{interfere}\index{subject}{interfere} with each other, and
  4625. represent this relation as an undirected graph whose vertices are
  4626. variables and edges indicate when two variables interfere
  4627. (section~\ref{sec:build-interference}). We then model register
  4628. allocation as a graph coloring problem
  4629. (section~\ref{sec:graph-coloring}).
  4630. If we run out of registers despite these efforts, we place the
  4631. remaining variables on the stack, similarly to how we handled
  4632. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4633. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4634. location. The decision to spill a variable is handled as part of the
  4635. graph coloring process.
  4636. We make the simplifying assumption that each variable is assigned to
  4637. one location (a register or stack address). A more sophisticated
  4638. approach is to assign a variable to one or more locations in different
  4639. regions of the program. For example, if a variable is used many times
  4640. in short sequence and then used again only after many other
  4641. instructions, it could be more efficient to assign the variable to a
  4642. register during the initial sequence and then move it to the stack for
  4643. the rest of its lifetime. We refer the interested reader to
  4644. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4645. approach.
  4646. % discuss prioritizing variables based on how much they are used.
  4647. \section{Registers and Calling Conventions}
  4648. \label{sec:calling-conventions}
  4649. \index{subject}{calling conventions}
  4650. As we perform register allocation, we must be aware of the
  4651. \emph{calling conventions} \index{subject}{calling conventions} that
  4652. govern how functions calls are performed in x86.
  4653. %
  4654. Even though \LangVar{} does not include programmer-defined functions,
  4655. our generated code includes a \code{main} function that is called by
  4656. the operating system and our generated code contains calls to the
  4657. \code{read\_int} function.
  4658. Function calls require coordination between two pieces of code that
  4659. may be written by different programmers or generated by different
  4660. compilers. Here we follow the System V calling conventions that are
  4661. used by the GNU C compiler on Linux and
  4662. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4663. %
  4664. The calling conventions include rules about how functions share the
  4665. use of registers. In particular, the caller is responsible for freeing
  4666. some registers prior to the function call for use by the callee.
  4667. These are called the \emph{caller-saved registers}
  4668. \index{subject}{caller-saved registers}
  4669. and they are
  4670. \begin{lstlisting}
  4671. rax rcx rdx rsi rdi r8 r9 r10 r11
  4672. \end{lstlisting}
  4673. On the other hand, the callee is responsible for preserving the values
  4674. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4675. which are
  4676. \begin{lstlisting}
  4677. rsp rbp rbx r12 r13 r14 r15
  4678. \end{lstlisting}
  4679. We can think about this caller/callee convention from two points of
  4680. view, the caller view and the callee view, as follows:
  4681. \begin{itemize}
  4682. \item The caller should assume that all the caller-saved registers get
  4683. overwritten with arbitrary values by the callee. On the other hand,
  4684. the caller can safely assume that all the callee-saved registers
  4685. retain their original values.
  4686. \item The callee can freely use any of the caller-saved registers.
  4687. However, if the callee wants to use a callee-saved register, the
  4688. callee must arrange to put the original value back in the register
  4689. prior to returning to the caller. This can be accomplished by saving
  4690. the value to the stack in the prelude of the function and restoring
  4691. the value in the conclusion of the function.
  4692. \end{itemize}
  4693. In x86, registers are also used for passing arguments to a function
  4694. and for the return value. In particular, the first six arguments of a
  4695. function are passed in the following six registers, in this order.
  4696. \index{subject}{argument-passing registers}
  4697. \index{subject}{parameter-passing registers}
  4698. \begin{lstlisting}
  4699. rdi rsi rdx rcx r8 r9
  4700. \end{lstlisting}
  4701. If there are more than six arguments, the convention is to use
  4702. space on the frame of the caller for the rest of the
  4703. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  4704. need more than six arguments.
  4705. %
  4706. \racket{For now, the only function we care about is \code{read\_int},
  4707. which takes zero arguments.}
  4708. %
  4709. \python{For now, the only functions we care about are \code{read\_int}
  4710. and \code{print\_int}, which take zero and one argument, respectively.}
  4711. %
  4712. The register \code{rax} is used for the return value of a function.
  4713. The next question is how these calling conventions impact register
  4714. allocation. Consider the \LangVar{} program presented in
  4715. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4716. example from the caller point of view and then from the callee point
  4717. of view. We refer to a variable that is in use during a function call
  4718. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4719. The program makes two calls to \READOP{}. The variable \code{x} is
  4720. call-live because it is in use during the second call to \READOP{}; we
  4721. must ensure that the value in \code{x} does not get overwritten during
  4722. the call to \READOP{}. One obvious approach is to save all the values
  4723. that reside in caller-saved registers to the stack prior to each
  4724. function call and to restore them after each call. That way, if the
  4725. register allocator chooses to assign \code{x} to a caller-saved
  4726. register, its value will be preserved across the call to \READOP{}.
  4727. However, saving and restoring to the stack is relatively slow. If
  4728. \code{x} is not used many times, it may be better to assign \code{x}
  4729. to a stack location in the first place. Or better yet, if we can
  4730. arrange for \code{x} to be placed in a callee-saved register, then it
  4731. won't need to be saved and restored during function calls.
  4732. We recommend an approach that captures these issues in the
  4733. interference graph, without complicating the graph coloring algorithm.
  4734. During liveness analysis we know which variables are call-live because
  4735. we compute which variables are in use at every instruction
  4736. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4737. interference graph (section~\ref{sec:build-interference}), we can
  4738. place an edge in the interference graph between each call-live
  4739. variable and the caller-saved registers. This will prevent the graph
  4740. coloring algorithm from assigning call-live variables to caller-saved
  4741. registers.
  4742. On the other hand, for variables that are not call-live, we prefer
  4743. placing them in caller-saved registers to leave more room for
  4744. call-live variables in the callee-saved registers. This can also be
  4745. implemented without complicating the graph coloring algorithm. We
  4746. recommend that the graph coloring algorithm assign variables to
  4747. natural numbers, choosing the lowest number for which there is no
  4748. interference. After the coloring is complete, we assign the numbers to
  4749. registers and stack locations: placing the caller-saved registers in
  4750. the lowest numbers, followed by the callee-saved registers, then
  4751. placing the largest numbers in stack locations. This ordering gives
  4752. preference to registers over stack locations and to caller-saved
  4753. registers over callee-saved registers.
  4754. Returning to the example in
  4755. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4756. generated x86 code on the right-hand side. Variable \code{x} is
  4757. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4758. in a safe place during the second call to \code{read\_int}. Next,
  4759. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4760. because \code{y} is not a call-live variable.
  4761. We have completed the analysis from the caller point of view, so now
  4762. we switch to the callee point of view, focusing on the prelude and
  4763. conclusion of the \code{main} function. As usual, the prelude begins
  4764. with saving the \code{rbp} register to the stack and setting the
  4765. \code{rbp} to the current stack pointer. We now know why it is
  4766. necessary to save the \code{rbp}: it is a callee-saved register. The
  4767. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4768. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4769. (\code{x}). The other callee-saved registers are not saved in the
  4770. prelude because they are not used. The prelude subtracts 8 bytes from
  4771. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4772. conclusion, we see that \code{rbx} is restored from the stack with a
  4773. \code{popq} instruction.
  4774. \index{subject}{prelude}\index{subject}{conclusion}
  4775. \begin{figure}[tp]
  4776. \begin{tcolorbox}[colback=white]
  4777. \begin{minipage}{0.45\textwidth}
  4778. Example \LangVar{} program:
  4779. %var_test_14.rkt
  4780. {\if\edition\racketEd
  4781. \begin{lstlisting}
  4782. (let ([x (read)])
  4783. (let ([y (read)])
  4784. (+ (+ x y) 42)))
  4785. \end{lstlisting}
  4786. \fi}
  4787. {\if\edition\pythonEd
  4788. \begin{lstlisting}
  4789. x = input_int()
  4790. y = input_int()
  4791. print((x + y) + 42)
  4792. \end{lstlisting}
  4793. \fi}
  4794. \end{minipage}
  4795. \begin{minipage}{0.45\textwidth}
  4796. Generated x86 assembly:
  4797. {\if\edition\racketEd
  4798. \begin{lstlisting}
  4799. start:
  4800. callq read_int
  4801. movq %rax, %rbx
  4802. callq read_int
  4803. movq %rax, %rcx
  4804. addq %rcx, %rbx
  4805. movq %rbx, %rax
  4806. addq $42, %rax
  4807. jmp _conclusion
  4808. .globl main
  4809. main:
  4810. pushq %rbp
  4811. movq %rsp, %rbp
  4812. pushq %rbx
  4813. subq $8, %rsp
  4814. jmp start
  4815. conclusion:
  4816. addq $8, %rsp
  4817. popq %rbx
  4818. popq %rbp
  4819. retq
  4820. \end{lstlisting}
  4821. \fi}
  4822. {\if\edition\pythonEd
  4823. \begin{lstlisting}
  4824. .globl main
  4825. main:
  4826. pushq %rbp
  4827. movq %rsp, %rbp
  4828. pushq %rbx
  4829. subq $8, %rsp
  4830. callq read_int
  4831. movq %rax, %rbx
  4832. callq read_int
  4833. movq %rax, %rcx
  4834. movq %rbx, %rdx
  4835. addq %rcx, %rdx
  4836. movq %rdx, %rcx
  4837. addq $42, %rcx
  4838. movq %rcx, %rdi
  4839. callq print_int
  4840. addq $8, %rsp
  4841. popq %rbx
  4842. popq %rbp
  4843. retq
  4844. \end{lstlisting}
  4845. \fi}
  4846. \end{minipage}
  4847. \end{tcolorbox}
  4848. \caption{An example with function calls.}
  4849. \label{fig:example-calling-conventions}
  4850. \end{figure}
  4851. %\clearpage
  4852. \section{Liveness Analysis}
  4853. \label{sec:liveness-analysis-Lvar}
  4854. \index{subject}{liveness analysis}
  4855. The \code{uncover\_live} \racket{pass}\python{function} performs
  4856. \emph{liveness analysis}; that is, it discovers which variables are
  4857. in use in different regions of a program.
  4858. %
  4859. A variable or register is \emph{live} at a program point if its
  4860. current value is used at some later point in the program. We refer to
  4861. variables, stack locations, and registers collectively as
  4862. \emph{locations}.
  4863. %
  4864. Consider the following code fragment in which there are two writes to
  4865. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4866. time?
  4867. \begin{center}
  4868. \begin{minipage}{0.96\textwidth}
  4869. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4870. movq $5, a
  4871. movq $30, b
  4872. movq a, c
  4873. movq $10, b
  4874. addq b, c
  4875. \end{lstlisting}
  4876. \end{minipage}
  4877. \end{center}
  4878. The answer is no, because \code{a} is live from line 1 to 3 and
  4879. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4880. line 2 is never used because it is overwritten (line 4) before the
  4881. next read (line 5).
  4882. The live locations for each instruction can be computed by traversing
  4883. the instruction sequence back to front (i.e., backward in execution
  4884. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4885. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4886. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4887. locations before instruction $I_k$. \racket{We recommend representing
  4888. these sets with the Racket \code{set} data structure described in
  4889. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4890. with the Python
  4891. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4892. data structure.}
  4893. {\if\edition\racketEd
  4894. \begin{figure}[tp]
  4895. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4896. \small
  4897. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4898. A \emph{set} is an unordered collection of elements without duplicates.
  4899. Here are some of the operations defined on sets.
  4900. \index{subject}{set}
  4901. \begin{description}
  4902. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4903. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4904. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4905. difference of the two sets.
  4906. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4907. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4908. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4909. \end{description}
  4910. \end{tcolorbox}
  4911. %\end{wrapfigure}
  4912. \caption{The \code{set} data structure.}
  4913. \label{fig:set}
  4914. \end{figure}
  4915. \fi}
  4916. The live locations after an instruction are always the same as the
  4917. live locations before the next instruction.
  4918. \index{subject}{live-after} \index{subject}{live-before}
  4919. \begin{equation} \label{eq:live-after-before-next}
  4920. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4921. \end{equation}
  4922. To start things off, there are no live locations after the last
  4923. instruction, so
  4924. \begin{equation}\label{eq:live-last-empty}
  4925. L_{\mathsf{after}}(n) = \emptyset
  4926. \end{equation}
  4927. We then apply the following rule repeatedly, traversing the
  4928. instruction sequence back to front.
  4929. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4930. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4931. \end{equation}
  4932. where $W(k)$ are the locations written to by instruction $I_k$, and
  4933. $R(k)$ are the locations read by instruction $I_k$.
  4934. {\if\edition\racketEd
  4935. %
  4936. There is a special case for \code{jmp} instructions. The locations
  4937. that are live before a \code{jmp} should be the locations in
  4938. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4939. maintaining an alist named \code{label->live} that maps each label to
  4940. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4941. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4942. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4943. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4944. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4945. %
  4946. \fi}
  4947. Let us walk through the previous example, applying these formulas
  4948. starting with the instruction on line 5 of the code fragment. We
  4949. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4950. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4951. $\emptyset$ because it is the last instruction
  4952. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4953. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4954. variables \code{b} and \code{c}
  4955. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4956. \[
  4957. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4958. \]
  4959. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4960. the live-before set from line 5 to be the live-after set for this
  4961. instruction (formula~\eqref{eq:live-after-before-next}).
  4962. \[
  4963. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4964. \]
  4965. This move instruction writes to \code{b} and does not read from any
  4966. variables, so we have the following live-before set
  4967. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4968. \[
  4969. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4970. \]
  4971. The live-before for instruction \code{movq a, c}
  4972. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4973. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4974. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4975. variable that is not live and does not read from a variable.
  4976. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4977. because it writes to variable \code{a}.
  4978. \begin{figure}[tbp]
  4979. \centering
  4980. \begin{tcolorbox}[colback=white]
  4981. \hspace{10pt}
  4982. \begin{minipage}{0.4\textwidth}
  4983. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4984. movq $5, a
  4985. movq $30, b
  4986. movq a, c
  4987. movq $10, b
  4988. addq b, c
  4989. \end{lstlisting}
  4990. \end{minipage}
  4991. \vrule\hspace{10pt}
  4992. \begin{minipage}{0.45\textwidth}
  4993. \begin{align*}
  4994. L_{\mathsf{before}}(1)= \emptyset,
  4995. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4996. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4997. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4998. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4999. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5000. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5001. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5002. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5003. L_{\mathsf{after}}(5)= \emptyset
  5004. \end{align*}
  5005. \end{minipage}
  5006. \end{tcolorbox}
  5007. \caption{Example output of liveness analysis on a short example.}
  5008. \label{fig:liveness-example-0}
  5009. \end{figure}
  5010. \begin{exercise}\normalfont\normalsize
  5011. Perform liveness analysis by hand on the running example in
  5012. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5013. sets for each instruction. Compare your answers to the solution
  5014. shown in figure~\ref{fig:live-eg}.
  5015. \end{exercise}
  5016. \begin{figure}[tp]
  5017. \hspace{20pt}
  5018. \begin{minipage}{0.55\textwidth}
  5019. \begin{tcolorbox}[colback=white]
  5020. {\if\edition\racketEd
  5021. \begin{lstlisting}
  5022. |$\{\ttm{rsp}\}$|
  5023. movq $1, v
  5024. |$\{\ttm{v},\ttm{rsp}\}$|
  5025. movq $42, w
  5026. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5027. movq v, x
  5028. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5029. addq $7, x
  5030. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5031. movq x, y
  5032. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5033. movq x, z
  5034. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5035. addq w, z
  5036. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5037. movq y, t
  5038. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5039. negq t
  5040. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5041. movq z, %rax
  5042. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5043. addq t, %rax
  5044. |$\{\ttm{rax},\ttm{rsp}\}$|
  5045. jmp conclusion
  5046. \end{lstlisting}
  5047. \fi}
  5048. {\if\edition\pythonEd
  5049. \begin{lstlisting}
  5050. movq $1, v
  5051. |$\{\ttm{v}\}$|
  5052. movq $42, w
  5053. |$\{\ttm{w}, \ttm{v}\}$|
  5054. movq v, x
  5055. |$\{\ttm{w}, \ttm{x}\}$|
  5056. addq $7, x
  5057. |$\{\ttm{w}, \ttm{x}\}$|
  5058. movq x, y
  5059. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5060. movq x, z
  5061. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5062. addq w, z
  5063. |$\{\ttm{y}, \ttm{z}\}$|
  5064. movq y, tmp_0
  5065. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5066. negq tmp_0
  5067. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5068. movq z, tmp_1
  5069. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5070. addq tmp_0, tmp_1
  5071. |$\{\ttm{tmp\_1}\}$|
  5072. movq tmp_1, %rdi
  5073. |$\{\ttm{rdi}\}$|
  5074. callq print_int
  5075. |$\{\}$|
  5076. \end{lstlisting}
  5077. \fi}
  5078. \end{tcolorbox}
  5079. \end{minipage}
  5080. \caption{The running example annotated with live-after sets.}
  5081. \label{fig:live-eg}
  5082. \end{figure}
  5083. \begin{exercise}\normalfont\normalsize
  5084. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5085. %
  5086. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5087. field of the \code{Block} structure.}
  5088. %
  5089. \python{Return a dictionary that maps each instruction to its
  5090. live-after set.}
  5091. %
  5092. \racket{We recommend creating an auxiliary function that takes a list
  5093. of instructions and an initial live-after set (typically empty) and
  5094. returns the list of live-after sets.}
  5095. %
  5096. We recommend creating auxiliary functions to (1) compute the set
  5097. of locations that appear in an \Arg{}, (2) compute the locations read
  5098. by an instruction (the $R$ function), and (3) the locations written by
  5099. an instruction (the $W$ function). The \code{callq} instruction should
  5100. include all the caller-saved registers in its write set $W$ because
  5101. the calling convention says that those registers may be written to
  5102. during the function call. Likewise, the \code{callq} instruction
  5103. should include the appropriate argument-passing registers in its
  5104. read set $R$, depending on the arity of the function being
  5105. called. (This is why the abstract syntax for \code{callq} includes the
  5106. arity.)
  5107. \end{exercise}
  5108. %\clearpage
  5109. \section{Build the Interference Graph}
  5110. \label{sec:build-interference}
  5111. {\if\edition\racketEd
  5112. \begin{figure}[tp]
  5113. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5114. \small
  5115. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5116. A \emph{graph} is a collection of vertices and edges where each
  5117. edge connects two vertices. A graph is \emph{directed} if each
  5118. edge points from a source to a target. Otherwise the graph is
  5119. \emph{undirected}.
  5120. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5121. \begin{description}
  5122. %% We currently don't use directed graphs. We instead use
  5123. %% directed multi-graphs. -Jeremy
  5124. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5125. directed graph from a list of edges. Each edge is a list
  5126. containing the source and target vertex.
  5127. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5128. undirected graph from a list of edges. Each edge is represented by
  5129. a list containing two vertices.
  5130. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5131. inserts a vertex into the graph.
  5132. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5133. inserts an edge between the two vertices.
  5134. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5135. returns a sequence of vertices adjacent to the vertex.
  5136. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5137. returns a sequence of all vertices in the graph.
  5138. \end{description}
  5139. \end{tcolorbox}
  5140. %\end{wrapfigure}
  5141. \caption{The Racket \code{graph} package.}
  5142. \label{fig:graph}
  5143. \end{figure}
  5144. \fi}
  5145. On the basis of the liveness analysis, we know where each location is
  5146. live. However, during register allocation, we need to answer
  5147. questions of the specific form: are locations $u$ and $v$ live at the
  5148. same time? (If so, they cannot be assigned to the same register.) To
  5149. make this question more efficient to answer, we create an explicit
  5150. data structure, an \emph{interference
  5151. graph}\index{subject}{interference graph}. An interference graph is
  5152. an undirected graph that has an edge between two locations if they are
  5153. live at the same time, that is, if they interfere with each other.
  5154. %
  5155. \racket{We recommend using the Racket \code{graph} package
  5156. (figure~\ref{fig:graph}) to represent the interference graph.}
  5157. %
  5158. \python{We provide implementations of directed and undirected graph
  5159. data structures in the file \code{graph.py} of the support code.}
  5160. A straightforward way to compute the interference graph is to look at
  5161. the set of live locations between each instruction and add an edge to
  5162. the graph for every pair of variables in the same set. This approach
  5163. is less than ideal for two reasons. First, it can be expensive because
  5164. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5165. locations. Second, in the special case in which two locations hold the
  5166. same value (because one was assigned to the other), they can be live
  5167. at the same time without interfering with each other.
  5168. A better way to compute the interference graph is to focus on
  5169. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5170. must not overwrite something in a live location. So for each
  5171. instruction, we create an edge between the locations being written to
  5172. and the live locations. (However, a location never interferes with
  5173. itself.) For the \key{callq} instruction, we consider all the
  5174. caller-saved registers to have been written to, so an edge is added
  5175. between every live variable and every caller-saved register. Also, for
  5176. \key{movq} there is the special case of two variables holding the same
  5177. value. If a live variable $v$ is the same as the source of the
  5178. \key{movq}, then there is no need to add an edge between $v$ and the
  5179. destination, because they both hold the same value.
  5180. %
  5181. Hence we have the following two rules:
  5182. \begin{enumerate}
  5183. \item If instruction $I_k$ is a move instruction of the form
  5184. \key{movq} $s$\key{,} $d$, then for every $v \in
  5185. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5186. $(d,v)$.
  5187. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5188. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5189. $(d,v)$.
  5190. \end{enumerate}
  5191. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5192. these rules to each instruction. We highlight a few of the
  5193. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5194. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5195. so \code{v} interferes with \code{rsp}.}
  5196. %
  5197. \python{The first instruction is \lstinline{movq $1, v}, and the
  5198. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  5199. no interference because $\ttm{v}$ is the destination of the move.}
  5200. %
  5201. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5202. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  5203. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5204. %
  5205. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5206. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  5207. $\ttm{x}$ interferes with \ttm{w}.}
  5208. %
  5209. \racket{The next instruction is \lstinline{movq x, y}, and the
  5210. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5211. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5212. \ttm{x} because \ttm{x} is the source of the move and therefore
  5213. \ttm{x} and \ttm{y} hold the same value.}
  5214. %
  5215. \python{The next instruction is \lstinline{movq x, y}, and the
  5216. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5217. applies, so \ttm{y} interferes with \ttm{w} but not
  5218. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5219. \ttm{x} and \ttm{y} hold the same value.}
  5220. %
  5221. Figure~\ref{fig:interference-results} lists the interference results
  5222. for all the instructions, and the resulting interference graph is
  5223. shown in figure~\ref{fig:interfere}.
  5224. \begin{figure}[tbp]
  5225. \begin{tcolorbox}[colback=white]
  5226. \begin{quote}
  5227. {\if\edition\racketEd
  5228. \begin{tabular}{ll}
  5229. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5230. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5231. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5232. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5233. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5234. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5235. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5236. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5237. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5238. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5239. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5240. \lstinline!jmp conclusion!& no interference.
  5241. \end{tabular}
  5242. \fi}
  5243. {\if\edition\pythonEd
  5244. \begin{tabular}{ll}
  5245. \lstinline!movq $1, v!& no interference\\
  5246. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5247. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5248. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5249. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5250. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5251. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5252. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5253. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5254. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5255. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5256. \lstinline!movq tmp_1, %rdi! & no interference \\
  5257. \lstinline!callq print_int!& no interference.
  5258. \end{tabular}
  5259. \fi}
  5260. \end{quote}
  5261. \end{tcolorbox}
  5262. \caption{Interference results for the running example.}
  5263. \label{fig:interference-results}
  5264. \end{figure}
  5265. \begin{figure}[tbp]
  5266. \begin{tcolorbox}[colback=white]
  5267. \large
  5268. {\if\edition\racketEd
  5269. \[
  5270. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5271. \node (rax) at (0,0) {$\ttm{rax}$};
  5272. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5273. \node (t1) at (0,2) {$\ttm{t}$};
  5274. \node (z) at (3,2) {$\ttm{z}$};
  5275. \node (x) at (6,2) {$\ttm{x}$};
  5276. \node (y) at (3,0) {$\ttm{y}$};
  5277. \node (w) at (6,0) {$\ttm{w}$};
  5278. \node (v) at (9,0) {$\ttm{v}$};
  5279. \draw (t1) to (rax);
  5280. \draw (t1) to (z);
  5281. \draw (z) to (y);
  5282. \draw (z) to (w);
  5283. \draw (x) to (w);
  5284. \draw (y) to (w);
  5285. \draw (v) to (w);
  5286. \draw (v) to (rsp);
  5287. \draw (w) to (rsp);
  5288. \draw (x) to (rsp);
  5289. \draw (y) to (rsp);
  5290. \path[-.,bend left=15] (z) edge node {} (rsp);
  5291. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5292. \draw (rax) to (rsp);
  5293. \end{tikzpicture}
  5294. \]
  5295. \fi}
  5296. {\if\edition\pythonEd
  5297. \[
  5298. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5299. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5300. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5301. \node (z) at (3,2) {$\ttm{z}$};
  5302. \node (x) at (6,2) {$\ttm{x}$};
  5303. \node (y) at (3,0) {$\ttm{y}$};
  5304. \node (w) at (6,0) {$\ttm{w}$};
  5305. \node (v) at (9,0) {$\ttm{v}$};
  5306. \draw (t0) to (t1);
  5307. \draw (t0) to (z);
  5308. \draw (z) to (y);
  5309. \draw (z) to (w);
  5310. \draw (x) to (w);
  5311. \draw (y) to (w);
  5312. \draw (v) to (w);
  5313. \end{tikzpicture}
  5314. \]
  5315. \fi}
  5316. \end{tcolorbox}
  5317. \caption{The interference graph of the example program.}
  5318. \label{fig:interfere}
  5319. \end{figure}
  5320. %% Our next concern is to choose a data structure for representing the
  5321. %% interference graph. There are many choices for how to represent a
  5322. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  5323. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  5324. %% data structure is to study the algorithm that uses the data structure,
  5325. %% determine what operations need to be performed, and then choose the
  5326. %% data structure that provide the most efficient implementations of
  5327. %% those operations. Often times the choice of data structure can have an
  5328. %% effect on the time complexity of the algorithm, as it does here. If
  5329. %% you skim the next section, you will see that the register allocation
  5330. %% algorithm needs to ask the graph for all its vertices and, given a
  5331. %% vertex, it needs to known all the adjacent vertices. Thus, the
  5332. %% correct choice of graph representation is that of an adjacency
  5333. %% list. There are helper functions in \code{utilities.rkt} for
  5334. %% representing graphs using the adjacency list representation:
  5335. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  5336. %% (Appendix~\ref{appendix:utilities}).
  5337. %% %
  5338. %% \margincomment{\footnotesize To do: change to use the
  5339. %% Racket graph library. \\ --Jeremy}
  5340. %% %
  5341. %% In particular, those functions use a hash table to map each vertex to
  5342. %% the set of adjacent vertices, and the sets are represented using
  5343. %% Racket's \key{set}, which is also a hash table.
  5344. \begin{exercise}\normalfont\normalsize
  5345. \racket{Implement the compiler pass named \code{build\_interference} according
  5346. to the algorithm suggested here. We recommend using the Racket
  5347. \code{graph} package to create and inspect the interference graph.
  5348. The output graph of this pass should be stored in the $\itm{info}$ field of
  5349. the program, under the key \code{conflicts}.}
  5350. %
  5351. \python{Implement a function named \code{build\_interference}
  5352. according to the algorithm suggested above that
  5353. returns the interference graph.}
  5354. \end{exercise}
  5355. \section{Graph Coloring via Sudoku}
  5356. \label{sec:graph-coloring}
  5357. \index{subject}{graph coloring}
  5358. \index{subject}{sudoku}
  5359. \index{subject}{color}
  5360. We come to the main event discussed in this chapter, mapping variables
  5361. to registers and stack locations. Variables that interfere with each
  5362. other must be mapped to different locations. In terms of the
  5363. interference graph, this means that adjacent vertices must be mapped
  5364. to different locations. If we think of locations as colors, the
  5365. register allocation problem becomes the graph coloring
  5366. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5367. The reader may be more familiar with the graph coloring problem than he
  5368. or she realizes; the popular game of sudoku is an instance of the
  5369. graph coloring problem. The following describes how to build a graph
  5370. out of an initial sudoku board.
  5371. \begin{itemize}
  5372. \item There is one vertex in the graph for each sudoku square.
  5373. \item There is an edge between two vertices if the corresponding squares
  5374. are in the same row, in the same column, or in the same $3\times 3$ region.
  5375. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5376. \item On the basis of the initial assignment of numbers to squares on the
  5377. sudoku board, assign the corresponding colors to the corresponding
  5378. vertices in the graph.
  5379. \end{itemize}
  5380. If you can color the remaining vertices in the graph with the nine
  5381. colors, then you have also solved the corresponding game of sudoku.
  5382. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5383. the corresponding graph with colored vertices. Here we use a
  5384. monochrome representation of colors, mapping the sudoku number 1 to
  5385. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5386. of the vertices (the colored ones) because showing edges for all the
  5387. vertices would make the graph unreadable.
  5388. \begin{figure}[tbp]
  5389. \begin{tcolorbox}[colback=white]
  5390. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5391. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5392. \end{tcolorbox}
  5393. \caption{A sudoku game board and the corresponding colored graph.}
  5394. \label{fig:sudoku-graph}
  5395. \end{figure}
  5396. Some techniques for playing sudoku correspond to heuristics used in
  5397. graph coloring algorithms. For example, one of the basic techniques
  5398. for sudoku is called Pencil Marks. The idea is to use a process of
  5399. elimination to determine what numbers are no longer available for a
  5400. square and to write those numbers in the square (writing very
  5401. small). For example, if the number $1$ is assigned to a square, then
  5402. write the pencil mark $1$ in all the squares in the same row, column,
  5403. and region to indicate that $1$ is no longer an option for those other
  5404. squares.
  5405. %
  5406. The Pencil Marks technique corresponds to the notion of
  5407. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5408. saturation of a vertex, in sudoku terms, is the set of numbers that
  5409. are no longer available. In graph terminology, we have the following
  5410. definition:
  5411. \begin{equation*}
  5412. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5413. \text{ and } \mathrm{color}(v) = c \}
  5414. \end{equation*}
  5415. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5416. edge with $u$.
  5417. The Pencil Marks technique leads to a simple strategy for filling in
  5418. numbers: if there is a square with only one possible number left, then
  5419. choose that number! But what if there are no squares with only one
  5420. possibility left? One brute-force approach is to try them all: choose
  5421. the first one, and if that ultimately leads to a solution, great. If
  5422. not, backtrack and choose the next possibility. One good thing about
  5423. Pencil Marks is that it reduces the degree of branching in the search
  5424. tree. Nevertheless, backtracking can be terribly time consuming. One
  5425. way to reduce the amount of backtracking is to use the
  5426. most-constrained-first heuristic (aka minimum remaining
  5427. values)~\citep{Russell2003}. That is, in choosing a square, always
  5428. choose one with the fewest possibilities left (the vertex with the
  5429. highest saturation). The idea is that choosing highly constrained
  5430. squares earlier rather than later is better, because later on there may
  5431. not be any possibilities left in the highly saturated squares.
  5432. However, register allocation is easier than sudoku, because the
  5433. register allocator can fall back to assigning variables to stack
  5434. locations when the registers run out. Thus, it makes sense to replace
  5435. backtracking with greedy search: make the best choice at the time and
  5436. keep going. We still wish to minimize the number of colors needed, so
  5437. we use the most-constrained-first heuristic in the greedy search.
  5438. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5439. algorithm for register allocation based on saturation and the
  5440. most-constrained-first heuristic. It is roughly equivalent to the
  5441. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  5442. Just as in sudoku, the algorithm represents colors with integers. The
  5443. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  5444. for register allocation. The integers $k$ and larger correspond to
  5445. stack locations. The registers that are not used for register
  5446. allocation, such as \code{rax}, are assigned to negative integers. In
  5447. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  5448. %% One might wonder why we include registers at all in the liveness
  5449. %% analysis and interference graph. For example, we never allocate a
  5450. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  5451. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  5452. %% to use register for passing arguments to functions, it will be
  5453. %% necessary for those registers to appear in the interference graph
  5454. %% because those registers will also be assigned to variables, and we
  5455. %% don't want those two uses to encroach on each other. Regarding
  5456. %% registers such as \code{rax} and \code{rsp} that are not used for
  5457. %% variables, we could omit them from the interference graph but that
  5458. %% would require adding special cases to our algorithm, which would
  5459. %% complicate the logic for little gain.
  5460. \begin{figure}[btp]
  5461. \begin{tcolorbox}[colback=white]
  5462. \centering
  5463. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5464. Algorithm: DSATUR
  5465. Input: A graph |$G$|
  5466. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5467. |$W \gets \mathrm{vertices}(G)$|
  5468. while |$W \neq \emptyset$| do
  5469. pick a vertex |$u$| from |$W$| with the highest saturation,
  5470. breaking ties randomly
  5471. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5472. |$\mathrm{color}[u] \gets c$|
  5473. |$W \gets W - \{u\}$|
  5474. \end{lstlisting}
  5475. \end{tcolorbox}
  5476. \caption{The saturation-based greedy graph coloring algorithm.}
  5477. \label{fig:satur-algo}
  5478. \end{figure}
  5479. {\if\edition\racketEd
  5480. With the DSATUR algorithm in hand, let us return to the running
  5481. example and consider how to color the interference graph shown in
  5482. figure~\ref{fig:interfere}.
  5483. %
  5484. We start by assigning each register node to its own color. For
  5485. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  5486. assigned $-2$. The variables are not yet colored, so they are
  5487. annotated with a dash. We then update the saturation for vertices that
  5488. are adjacent to a register, obtaining the following annotated
  5489. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  5490. it interferes with both \code{rax} and \code{rsp}.
  5491. \[
  5492. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5493. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5494. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5495. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5496. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5497. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5498. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5499. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5500. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5501. \draw (t1) to (rax);
  5502. \draw (t1) to (z);
  5503. \draw (z) to (y);
  5504. \draw (z) to (w);
  5505. \draw (x) to (w);
  5506. \draw (y) to (w);
  5507. \draw (v) to (w);
  5508. \draw (v) to (rsp);
  5509. \draw (w) to (rsp);
  5510. \draw (x) to (rsp);
  5511. \draw (y) to (rsp);
  5512. \path[-.,bend left=15] (z) edge node {} (rsp);
  5513. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5514. \draw (rax) to (rsp);
  5515. \end{tikzpicture}
  5516. \]
  5517. The algorithm says to select a maximally saturated vertex. So, we pick
  5518. $\ttm{t}$ and color it with the first available integer, which is
  5519. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5520. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5521. \[
  5522. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5523. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5524. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5525. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5526. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5527. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5528. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5529. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5530. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5531. \draw (t1) to (rax);
  5532. \draw (t1) to (z);
  5533. \draw (z) to (y);
  5534. \draw (z) to (w);
  5535. \draw (x) to (w);
  5536. \draw (y) to (w);
  5537. \draw (v) to (w);
  5538. \draw (v) to (rsp);
  5539. \draw (w) to (rsp);
  5540. \draw (x) to (rsp);
  5541. \draw (y) to (rsp);
  5542. \path[-.,bend left=15] (z) edge node {} (rsp);
  5543. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5544. \draw (rax) to (rsp);
  5545. \end{tikzpicture}
  5546. \]
  5547. We repeat the process, selecting a maximally saturated vertex,
  5548. choosing \code{z}, and coloring it with the first available number, which
  5549. is $1$. We add $1$ to the saturation for the neighboring vertices
  5550. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5551. \[
  5552. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5553. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5554. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5555. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5556. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5557. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5558. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5559. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5560. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5561. \draw (t1) to (rax);
  5562. \draw (t1) to (z);
  5563. \draw (z) to (y);
  5564. \draw (z) to (w);
  5565. \draw (x) to (w);
  5566. \draw (y) to (w);
  5567. \draw (v) to (w);
  5568. \draw (v) to (rsp);
  5569. \draw (w) to (rsp);
  5570. \draw (x) to (rsp);
  5571. \draw (y) to (rsp);
  5572. \path[-.,bend left=15] (z) edge node {} (rsp);
  5573. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5574. \draw (rax) to (rsp);
  5575. \end{tikzpicture}
  5576. \]
  5577. The most saturated vertices are now \code{w} and \code{y}. We color
  5578. \code{w} with the first available color, which is $0$.
  5579. \[
  5580. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5581. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5582. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5583. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5584. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5585. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5586. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5587. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5588. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5589. \draw (t1) to (rax);
  5590. \draw (t1) to (z);
  5591. \draw (z) to (y);
  5592. \draw (z) to (w);
  5593. \draw (x) to (w);
  5594. \draw (y) to (w);
  5595. \draw (v) to (w);
  5596. \draw (v) to (rsp);
  5597. \draw (w) to (rsp);
  5598. \draw (x) to (rsp);
  5599. \draw (y) to (rsp);
  5600. \path[-.,bend left=15] (z) edge node {} (rsp);
  5601. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5602. \draw (rax) to (rsp);
  5603. \end{tikzpicture}
  5604. \]
  5605. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5606. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5607. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5608. and \code{z}, whose colors are $0$ and $1$ respectively.
  5609. \[
  5610. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5611. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5612. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5613. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5614. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5615. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5616. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5617. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5618. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5619. \draw (t1) to (rax);
  5620. \draw (t1) to (z);
  5621. \draw (z) to (y);
  5622. \draw (z) to (w);
  5623. \draw (x) to (w);
  5624. \draw (y) to (w);
  5625. \draw (v) to (w);
  5626. \draw (v) to (rsp);
  5627. \draw (w) to (rsp);
  5628. \draw (x) to (rsp);
  5629. \draw (y) to (rsp);
  5630. \path[-.,bend left=15] (z) edge node {} (rsp);
  5631. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5632. \draw (rax) to (rsp);
  5633. \end{tikzpicture}
  5634. \]
  5635. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5636. \[
  5637. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5638. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5639. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5640. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5641. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5642. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5643. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5644. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5645. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5646. \draw (t1) to (rax);
  5647. \draw (t1) to (z);
  5648. \draw (z) to (y);
  5649. \draw (z) to (w);
  5650. \draw (x) to (w);
  5651. \draw (y) to (w);
  5652. \draw (v) to (w);
  5653. \draw (v) to (rsp);
  5654. \draw (w) to (rsp);
  5655. \draw (x) to (rsp);
  5656. \draw (y) to (rsp);
  5657. \path[-.,bend left=15] (z) edge node {} (rsp);
  5658. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5659. \draw (rax) to (rsp);
  5660. \end{tikzpicture}
  5661. \]
  5662. In the last step of the algorithm, we color \code{x} with $1$.
  5663. \[
  5664. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5665. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5666. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5667. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5668. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5669. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5670. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5671. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5672. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5673. \draw (t1) to (rax);
  5674. \draw (t1) to (z);
  5675. \draw (z) to (y);
  5676. \draw (z) to (w);
  5677. \draw (x) to (w);
  5678. \draw (y) to (w);
  5679. \draw (v) to (w);
  5680. \draw (v) to (rsp);
  5681. \draw (w) to (rsp);
  5682. \draw (x) to (rsp);
  5683. \draw (y) to (rsp);
  5684. \path[-.,bend left=15] (z) edge node {} (rsp);
  5685. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5686. \draw (rax) to (rsp);
  5687. \end{tikzpicture}
  5688. \]
  5689. So, we obtain the following coloring:
  5690. \[
  5691. \{
  5692. \ttm{rax} \mapsto -1,
  5693. \ttm{rsp} \mapsto -2,
  5694. \ttm{t} \mapsto 0,
  5695. \ttm{z} \mapsto 1,
  5696. \ttm{x} \mapsto 1,
  5697. \ttm{y} \mapsto 2,
  5698. \ttm{w} \mapsto 0,
  5699. \ttm{v} \mapsto 1
  5700. \}
  5701. \]
  5702. \fi}
  5703. %
  5704. {\if\edition\pythonEd
  5705. %
  5706. With the DSATUR algorithm in hand, let us return to the running
  5707. example and consider how to color the interference graph in
  5708. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5709. to indicate that it has not yet been assigned a color. The saturation
  5710. sets are also shown for each node; all of them start as the empty set.
  5711. (We do not include the register nodes in the graph below because there
  5712. were no interference edges involving registers in this program, but in
  5713. general there can be.)
  5714. %
  5715. \[
  5716. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5717. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5718. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5719. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5720. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5721. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5722. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5723. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5724. \draw (t0) to (t1);
  5725. \draw (t0) to (z);
  5726. \draw (z) to (y);
  5727. \draw (z) to (w);
  5728. \draw (x) to (w);
  5729. \draw (y) to (w);
  5730. \draw (v) to (w);
  5731. \end{tikzpicture}
  5732. \]
  5733. The algorithm says to select a maximally saturated vertex, but they
  5734. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5735. then color it with the first available integer, which is $0$. We mark
  5736. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5737. they interfere with $\ttm{tmp\_0}$.
  5738. \[
  5739. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5740. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5741. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5742. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5743. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5744. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5745. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5746. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5747. \draw (t0) to (t1);
  5748. \draw (t0) to (z);
  5749. \draw (z) to (y);
  5750. \draw (z) to (w);
  5751. \draw (x) to (w);
  5752. \draw (y) to (w);
  5753. \draw (v) to (w);
  5754. \end{tikzpicture}
  5755. \]
  5756. We repeat the process. The most saturated vertices are \code{z} and
  5757. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5758. available number, which is $1$. We add $1$ to the saturation for the
  5759. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5760. \[
  5761. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5762. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5763. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5764. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5765. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5766. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5767. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5768. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5769. \draw (t0) to (t1);
  5770. \draw (t0) to (z);
  5771. \draw (z) to (y);
  5772. \draw (z) to (w);
  5773. \draw (x) to (w);
  5774. \draw (y) to (w);
  5775. \draw (v) to (w);
  5776. \end{tikzpicture}
  5777. \]
  5778. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5779. \code{y}. We color \code{w} with the first available color, which
  5780. is $0$.
  5781. \[
  5782. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5783. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5784. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5785. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5786. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5787. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5788. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5789. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5790. \draw (t0) to (t1);
  5791. \draw (t0) 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. \end{tikzpicture}
  5798. \]
  5799. Now \code{y} is the most saturated, so we color it with $2$.
  5800. \[
  5801. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5802. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5803. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5804. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5805. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5806. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5807. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5808. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5809. \draw (t0) to (t1);
  5810. \draw (t0) to (z);
  5811. \draw (z) to (y);
  5812. \draw (z) to (w);
  5813. \draw (x) to (w);
  5814. \draw (y) to (w);
  5815. \draw (v) to (w);
  5816. \end{tikzpicture}
  5817. \]
  5818. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5819. We choose to color \code{v} with $1$.
  5820. \[
  5821. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5822. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5823. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5824. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5825. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5826. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5827. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5828. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5829. \draw (t0) to (t1);
  5830. \draw (t0) to (z);
  5831. \draw (z) to (y);
  5832. \draw (z) to (w);
  5833. \draw (x) to (w);
  5834. \draw (y) to (w);
  5835. \draw (v) to (w);
  5836. \end{tikzpicture}
  5837. \]
  5838. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5839. \[
  5840. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5841. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5842. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5843. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5844. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5845. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5846. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5847. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5848. \draw (t0) to (t1);
  5849. \draw (t0) to (z);
  5850. \draw (z) to (y);
  5851. \draw (z) to (w);
  5852. \draw (x) to (w);
  5853. \draw (y) to (w);
  5854. \draw (v) to (w);
  5855. \end{tikzpicture}
  5856. \]
  5857. So, we obtain the following coloring:
  5858. \[
  5859. \{ \ttm{tmp\_0} \mapsto 0,
  5860. \ttm{tmp\_1} \mapsto 1,
  5861. \ttm{z} \mapsto 1,
  5862. \ttm{x} \mapsto 1,
  5863. \ttm{y} \mapsto 2,
  5864. \ttm{w} \mapsto 0,
  5865. \ttm{v} \mapsto 1 \}
  5866. \]
  5867. \fi}
  5868. We recommend creating an auxiliary function named \code{color\_graph}
  5869. that takes an interference graph and a list of all the variables in
  5870. the program. This function should return a mapping of variables to
  5871. their colors (represented as natural numbers). By creating this helper
  5872. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5873. when we add support for functions.
  5874. To prioritize the processing of highly saturated nodes inside the
  5875. \code{color\_graph} function, we recommend using the priority queue
  5876. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5877. addition, you will need to maintain a mapping from variables to their
  5878. handles in the priority queue so that you can notify the priority
  5879. queue when their saturation changes.}
  5880. {\if\edition\racketEd
  5881. \begin{figure}[tp]
  5882. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5883. \small
  5884. \begin{tcolorbox}[title=Priority Queue]
  5885. A \emph{priority queue} is a collection of items in which the
  5886. removal of items is governed by priority. In a min queue,
  5887. lower priority items are removed first. An implementation is in
  5888. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5889. queue} \index{subject}{minimum priority queue}
  5890. \begin{description}
  5891. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5892. priority queue that uses the $\itm{cmp}$ predicate to determine
  5893. whether its first argument has lower or equal priority to its
  5894. second argument.
  5895. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5896. items in the queue.
  5897. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5898. the item into the queue and returns a handle for the item in the
  5899. queue.
  5900. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5901. the lowest priority.
  5902. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5903. notifies the queue that the priority has decreased for the item
  5904. associated with the given handle.
  5905. \end{description}
  5906. \end{tcolorbox}
  5907. %\end{wrapfigure}
  5908. \caption{The priority queue data structure.}
  5909. \label{fig:priority-queue}
  5910. \end{figure}
  5911. \fi}
  5912. With the coloring complete, we finalize the assignment of variables to
  5913. registers and stack locations. We map the first $k$ colors to the $k$
  5914. registers and the rest of the colors to stack locations. Suppose for
  5915. the moment that we have just one register to use for register
  5916. allocation, \key{rcx}. Then we have the following map from colors to
  5917. locations.
  5918. \[
  5919. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5920. \]
  5921. Composing this mapping with the coloring, we arrive at the following
  5922. assignment of variables to locations.
  5923. {\if\edition\racketEd
  5924. \begin{gather*}
  5925. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5926. \ttm{w} \mapsto \key{\%rcx}, \,
  5927. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5928. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5929. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5930. \ttm{t} \mapsto \key{\%rcx} \}
  5931. \end{gather*}
  5932. \fi}
  5933. {\if\edition\pythonEd
  5934. \begin{gather*}
  5935. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5936. \ttm{w} \mapsto \key{\%rcx}, \,
  5937. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5938. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5939. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5940. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5941. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5942. \end{gather*}
  5943. \fi}
  5944. Adapt the code from the \code{assign\_homes} pass
  5945. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5946. assigned location. Applying this assignment to our running
  5947. example shown next, on the left, yields the program on the right.
  5948. % why frame size of 32? -JGS
  5949. \begin{center}
  5950. {\if\edition\racketEd
  5951. \begin{minipage}{0.3\textwidth}
  5952. \begin{lstlisting}
  5953. movq $1, v
  5954. movq $42, w
  5955. movq v, x
  5956. addq $7, x
  5957. movq x, y
  5958. movq x, z
  5959. addq w, z
  5960. movq y, t
  5961. negq t
  5962. movq z, %rax
  5963. addq t, %rax
  5964. jmp conclusion
  5965. \end{lstlisting}
  5966. \end{minipage}
  5967. $\Rightarrow\qquad$
  5968. \begin{minipage}{0.45\textwidth}
  5969. \begin{lstlisting}
  5970. movq $1, -8(%rbp)
  5971. movq $42, %rcx
  5972. movq -8(%rbp), -8(%rbp)
  5973. addq $7, -8(%rbp)
  5974. movq -8(%rbp), -16(%rbp)
  5975. movq -8(%rbp), -8(%rbp)
  5976. addq %rcx, -8(%rbp)
  5977. movq -16(%rbp), %rcx
  5978. negq %rcx
  5979. movq -8(%rbp), %rax
  5980. addq %rcx, %rax
  5981. jmp conclusion
  5982. \end{lstlisting}
  5983. \end{minipage}
  5984. \fi}
  5985. {\if\edition\pythonEd
  5986. \begin{minipage}{0.3\textwidth}
  5987. \begin{lstlisting}
  5988. movq $1, v
  5989. movq $42, w
  5990. movq v, x
  5991. addq $7, x
  5992. movq x, y
  5993. movq x, z
  5994. addq w, z
  5995. movq y, tmp_0
  5996. negq tmp_0
  5997. movq z, tmp_1
  5998. addq tmp_0, tmp_1
  5999. movq tmp_1, %rdi
  6000. callq print_int
  6001. \end{lstlisting}
  6002. \end{minipage}
  6003. $\Rightarrow\qquad$
  6004. \begin{minipage}{0.45\textwidth}
  6005. \begin{lstlisting}
  6006. movq $1, -8(%rbp)
  6007. movq $42, %rcx
  6008. movq -8(%rbp), -8(%rbp)
  6009. addq $7, -8(%rbp)
  6010. movq -8(%rbp), -16(%rbp)
  6011. movq -8(%rbp), -8(%rbp)
  6012. addq %rcx, -8(%rbp)
  6013. movq -16(%rbp), %rcx
  6014. negq %rcx
  6015. movq -8(%rbp), -8(%rbp)
  6016. addq %rcx, -8(%rbp)
  6017. movq -8(%rbp), %rdi
  6018. callq print_int
  6019. \end{lstlisting}
  6020. \end{minipage}
  6021. \fi}
  6022. \end{center}
  6023. \begin{exercise}\normalfont\normalsize
  6024. Implement the \code{allocate\_registers} pass.
  6025. Create five programs that exercise all aspects of the register
  6026. allocation algorithm, including spilling variables to the stack.
  6027. %
  6028. {\if\edition\racketEd
  6029. Replace \code{assign\_homes} in the list of \code{passes} in the
  6030. \code{run-tests.rkt} script with the three new passes:
  6031. \code{uncover\_live}, \code{build\_interference}, and
  6032. \code{allocate\_registers}.
  6033. Temporarily remove the call to \code{compiler-tests}.
  6034. Run the script to test the register allocator.
  6035. \fi}
  6036. %
  6037. {\if\edition\pythonEd
  6038. Run the \code{run-tests.py} script to to check whether the
  6039. output programs produce the same result as the input programs.
  6040. \fi}
  6041. \end{exercise}
  6042. \section{Patch Instructions}
  6043. \label{sec:patch-instructions}
  6044. The remaining step in the compilation to x86 is to ensure that the
  6045. instructions have at most one argument that is a memory access.
  6046. %
  6047. In the running example, the instruction \code{movq -8(\%rbp),
  6048. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6049. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6050. then move \code{rax} into \code{-16(\%rbp)}.
  6051. %
  6052. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6053. problematic, but they can simply be deleted. In general, we recommend
  6054. deleting all the trivial moves whose source and destination are the
  6055. same location.
  6056. %
  6057. The following is the output of \code{patch\_instructions} on the
  6058. running example.
  6059. \begin{center}
  6060. {\if\edition\racketEd
  6061. \begin{minipage}{0.4\textwidth}
  6062. \begin{lstlisting}
  6063. movq $1, -8(%rbp)
  6064. movq $42, %rcx
  6065. movq -8(%rbp), -8(%rbp)
  6066. addq $7, -8(%rbp)
  6067. movq -8(%rbp), -16(%rbp)
  6068. movq -8(%rbp), -8(%rbp)
  6069. addq %rcx, -8(%rbp)
  6070. movq -16(%rbp), %rcx
  6071. negq %rcx
  6072. movq -8(%rbp), %rax
  6073. addq %rcx, %rax
  6074. jmp conclusion
  6075. \end{lstlisting}
  6076. \end{minipage}
  6077. $\Rightarrow\qquad$
  6078. \begin{minipage}{0.45\textwidth}
  6079. \begin{lstlisting}
  6080. movq $1, -8(%rbp)
  6081. movq $42, %rcx
  6082. addq $7, -8(%rbp)
  6083. movq -8(%rbp), %rax
  6084. movq %rax, -16(%rbp)
  6085. addq %rcx, -8(%rbp)
  6086. movq -16(%rbp), %rcx
  6087. negq %rcx
  6088. movq -8(%rbp), %rax
  6089. addq %rcx, %rax
  6090. jmp conclusion
  6091. \end{lstlisting}
  6092. \end{minipage}
  6093. \fi}
  6094. {\if\edition\pythonEd
  6095. \begin{minipage}{0.4\textwidth}
  6096. \begin{lstlisting}
  6097. movq $1, -8(%rbp)
  6098. movq $42, %rcx
  6099. movq -8(%rbp), -8(%rbp)
  6100. addq $7, -8(%rbp)
  6101. movq -8(%rbp), -16(%rbp)
  6102. movq -8(%rbp), -8(%rbp)
  6103. addq %rcx, -8(%rbp)
  6104. movq -16(%rbp), %rcx
  6105. negq %rcx
  6106. movq -8(%rbp), -8(%rbp)
  6107. addq %rcx, -8(%rbp)
  6108. movq -8(%rbp), %rdi
  6109. callq print_int
  6110. \end{lstlisting}
  6111. \end{minipage}
  6112. $\Rightarrow\qquad$
  6113. \begin{minipage}{0.45\textwidth}
  6114. \begin{lstlisting}
  6115. movq $1, -8(%rbp)
  6116. movq $42, %rcx
  6117. addq $7, -8(%rbp)
  6118. movq -8(%rbp), %rax
  6119. movq %rax, -16(%rbp)
  6120. addq %rcx, -8(%rbp)
  6121. movq -16(%rbp), %rcx
  6122. negq %rcx
  6123. addq %rcx, -8(%rbp)
  6124. movq -8(%rbp), %rdi
  6125. callq print_int
  6126. \end{lstlisting}
  6127. \end{minipage}
  6128. \fi}
  6129. \end{center}
  6130. \begin{exercise}\normalfont\normalsize
  6131. %
  6132. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6133. %
  6134. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6135. %in the \code{run-tests.rkt} script.
  6136. %
  6137. Run the script to test the \code{patch\_instructions} pass.
  6138. \end{exercise}
  6139. \section{Prelude and Conclusion}
  6140. \label{sec:print-x86-reg-alloc}
  6141. \index{subject}{calling conventions}
  6142. \index{subject}{prelude}\index{subject}{conclusion}
  6143. Recall that this pass generates the prelude and conclusion
  6144. instructions to satisfy the x86 calling conventions
  6145. (section~\ref{sec:calling-conventions}). With the addition of the
  6146. register allocator, the callee-saved registers used by the register
  6147. allocator must be saved in the prelude and restored in the conclusion.
  6148. In the \code{allocate\_registers} pass,
  6149. %
  6150. \racket{add an entry to the \itm{info}
  6151. of \code{X86Program} named \code{used\_callee}}
  6152. %
  6153. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6154. %
  6155. that stores the set of callee-saved registers that were assigned to
  6156. variables. The \code{prelude\_and\_conclusion} pass can then access
  6157. this information to decide which callee-saved registers need to be
  6158. saved and restored.
  6159. %
  6160. When calculating the amount to adjust the \code{rsp} in the prelude,
  6161. make sure to take into account the space used for saving the
  6162. callee-saved registers. Also, remember that the frame needs to be a
  6163. multiple of 16 bytes! We recommend using the following equation for
  6164. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6165. of spilled variables and $C$ be the number of callee-saved registers
  6166. that were allocated to variables. The $\itm{align}$ function rounds a
  6167. number up to the nearest 16 bytes.
  6168. \[
  6169. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6170. \]
  6171. The reason we subtract $8\itm{C}$ in this equation is that the
  6172. prelude uses \code{pushq} to save each of the callee-saved registers,
  6173. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6174. \racket{An overview of all the passes involved in register
  6175. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6176. {\if\edition\racketEd
  6177. \begin{figure}[tbp]
  6178. \begin{tcolorbox}[colback=white]
  6179. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6180. \node (Lvar) at (0,2) {\large \LangVar{}};
  6181. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6182. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6183. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6184. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6185. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6186. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6187. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6188. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6189. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6190. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6191. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6192. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  6193. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6194. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6195. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6196. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6197. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6198. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6199. \end{tikzpicture}
  6200. \end{tcolorbox}
  6201. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6202. \label{fig:reg-alloc-passes}
  6203. \end{figure}
  6204. \fi}
  6205. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6206. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6207. use of registers and the stack, we limit the register allocator for
  6208. this example to use just two registers: \code{rbx} and \code{rcx}. In
  6209. the prelude\index{subject}{prelude} of the \code{main} function, we
  6210. push \code{rbx} onto the stack because it is a callee-saved register
  6211. and it was assigned to a variable by the register allocator. We
  6212. subtract \code{8} from the \code{rsp} at the end of the prelude to
  6213. reserve space for the one spilled variable. After that subtraction,
  6214. the \code{rsp} is aligned to 16 bytes.
  6215. Moving on to the program proper, we see how the registers were
  6216. allocated.
  6217. %
  6218. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  6219. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  6220. %
  6221. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6222. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  6223. were assigned to \code{rbx}.}
  6224. %
  6225. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  6226. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6227. callee-save register \code{rbx} onto the stack. The spilled variables
  6228. must be placed lower on the stack than the saved callee-save
  6229. registers, so in this case \racket{\code{w}}\python{z} is placed at
  6230. \code{-16(\%rbp)}.
  6231. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6232. done in the prelude. We move the stack pointer up by \code{8} bytes
  6233. (the room for spilled variables), then pop the old values of
  6234. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6235. \code{retq} to return control to the operating system.
  6236. \begin{figure}[tbp]
  6237. \begin{minipage}{0.55\textwidth}
  6238. \begin{tcolorbox}[colback=white]
  6239. % var_test_28.rkt
  6240. % (use-minimal-set-of-registers! #t)
  6241. % and only rbx rcx
  6242. % tmp 0 rbx
  6243. % z 1 rcx
  6244. % y 0 rbx
  6245. % w 2 16(%rbp)
  6246. % v 0 rbx
  6247. % x 0 rbx
  6248. {\if\edition\racketEd
  6249. \begin{lstlisting}
  6250. start:
  6251. movq $1, %rbx
  6252. movq $42, -16(%rbp)
  6253. addq $7, %rbx
  6254. movq %rbx, %rcx
  6255. addq -16(%rbp), %rcx
  6256. negq %rbx
  6257. movq %rcx, %rax
  6258. addq %rbx, %rax
  6259. jmp conclusion
  6260. .globl main
  6261. main:
  6262. pushq %rbp
  6263. movq %rsp, %rbp
  6264. pushq %rbx
  6265. subq $8, %rsp
  6266. jmp start
  6267. conclusion:
  6268. addq $8, %rsp
  6269. popq %rbx
  6270. popq %rbp
  6271. retq
  6272. \end{lstlisting}
  6273. \fi}
  6274. {\if\edition\pythonEd
  6275. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6276. \begin{lstlisting}
  6277. .globl main
  6278. main:
  6279. pushq %rbp
  6280. movq %rsp, %rbp
  6281. pushq %rbx
  6282. subq $8, %rsp
  6283. movq $1, %rcx
  6284. movq $42, %rbx
  6285. addq $7, %rcx
  6286. movq %rcx, -16(%rbp)
  6287. addq %rbx, -16(%rbp)
  6288. negq %rcx
  6289. movq -16(%rbp), %rbx
  6290. addq %rcx, %rbx
  6291. movq %rbx, %rdi
  6292. callq print_int
  6293. addq $8, %rsp
  6294. popq %rbx
  6295. popq %rbp
  6296. retq
  6297. \end{lstlisting}
  6298. \fi}
  6299. \end{tcolorbox}
  6300. \end{minipage}
  6301. \caption{The x86 output from the running example
  6302. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6303. and \code{rcx}.}
  6304. \label{fig:running-example-x86}
  6305. \end{figure}
  6306. \begin{exercise}\normalfont\normalsize
  6307. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6308. %
  6309. \racket{
  6310. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6311. list of passes and the call to \code{compiler-tests}.}
  6312. %
  6313. Run the script to test the complete compiler for \LangVar{} that
  6314. performs register allocation.
  6315. \end{exercise}
  6316. \section{Challenge: Move Biasing}
  6317. \label{sec:move-biasing}
  6318. \index{subject}{move biasing}
  6319. This section describes an enhancement to the register allocator,
  6320. called move biasing, for students who are looking for an extra
  6321. challenge.
  6322. {\if\edition\racketEd
  6323. To motivate the need for move biasing we return to the running example,
  6324. but this time we use all the general purpose registers. So, we have
  6325. the following mapping of color numbers to registers.
  6326. \[
  6327. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6328. \]
  6329. Using the same assignment of variables to color numbers that was
  6330. produced by the register allocator described in the last section, we
  6331. get the following program.
  6332. \begin{center}
  6333. \begin{minipage}{0.3\textwidth}
  6334. \begin{lstlisting}
  6335. movq $1, v
  6336. movq $42, w
  6337. movq v, x
  6338. addq $7, x
  6339. movq x, y
  6340. movq x, z
  6341. addq w, z
  6342. movq y, t
  6343. negq t
  6344. movq z, %rax
  6345. addq t, %rax
  6346. jmp conclusion
  6347. \end{lstlisting}
  6348. \end{minipage}
  6349. $\Rightarrow\qquad$
  6350. \begin{minipage}{0.45\textwidth}
  6351. \begin{lstlisting}
  6352. movq $1, %rdx
  6353. movq $42, %rcx
  6354. movq %rdx, %rdx
  6355. addq $7, %rdx
  6356. movq %rdx, %rsi
  6357. movq %rdx, %rdx
  6358. addq %rcx, %rdx
  6359. movq %rsi, %rcx
  6360. negq %rcx
  6361. movq %rdx, %rax
  6362. addq %rcx, %rax
  6363. jmp conclusion
  6364. \end{lstlisting}
  6365. \end{minipage}
  6366. \end{center}
  6367. In this output code there are two \key{movq} instructions that
  6368. can be removed because their source and target are the same. However,
  6369. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6370. register, we could instead remove three \key{movq} instructions. We
  6371. can accomplish this by taking into account which variables appear in
  6372. \key{movq} instructions with which other variables.
  6373. \fi}
  6374. {\if\edition\pythonEd
  6375. %
  6376. To motivate the need for move biasing we return to the running example
  6377. and recall that in section~\ref{sec:patch-instructions} we were able to
  6378. remove three trivial move instructions from the running
  6379. example. However, we could remove another trivial move if we were able
  6380. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6381. We say that two variables $p$ and $q$ are \emph{move
  6382. related}\index{subject}{move related} if they participate together in
  6383. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6384. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  6385. if there are multiple variables with the same saturation, prefer
  6386. variables that can be assigned to a color that is the same as the
  6387. color of a move-related variable. Furthermore, when the register
  6388. allocator chooses a color for a variable, it should prefer a color
  6389. that has already been used for a move-related variable (assuming that
  6390. they do not interfere). Of course, this preference should not override
  6391. the preference for registers over stack locations. So, this preference
  6392. should be used as a tie breaker in choosing between registers and
  6393. in choosing between stack locations.
  6394. We recommend representing the move relationships in a graph, similarly
  6395. to how we represented interference. The following is the \emph{move
  6396. graph} for our running example.
  6397. {\if\edition\racketEd
  6398. \[
  6399. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6400. \node (rax) at (0,0) {$\ttm{rax}$};
  6401. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6402. \node (t) at (0,2) {$\ttm{t}$};
  6403. \node (z) at (3,2) {$\ttm{z}$};
  6404. \node (x) at (6,2) {$\ttm{x}$};
  6405. \node (y) at (3,0) {$\ttm{y}$};
  6406. \node (w) at (6,0) {$\ttm{w}$};
  6407. \node (v) at (9,0) {$\ttm{v}$};
  6408. \draw (v) to (x);
  6409. \draw (x) to (y);
  6410. \draw (x) to (z);
  6411. \draw (y) to (t);
  6412. \end{tikzpicture}
  6413. \]
  6414. \fi}
  6415. %
  6416. {\if\edition\pythonEd
  6417. \[
  6418. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6419. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6420. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6421. \node (z) at (3,2) {$\ttm{z}$};
  6422. \node (x) at (6,2) {$\ttm{x}$};
  6423. \node (y) at (3,0) {$\ttm{y}$};
  6424. \node (w) at (6,0) {$\ttm{w}$};
  6425. \node (v) at (9,0) {$\ttm{v}$};
  6426. \draw (y) to (t0);
  6427. \draw (z) to (x);
  6428. \draw (z) to (t1);
  6429. \draw (x) to (y);
  6430. \draw (x) to (v);
  6431. \end{tikzpicture}
  6432. \]
  6433. \fi}
  6434. {\if\edition\racketEd
  6435. Now we replay the graph coloring, pausing to see the coloring of
  6436. \code{y}. Recall the following configuration. The most saturated vertices
  6437. were \code{w} and \code{y}.
  6438. \[
  6439. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6440. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6441. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6442. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6443. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6444. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6445. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6446. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6447. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6448. \draw (t1) to (rax);
  6449. \draw (t1) to (z);
  6450. \draw (z) to (y);
  6451. \draw (z) to (w);
  6452. \draw (x) to (w);
  6453. \draw (y) to (w);
  6454. \draw (v) to (w);
  6455. \draw (v) to (rsp);
  6456. \draw (w) to (rsp);
  6457. \draw (x) to (rsp);
  6458. \draw (y) to (rsp);
  6459. \path[-.,bend left=15] (z) edge node {} (rsp);
  6460. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6461. \draw (rax) to (rsp);
  6462. \end{tikzpicture}
  6463. \]
  6464. %
  6465. The last time, we chose to color \code{w} with $0$. This time, we see
  6466. that \code{w} is not move-related to any vertex, but \code{y} is
  6467. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6468. the same color as \code{t}.
  6469. \[
  6470. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6471. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6472. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6473. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6474. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6475. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6476. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6477. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6478. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6479. \draw (t1) to (rax);
  6480. \draw (t1) to (z);
  6481. \draw (z) to (y);
  6482. \draw (z) to (w);
  6483. \draw (x) to (w);
  6484. \draw (y) to (w);
  6485. \draw (v) to (w);
  6486. \draw (v) to (rsp);
  6487. \draw (w) to (rsp);
  6488. \draw (x) to (rsp);
  6489. \draw (y) to (rsp);
  6490. \path[-.,bend left=15] (z) edge node {} (rsp);
  6491. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6492. \draw (rax) to (rsp);
  6493. \end{tikzpicture}
  6494. \]
  6495. Now \code{w} is the most saturated, so we color it $2$.
  6496. \[
  6497. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6498. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6499. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6500. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6501. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6502. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6503. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6504. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6505. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6506. \draw (t1) to (rax);
  6507. \draw (t1) to (z);
  6508. \draw (z) to (y);
  6509. \draw (z) to (w);
  6510. \draw (x) to (w);
  6511. \draw (y) to (w);
  6512. \draw (v) to (w);
  6513. \draw (v) to (rsp);
  6514. \draw (w) to (rsp);
  6515. \draw (x) to (rsp);
  6516. \draw (y) to (rsp);
  6517. \path[-.,bend left=15] (z) edge node {} (rsp);
  6518. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6519. \draw (rax) to (rsp);
  6520. \end{tikzpicture}
  6521. \]
  6522. At this point, vertices \code{x} and \code{v} are most saturated, but
  6523. \code{x} is move related to \code{y} and \code{z}, so we color
  6524. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6525. \[
  6526. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6527. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6528. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6529. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6530. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6531. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6532. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6533. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6534. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6535. \draw (t1) to (rax);
  6536. \draw (t) to (z);
  6537. \draw (z) to (y);
  6538. \draw (z) to (w);
  6539. \draw (x) to (w);
  6540. \draw (y) to (w);
  6541. \draw (v) to (w);
  6542. \draw (v) to (rsp);
  6543. \draw (w) to (rsp);
  6544. \draw (x) to (rsp);
  6545. \draw (y) to (rsp);
  6546. \path[-.,bend left=15] (z) edge node {} (rsp);
  6547. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6548. \draw (rax) to (rsp);
  6549. \end{tikzpicture}
  6550. \]
  6551. \fi}
  6552. %
  6553. {\if\edition\pythonEd
  6554. Now we replay the graph coloring, pausing before the coloring of
  6555. \code{w}. Recall the following configuration. The most saturated vertices
  6556. were \code{tmp\_1}, \code{w}, and \code{y}.
  6557. \[
  6558. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6559. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6560. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6561. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6562. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6563. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6564. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6565. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6566. \draw (t0) to (t1);
  6567. \draw (t0) to (z);
  6568. \draw (z) to (y);
  6569. \draw (z) to (w);
  6570. \draw (x) to (w);
  6571. \draw (y) to (w);
  6572. \draw (v) to (w);
  6573. \end{tikzpicture}
  6574. \]
  6575. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6576. or \code{y}, but note that \code{w} is not move related to any
  6577. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6578. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6579. \code{y} and color it $0$, we can delete another move instruction.
  6580. \[
  6581. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6582. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6583. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6584. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6585. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6586. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6587. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6588. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6589. \draw (t0) to (t1);
  6590. \draw (t0) to (z);
  6591. \draw (z) to (y);
  6592. \draw (z) to (w);
  6593. \draw (x) to (w);
  6594. \draw (y) to (w);
  6595. \draw (v) to (w);
  6596. \end{tikzpicture}
  6597. \]
  6598. Now \code{w} is the most saturated, so we color it $2$.
  6599. \[
  6600. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6601. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6602. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6603. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6604. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6605. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6606. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6607. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6608. \draw (t0) to (t1);
  6609. \draw (t0) 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. \end{tikzpicture}
  6616. \]
  6617. To finish the coloring, \code{x} and \code{v} get $0$ and
  6618. \code{tmp\_1} gets $1$.
  6619. \[
  6620. \begin{tikzpicture}[baseline=(current bounding box.center)]
  6621. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6622. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6623. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6624. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6625. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6626. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6627. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6628. \draw (t0) to (t1);
  6629. \draw (t0) to (z);
  6630. \draw (z) to (y);
  6631. \draw (z) to (w);
  6632. \draw (x) to (w);
  6633. \draw (y) to (w);
  6634. \draw (v) to (w);
  6635. \end{tikzpicture}
  6636. \]
  6637. \fi}
  6638. So, we have the following assignment of variables to registers.
  6639. {\if\edition\racketEd
  6640. \begin{gather*}
  6641. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6642. \ttm{w} \mapsto \key{\%rsi}, \,
  6643. \ttm{x} \mapsto \key{\%rcx}, \,
  6644. \ttm{y} \mapsto \key{\%rcx}, \,
  6645. \ttm{z} \mapsto \key{\%rdx}, \,
  6646. \ttm{t} \mapsto \key{\%rcx} \}
  6647. \end{gather*}
  6648. \fi}
  6649. {\if\edition\pythonEd
  6650. \begin{gather*}
  6651. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6652. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6653. \ttm{x} \mapsto \key{\%rcx}, \,
  6654. \ttm{y} \mapsto \key{\%rcx}, \\
  6655. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6656. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6657. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6658. \end{gather*}
  6659. \fi}
  6660. %
  6661. We apply this register assignment to the running example shown next,
  6662. on the left, to obtain the code in the middle. The
  6663. \code{patch\_instructions} then deletes the trivial moves to obtain
  6664. the code on the right.
  6665. {\if\edition\racketEd
  6666. \begin{minipage}{0.25\textwidth}
  6667. \begin{lstlisting}
  6668. movq $1, v
  6669. movq $42, w
  6670. movq v, x
  6671. addq $7, x
  6672. movq x, y
  6673. movq x, z
  6674. addq w, z
  6675. movq y, t
  6676. negq t
  6677. movq z, %rax
  6678. addq t, %rax
  6679. jmp conclusion
  6680. \end{lstlisting}
  6681. \end{minipage}
  6682. $\Rightarrow\qquad$
  6683. \begin{minipage}{0.25\textwidth}
  6684. \begin{lstlisting}
  6685. movq $1, %rcx
  6686. movq $42, %rsi
  6687. movq %rcx, %rcx
  6688. addq $7, %rcx
  6689. movq %rcx, %rcx
  6690. movq %rcx, %rdx
  6691. addq %rsi, %rdx
  6692. movq %rcx, %rcx
  6693. negq %rcx
  6694. movq %rdx, %rax
  6695. addq %rcx, %rax
  6696. jmp conclusion
  6697. \end{lstlisting}
  6698. \end{minipage}
  6699. $\Rightarrow\qquad$
  6700. \begin{minipage}{0.25\textwidth}
  6701. \begin{lstlisting}
  6702. movq $1, %rcx
  6703. movq $42, %rsi
  6704. addq $7, %rcx
  6705. movq %rcx, %rdx
  6706. addq %rsi, %rdx
  6707. negq %rcx
  6708. movq %rdx, %rax
  6709. addq %rcx, %rax
  6710. jmp conclusion
  6711. \end{lstlisting}
  6712. \end{minipage}
  6713. \fi}
  6714. {\if\edition\pythonEd
  6715. \begin{minipage}{0.20\textwidth}
  6716. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6717. movq $1, v
  6718. movq $42, w
  6719. movq v, x
  6720. addq $7, x
  6721. movq x, y
  6722. movq x, z
  6723. addq w, z
  6724. movq y, tmp_0
  6725. negq tmp_0
  6726. movq z, tmp_1
  6727. addq tmp_0, tmp_1
  6728. movq tmp_1, %rdi
  6729. callq _print_int
  6730. \end{lstlisting}
  6731. \end{minipage}
  6732. ${\Rightarrow\qquad}$
  6733. \begin{minipage}{0.30\textwidth}
  6734. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6735. movq $1, %rcx
  6736. movq $42, -16(%rbp)
  6737. movq %rcx, %rcx
  6738. addq $7, %rcx
  6739. movq %rcx, %rcx
  6740. movq %rcx, -8(%rbp)
  6741. addq -16(%rbp), -8(%rbp)
  6742. movq %rcx, %rcx
  6743. negq %rcx
  6744. movq -8(%rbp), -8(%rbp)
  6745. addq %rcx, -8(%rbp)
  6746. movq -8(%rbp), %rdi
  6747. callq _print_int
  6748. \end{lstlisting}
  6749. \end{minipage}
  6750. ${\Rightarrow\qquad}$
  6751. \begin{minipage}{0.20\textwidth}
  6752. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6753. movq $1, %rcx
  6754. movq $42, -16(%rbp)
  6755. addq $7, %rcx
  6756. movq %rcx, -8(%rbp)
  6757. movq -16(%rbp), %rax
  6758. addq %rax, -8(%rbp)
  6759. negq %rcx
  6760. addq %rcx, -8(%rbp)
  6761. movq -8(%rbp), %rdi
  6762. callq print_int
  6763. \end{lstlisting}
  6764. \end{minipage}
  6765. \fi}
  6766. \begin{exercise}\normalfont\normalsize
  6767. Change your implementation of \code{allocate\_registers} to take move
  6768. biasing into account. Create two new tests that include at least one
  6769. opportunity for move biasing, and visually inspect the output x86
  6770. programs to make sure that your move biasing is working properly. Make
  6771. sure that your compiler still passes all the tests.
  6772. \end{exercise}
  6773. %To do: another neat challenge would be to do
  6774. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6775. %% \subsection{Output of the Running Example}
  6776. %% \label{sec:reg-alloc-output}
  6777. % challenge: prioritize variables based on execution frequencies
  6778. % and the number of uses of a variable
  6779. % challenge: enhance the coloring algorithm using Chaitin's
  6780. % approach of prioritizing high-degree variables
  6781. % by removing low-degree variables (coloring them later)
  6782. % from the interference graph
  6783. \section{Further Reading}
  6784. \label{sec:register-allocation-further-reading}
  6785. Early register allocation algorithms were developed for Fortran
  6786. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6787. of graph coloring began in the late 1970s and early 1980s with the
  6788. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6789. algorithm is based on the following observation of
  6790. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6791. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6792. $v$ removed is also $k$ colorable. To see why, suppose that the
  6793. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6794. different colors, but because there are fewer than $k$ neighbors, there
  6795. will be one or more colors left over to use for coloring $v$ in $G$.
  6796. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6797. less than $k$ from the graph and recursively colors the rest of the
  6798. graph. Upon returning from the recursion, it colors $v$ with one of
  6799. the available colors and returns. \citet{Chaitin:1982vn} augments
  6800. this algorithm to handle spilling as follows. If there are no vertices
  6801. of degree lower than $k$ then pick a vertex at random, spill it,
  6802. remove it from the graph, and proceed recursively to color the rest of
  6803. the graph.
  6804. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6805. move-related and that don't interfere with each other, in a process
  6806. called \emph{coalescing}. Although coalescing decreases the number of
  6807. moves, it can make the graph more difficult to
  6808. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6809. which two variables are merged only if they have fewer than $k$
  6810. neighbors of high degree. \citet{George:1996aa} observed that
  6811. conservative coalescing is sometimes too conservative and made it more
  6812. aggressive by iterating the coalescing with the removal of low-degree
  6813. vertices.
  6814. %
  6815. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6816. also proposed \emph{biased coloring}, in which a variable is assigned to
  6817. the same color as another move-related variable if possible, as
  6818. discussed in section~\ref{sec:move-biasing}.
  6819. %
  6820. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6821. performs coalescing, graph coloring, and spill code insertion until
  6822. all variables have been assigned a location.
  6823. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6824. spilled variables that don't have to be: a high-degree variable can be
  6825. colorable if many of its neighbors are assigned the same color.
  6826. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6827. high-degree vertex is not immediately spilled. Instead the decision is
  6828. deferred until after the recursive call, at which point it is apparent
  6829. whether there is actually an available color or not. We observe that
  6830. this algorithm is equivalent to the smallest-last ordering
  6831. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6832. be registers and the rest to be stack locations.
  6833. %% biased coloring
  6834. Earlier editions of the compiler course at Indiana University
  6835. \citep{Dybvig:2010aa} were based on the algorithm of
  6836. \citet{Briggs:1994kx}.
  6837. The smallest-last ordering algorithm is one of many \emph{greedy}
  6838. coloring algorithms. A greedy coloring algorithm visits all the
  6839. vertices in a particular order and assigns each one the first
  6840. available color. An \emph{offline} greedy algorithm chooses the
  6841. ordering up front, prior to assigning colors. The algorithm of
  6842. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6843. ordering does not depend on the colors assigned. Other orderings are
  6844. possible. For example, \citet{Chow:1984ys} ordered variables according
  6845. to an estimate of runtime cost.
  6846. An \emph{online} greedy coloring algorithm uses information about the
  6847. current assignment of colors to influence the order in which the
  6848. remaining vertices are colored. The saturation-based algorithm
  6849. described in this chapter is one such algorithm. We choose to use
  6850. saturation-based coloring because it is fun to introduce graph
  6851. coloring via sudoku!
  6852. A register allocator may choose to map each variable to just one
  6853. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6854. variable to one or more locations. The latter can be achieved by
  6855. \emph{live range splitting}, where a variable is replaced by several
  6856. variables that each handle part of its live
  6857. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6858. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6859. %% replacement algorithm, bottom-up local
  6860. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6861. %% Cooper: top-down (priority bassed), bottom-up
  6862. %% top-down
  6863. %% order variables by priority (estimated cost)
  6864. %% caveat: split variables into two groups:
  6865. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6866. %% color the constrained ones first
  6867. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6868. %% cite J. Cocke for an algorithm that colors variables
  6869. %% in a high-degree first ordering
  6870. %Register Allocation via Usage Counts, Freiburghouse CACM
  6871. \citet{Palsberg:2007si} observed that many of the interference graphs
  6872. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6873. that is, every cycle with four or more edges has an edge that is not
  6874. part of the cycle but that connects two vertices on the cycle. Such
  6875. graphs can be optimally colored by the greedy algorithm with a vertex
  6876. ordering determined by maximum cardinality search.
  6877. In situations in which compile time is of utmost importance, such as
  6878. in just-in-time compilers, graph coloring algorithms can be too
  6879. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6880. be more appropriate.
  6881. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6882. \chapter{Booleans and Conditionals}
  6883. \label{ch:Lif}
  6884. \index{subject}{Boolean}
  6885. \index{subject}{control flow}
  6886. \index{subject}{conditional expression}
  6887. \setcounter{footnote}{0}
  6888. The \LangVar{} language has only a single kind of value, the
  6889. integers. In this chapter we add a second kind of value, the Booleans,
  6890. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6891. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6892. and \FALSE{}, respectively. The \LangIf{} language includes several
  6893. operations that involve Booleans (\key{and}, \key{not},
  6894. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6895. expression \python{and statement}. With the addition of \key{if},
  6896. programs can have nontrivial control flow which
  6897. %
  6898. \racket{impacts \code{explicate\_control} and liveness analysis}
  6899. %
  6900. \python{impacts liveness analysis and motivates a new pass named
  6901. \code{explicate\_control}}.
  6902. %
  6903. Also, because we now have two kinds of values, we need to handle
  6904. programs that apply an operation to the wrong kind of value, such as
  6905. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6906. There are two language design options for such situations. One option
  6907. is to signal an error and the other is to provide a wider
  6908. interpretation of the operation. \racket{The Racket
  6909. language}\python{Python} uses a mixture of these two options,
  6910. depending on the operation and the kind of value. For example, the
  6911. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6912. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6913. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6914. %
  6915. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6916. in Racket because \code{car} expects a pair.}
  6917. %
  6918. \python{On the other hand, \code{1[0]} results in a runtime error
  6919. in Python because an ``\code{int} object is not subscriptable''.}
  6920. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6921. design choices as \racket{Racket}\python{Python}, except that much of the
  6922. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6923. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6924. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6925. \python{MyPy} reports a compile-time error
  6926. %
  6927. \racket{because Racket expects the type of the argument to be of the form
  6928. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6929. %
  6930. \python{stating that a ``value of type \code{int} is not indexable''.}
  6931. The \LangIf{} language performs type checking during compilation just as
  6932. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6933. the alternative choice, that is, a dynamically typed language like
  6934. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6935. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6936. restrictive, for example, rejecting \racket{\code{(not
  6937. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6938. fairly simple because the focus of this book is on compilation and not
  6939. type systems, about which there are already several excellent
  6940. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6941. This chapter is organized as follows. We begin by defining the syntax
  6942. and interpreter for the \LangIf{} language
  6943. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6944. checking and define a type checker for \LangIf{}
  6945. (section~\ref{sec:type-check-Lif}).
  6946. %
  6947. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6948. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6949. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6950. %
  6951. The remaining sections of this chapter discuss how Booleans and
  6952. conditional control flow require changes to the existing compiler
  6953. passes and the addition of new ones. We introduce the \code{shrink}
  6954. pass to translate some operators into others, thereby reducing the
  6955. number of operators that need to be handled in later passes.
  6956. %
  6957. The main event of this chapter is the \code{explicate\_control} pass
  6958. that is responsible for translating \code{if}s into conditional
  6959. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6960. %
  6961. Regarding register allocation, there is the interesting question of
  6962. how to handle conditional \code{goto}s during liveness analysis.
  6963. \section{The \LangIf{} Language}
  6964. \label{sec:lang-if}
  6965. Definitions of the concrete syntax and abstract syntax of the
  6966. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6967. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6968. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6969. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6970. %
  6971. \python{, and the \code{if} statement}. We expand the set of
  6972. operators to include
  6973. \begin{enumerate}
  6974. \item the logical operators \key{and}, \key{or}, and \key{not},
  6975. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6976. for comparing integers or Booleans for equality, and
  6977. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6978. comparing integers.
  6979. \end{enumerate}
  6980. \racket{We reorganize the abstract syntax for the primitive
  6981. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6982. rule for all of them. This means that the grammar no longer checks
  6983. whether the arity of an operators matches the number of
  6984. arguments. That responsibility is moved to the type checker for
  6985. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6986. \newcommand{\LifGrammarRacket}{
  6987. \begin{array}{lcl}
  6988. \Type &::=& \key{Boolean} \\
  6989. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6990. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6991. \Exp &::=& \itm{bool}
  6992. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6993. \MID (\key{not}\;\Exp) \\
  6994. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6995. \end{array}
  6996. }
  6997. \newcommand{\LifASTRacket}{
  6998. \begin{array}{lcl}
  6999. \Type &::=& \key{Boolean} \\
  7000. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7001. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7002. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7003. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7004. \end{array}
  7005. }
  7006. \newcommand{\LintOpAST}{
  7007. \begin{array}{rcl}
  7008. \Type &::=& \key{Integer} \\
  7009. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7010. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7011. \end{array}
  7012. }
  7013. \newcommand{\LifGrammarPython}{
  7014. \begin{array}{rcl}
  7015. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7016. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7017. \MID \key{not}~\Exp \\
  7018. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7019. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7020. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7021. \end{array}
  7022. }
  7023. \newcommand{\LifASTPython}{
  7024. \begin{array}{lcl}
  7025. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7026. \itm{unaryop} &::=& \code{Not()} \\
  7027. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7028. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7029. \Exp &::=& \BOOL{\itm{bool}}
  7030. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7031. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7032. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7033. \end{array}
  7034. }
  7035. \begin{figure}[tp]
  7036. \centering
  7037. \begin{tcolorbox}[colback=white]
  7038. {\if\edition\racketEd
  7039. \[
  7040. \begin{array}{l}
  7041. \gray{\LintGrammarRacket{}} \\ \hline
  7042. \gray{\LvarGrammarRacket{}} \\ \hline
  7043. \LifGrammarRacket{} \\
  7044. \begin{array}{lcl}
  7045. \LangIfM{} &::=& \Exp
  7046. \end{array}
  7047. \end{array}
  7048. \]
  7049. \fi}
  7050. {\if\edition\pythonEd
  7051. \[
  7052. \begin{array}{l}
  7053. \gray{\LintGrammarPython} \\ \hline
  7054. \gray{\LvarGrammarPython} \\ \hline
  7055. \LifGrammarPython \\
  7056. \begin{array}{rcl}
  7057. \LangIfM{} &::=& \Stmt^{*}
  7058. \end{array}
  7059. \end{array}
  7060. \]
  7061. \fi}
  7062. \end{tcolorbox}
  7063. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7064. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7065. \label{fig:Lif-concrete-syntax}
  7066. \end{figure}
  7067. \begin{figure}[tp]
  7068. %\begin{minipage}{0.66\textwidth}
  7069. \begin{tcolorbox}[colback=white]
  7070. \centering
  7071. {\if\edition\racketEd
  7072. \[
  7073. \begin{array}{l}
  7074. \gray{\LintOpAST} \\ \hline
  7075. \gray{\LvarASTRacket{}} \\ \hline
  7076. \LifASTRacket{} \\
  7077. \begin{array}{lcl}
  7078. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7079. \end{array}
  7080. \end{array}
  7081. \]
  7082. \fi}
  7083. {\if\edition\pythonEd
  7084. \[
  7085. \begin{array}{l}
  7086. \gray{\LintASTPython} \\ \hline
  7087. \gray{\LvarASTPython} \\ \hline
  7088. \LifASTPython \\
  7089. \begin{array}{lcl}
  7090. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7091. \end{array}
  7092. \end{array}
  7093. \]
  7094. \fi}
  7095. \end{tcolorbox}
  7096. %\end{minipage}
  7097. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  7098. \index{subject}{IfExp@\IFNAME{}}
  7099. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  7100. \index{subject}{and@\ANDNAME{}}
  7101. \index{subject}{or@\ORNAME{}}
  7102. \index{subject}{not@\NOTNAME{}}
  7103. \index{subject}{equal@\EQNAME{}}
  7104. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7105. \racket{
  7106. \index{subject}{lessthan@\texttt{<}}
  7107. \index{subject}{lessthaneq@\texttt{<=}}
  7108. \index{subject}{greaterthan@\texttt{>}}
  7109. \index{subject}{greaterthaneq@\texttt{>=}}
  7110. }
  7111. \python{
  7112. \index{subject}{BoolOp@\texttt{BoolOp}}
  7113. \index{subject}{Compare@\texttt{Compare}}
  7114. \index{subject}{Lt@\texttt{Lt}}
  7115. \index{subject}{LtE@\texttt{LtE}}
  7116. \index{subject}{Gt@\texttt{Gt}}
  7117. \index{subject}{GtE@\texttt{GtE}}
  7118. }
  7119. \caption{The abstract syntax of \LangIf{}.}
  7120. \label{fig:Lif-syntax}
  7121. \end{figure}
  7122. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7123. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7124. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  7125. evaluate to the corresponding Boolean values. The conditional
  7126. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  7127. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  7128. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  7129. \code{or}, and \code{not} behave according to propositional logic. In
  7130. addition, the \code{and} and \code{or} operations perform
  7131. \emph{short-circuit evaluation}.
  7132. %
  7133. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7134. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7135. %
  7136. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7137. evaluated if $e_1$ evaluates to \TRUE{}.
  7138. \racket{With the increase in the number of primitive operations, the
  7139. interpreter would become repetitive without some care. We refactor
  7140. the case for \code{Prim}, moving the code that differs with each
  7141. operation into the \code{interp\_op} method shown in
  7142. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7143. \code{or} operations separately because of their short-circuiting
  7144. behavior.}
  7145. \begin{figure}[tbp]
  7146. \begin{tcolorbox}[colback=white]
  7147. {\if\edition\racketEd
  7148. \begin{lstlisting}
  7149. (define interp-Lif-class
  7150. (class interp-Lvar-class
  7151. (super-new)
  7152. (define/public (interp_op op) ...)
  7153. (define/override ((interp_exp env) e)
  7154. (define recur (interp_exp env))
  7155. (match e
  7156. [(Bool b) b]
  7157. [(If cnd thn els)
  7158. (match (recur cnd)
  7159. [#t (recur thn)]
  7160. [#f (recur els)])]
  7161. [(Prim 'and (list e1 e2))
  7162. (match (recur e1)
  7163. [#t (match (recur e2) [#t #t] [#f #f])]
  7164. [#f #f])]
  7165. [(Prim 'or (list e1 e2))
  7166. (define v1 (recur e1))
  7167. (match v1
  7168. [#t #t]
  7169. [#f (match (recur e2) [#t #t] [#f #f])])]
  7170. [(Prim op args)
  7171. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7172. [else ((super interp_exp env) e)]))
  7173. ))
  7174. (define (interp_Lif p)
  7175. (send (new interp-Lif-class) interp_program p))
  7176. \end{lstlisting}
  7177. \fi}
  7178. {\if\edition\pythonEd
  7179. \begin{lstlisting}
  7180. class InterpLif(InterpLvar):
  7181. def interp_exp(self, e, env):
  7182. match e:
  7183. case IfExp(test, body, orelse):
  7184. if self.interp_exp(test, env):
  7185. return self.interp_exp(body, env)
  7186. else:
  7187. return self.interp_exp(orelse, env)
  7188. case UnaryOp(Not(), v):
  7189. return not self.interp_exp(v, env)
  7190. case BoolOp(And(), values):
  7191. if self.interp_exp(values[0], env):
  7192. return self.interp_exp(values[1], env)
  7193. else:
  7194. return False
  7195. case BoolOp(Or(), values):
  7196. if self.interp_exp(values[0], env):
  7197. return True
  7198. else:
  7199. return self.interp_exp(values[1], env)
  7200. case Compare(left, [cmp], [right]):
  7201. l = self.interp_exp(left, env)
  7202. r = self.interp_exp(right, env)
  7203. return self.interp_cmp(cmp)(l, r)
  7204. case _:
  7205. return super().interp_exp(e, env)
  7206. def interp_stmts(self, ss, env):
  7207. if len(ss) == 0:
  7208. return
  7209. match ss[0]:
  7210. case If(test, body, orelse):
  7211. if self.interp_exp(test, env):
  7212. return self.interp_stmts(body + ss[1:], env)
  7213. else:
  7214. return self.interp_stmts(orelse + ss[1:], env)
  7215. case _:
  7216. return super().interp_stmts(ss, env)
  7217. ...
  7218. \end{lstlisting}
  7219. \fi}
  7220. \end{tcolorbox}
  7221. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7222. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7223. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7224. \label{fig:interp-Lif}
  7225. \end{figure}
  7226. {\if\edition\racketEd
  7227. \begin{figure}[tbp]
  7228. \begin{tcolorbox}[colback=white]
  7229. \begin{lstlisting}
  7230. (define/public (interp_op op)
  7231. (match op
  7232. ['+ fx+]
  7233. ['- fx-]
  7234. ['read read-fixnum]
  7235. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7236. ['eq? (lambda (v1 v2)
  7237. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7238. (and (boolean? v1) (boolean? v2))
  7239. (and (vector? v1) (vector? v2)))
  7240. (eq? v1 v2)]))]
  7241. ['< (lambda (v1 v2)
  7242. (cond [(and (fixnum? v1) (fixnum? v2))
  7243. (< v1 v2)]))]
  7244. ['<= (lambda (v1 v2)
  7245. (cond [(and (fixnum? v1) (fixnum? v2))
  7246. (<= v1 v2)]))]
  7247. ['> (lambda (v1 v2)
  7248. (cond [(and (fixnum? v1) (fixnum? v2))
  7249. (> v1 v2)]))]
  7250. ['>= (lambda (v1 v2)
  7251. (cond [(and (fixnum? v1) (fixnum? v2))
  7252. (>= v1 v2)]))]
  7253. [else (error 'interp_op "unknown operator")]))
  7254. \end{lstlisting}
  7255. \end{tcolorbox}
  7256. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7257. \label{fig:interp-op-Lif}
  7258. \end{figure}
  7259. \fi}
  7260. {\if\edition\pythonEd
  7261. \begin{figure}
  7262. \begin{tcolorbox}[colback=white]
  7263. \begin{lstlisting}
  7264. class InterpLif(InterpLvar):
  7265. ...
  7266. def interp_cmp(self, cmp):
  7267. match cmp:
  7268. case Lt():
  7269. return lambda x, y: x < y
  7270. case LtE():
  7271. return lambda x, y: x <= y
  7272. case Gt():
  7273. return lambda x, y: x > y
  7274. case GtE():
  7275. return lambda x, y: x >= y
  7276. case Eq():
  7277. return lambda x, y: x == y
  7278. case NotEq():
  7279. return lambda x, y: x != y
  7280. \end{lstlisting}
  7281. \end{tcolorbox}
  7282. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7283. \label{fig:interp-cmp-Lif}
  7284. \end{figure}
  7285. \fi}
  7286. \section{Type Checking \LangIf{} Programs}
  7287. \label{sec:type-check-Lif}
  7288. \index{subject}{type checking}
  7289. \index{subject}{semantic analysis}
  7290. It is helpful to think about type checking in two complementary
  7291. ways. A type checker predicts the type of value that will be produced
  7292. by each expression in the program. For \LangIf{}, we have just two types,
  7293. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  7294. {\if\edition\racketEd
  7295. \begin{lstlisting}
  7296. (+ 10 (- (+ 12 20)))
  7297. \end{lstlisting}
  7298. \fi}
  7299. {\if\edition\pythonEd
  7300. \begin{lstlisting}
  7301. 10 + -(12 + 20)
  7302. \end{lstlisting}
  7303. \fi}
  7304. \noindent produces a value of type \INTTY{}, whereas
  7305. {\if\edition\racketEd
  7306. \begin{lstlisting}
  7307. (and (not #f) #t)
  7308. \end{lstlisting}
  7309. \fi}
  7310. {\if\edition\pythonEd
  7311. \begin{lstlisting}
  7312. (not False) and True
  7313. \end{lstlisting}
  7314. \fi}
  7315. \noindent produces a value of type \BOOLTY{}.
  7316. A second way to think about type checking is that it enforces a set of
  7317. rules about which operators can be applied to which kinds of
  7318. values. For example, our type checker for \LangIf{} signals an error
  7319. for the following expression:
  7320. %
  7321. {\if\edition\racketEd
  7322. \begin{lstlisting}
  7323. (not (+ 10 (- (+ 12 20))))
  7324. \end{lstlisting}
  7325. \fi}
  7326. {\if\edition\pythonEd
  7327. \begin{lstlisting}
  7328. not (10 + -(12 + 20))
  7329. \end{lstlisting}
  7330. \fi}
  7331. \noindent The subexpression
  7332. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7333. \python{\code{(10 + -(12 + 20))}}
  7334. has type \INTTY{}, but the type checker enforces the rule that the
  7335. argument of \code{not} must be an expression of type \BOOLTY{}.
  7336. We implement type checking using classes and methods because they
  7337. provide the open recursion needed to reuse code as we extend the type
  7338. checker in subsequent chapters, analogous to the use of classes and methods
  7339. for the interpreters (section~\ref{sec:extensible-interp}).
  7340. We separate the type checker for the \LangVar{} subset into its own
  7341. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7342. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7343. from the type checker for \LangVar{}. These type checkers are in the
  7344. files
  7345. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7346. and
  7347. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7348. of the support code.
  7349. %
  7350. Each type checker is a structurally recursive function over the AST.
  7351. Given an input expression \code{e}, the type checker either signals an
  7352. error or returns \racket{an expression and} its type.
  7353. %
  7354. \racket{It returns an expression because there are situations in which
  7355. we want to change or update the expression.}
  7356. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7357. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7358. constant is \INTTY{}. To handle variables, the type checker uses the
  7359. environment \code{env} to map variables to types.
  7360. %
  7361. \racket{Consider the case for \key{let}. We type check the
  7362. initializing expression to obtain its type \key{T} and then
  7363. associate type \code{T} with the variable \code{x} in the
  7364. environment used to type check the body of the \key{let}. Thus,
  7365. when the type checker encounters a use of variable \code{x}, it can
  7366. find its type in the environment.}
  7367. %
  7368. \python{Consider the case for assignment. We type check the
  7369. initializing expression to obtain its type \key{t}. If the variable
  7370. \code{lhs.id} is already in the environment because there was a
  7371. prior assignment, we check that this initializer has the same type
  7372. as the prior one. If this is the first assignment to the variable,
  7373. we associate type \code{t} with the variable \code{lhs.id} in the
  7374. environment. Thus, when the type checker encounters a use of
  7375. variable \code{x}, it can find its type in the environment.}
  7376. %
  7377. \racket{Regarding primitive operators, we recursively analyze the
  7378. arguments and then invoke \code{type\_check\_op} to check whether
  7379. the argument types are allowed.}
  7380. %
  7381. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7382. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7383. \racket{Several auxiliary methods are used in the type checker. The
  7384. method \code{operator-types} defines a dictionary that maps the
  7385. operator names to their parameter and return types. The
  7386. \code{type-equal?} method determines whether two types are equal,
  7387. which for now simply dispatches to \code{equal?} (deep
  7388. equality). The \code{check-type-equal?} method triggers an error if
  7389. the two types are not equal. The \code{type-check-op} method looks
  7390. up the operator in the \code{operator-types} dictionary and then
  7391. checks whether the argument types are equal to the parameter types.
  7392. The result is the return type of the operator.}
  7393. %
  7394. \python{The auxiliary method \code{check\_type\_equal} triggers
  7395. an error if the two types are not equal.}
  7396. \begin{figure}[tbp]
  7397. \begin{tcolorbox}[colback=white]
  7398. {\if\edition\racketEd
  7399. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7400. (define type-check-Lvar-class
  7401. (class object%
  7402. (super-new)
  7403. (define/public (operator-types)
  7404. '((+ . ((Integer Integer) . Integer))
  7405. (- . ((Integer Integer) . Integer))
  7406. (read . (() . Integer))))
  7407. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7408. (define/public (check-type-equal? t1 t2 e)
  7409. (unless (type-equal? t1 t2)
  7410. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7411. (define/public (type-check-op op arg-types e)
  7412. (match (dict-ref (operator-types) op)
  7413. [`(,param-types . ,return-type)
  7414. (for ([at arg-types] [pt param-types])
  7415. (check-type-equal? at pt e))
  7416. return-type]
  7417. [else (error 'type-check-op "unrecognized ~a" op)]))
  7418. (define/public (type-check-exp env)
  7419. (lambda (e)
  7420. (match e
  7421. [(Int n) (values (Int n) 'Integer)]
  7422. [(Var x) (values (Var x) (dict-ref env x))]
  7423. [(Let x e body)
  7424. (define-values (e^ Te) ((type-check-exp env) e))
  7425. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7426. (values (Let x e^ b) Tb)]
  7427. [(Prim op es)
  7428. (define-values (new-es ts)
  7429. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7430. (values (Prim op new-es) (type-check-op op ts e))]
  7431. [else (error 'type-check-exp "couldn't match" e)])))
  7432. (define/public (type-check-program e)
  7433. (match e
  7434. [(Program info body)
  7435. (define-values (body^ Tb) ((type-check-exp '()) body))
  7436. (check-type-equal? Tb 'Integer body)
  7437. (Program info body^)]
  7438. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7439. ))
  7440. (define (type-check-Lvar p)
  7441. (send (new type-check-Lvar-class) type-check-program p))
  7442. \end{lstlisting}
  7443. \fi}
  7444. {\if\edition\pythonEd
  7445. \begin{lstlisting}[escapechar=`]
  7446. class TypeCheckLvar:
  7447. def check_type_equal(self, t1, t2, e):
  7448. if t1 != t2:
  7449. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7450. raise Exception(msg)
  7451. def type_check_exp(self, e, env):
  7452. match e:
  7453. case BinOp(left, (Add() | Sub()), right):
  7454. l = self.type_check_exp(left, env)
  7455. check_type_equal(l, int, left)
  7456. r = self.type_check_exp(right, env)
  7457. check_type_equal(r, int, right)
  7458. return int
  7459. case UnaryOp(USub(), v):
  7460. t = self.type_check_exp(v, env)
  7461. check_type_equal(t, int, v)
  7462. return int
  7463. case Name(id):
  7464. return env[id]
  7465. case Constant(value) if isinstance(value, int):
  7466. return int
  7467. case Call(Name('input_int'), []):
  7468. return int
  7469. def type_check_stmts(self, ss, env):
  7470. if len(ss) == 0:
  7471. return
  7472. match ss[0]:
  7473. case Assign([lhs], value):
  7474. t = self.type_check_exp(value, env)
  7475. if lhs.id in env:
  7476. check_type_equal(env[lhs.id], t, value)
  7477. else:
  7478. env[lhs.id] = t
  7479. return self.type_check_stmts(ss[1:], env)
  7480. case Expr(Call(Name('print'), [arg])):
  7481. t = self.type_check_exp(arg, env)
  7482. check_type_equal(t, int, arg)
  7483. return self.type_check_stmts(ss[1:], env)
  7484. case Expr(value):
  7485. self.type_check_exp(value, env)
  7486. return self.type_check_stmts(ss[1:], env)
  7487. def type_check_P(self, p):
  7488. match p:
  7489. case Module(body):
  7490. self.type_check_stmts(body, {})
  7491. \end{lstlisting}
  7492. \fi}
  7493. \end{tcolorbox}
  7494. \caption{Type checker for the \LangVar{} language.}
  7495. \label{fig:type-check-Lvar}
  7496. \end{figure}
  7497. \begin{figure}[tbp]
  7498. \begin{tcolorbox}[colback=white]
  7499. {\if\edition\racketEd
  7500. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7501. (define type-check-Lif-class
  7502. (class type-check-Lvar-class
  7503. (super-new)
  7504. (inherit check-type-equal?)
  7505. (define/override (operator-types)
  7506. (append '((and . ((Boolean Boolean) . Boolean))
  7507. (or . ((Boolean Boolean) . Boolean))
  7508. (< . ((Integer Integer) . Boolean))
  7509. (<= . ((Integer Integer) . Boolean))
  7510. (> . ((Integer Integer) . Boolean))
  7511. (>= . ((Integer Integer) . Boolean))
  7512. (not . ((Boolean) . Boolean)))
  7513. (super operator-types)))
  7514. (define/override (type-check-exp env)
  7515. (lambda (e)
  7516. (match e
  7517. [(Bool b) (values (Bool b) 'Boolean)]
  7518. [(Prim 'eq? (list e1 e2))
  7519. (define-values (e1^ T1) ((type-check-exp env) e1))
  7520. (define-values (e2^ T2) ((type-check-exp env) e2))
  7521. (check-type-equal? T1 T2 e)
  7522. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7523. [(If cnd thn els)
  7524. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7525. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7526. (define-values (els^ Te) ((type-check-exp env) els))
  7527. (check-type-equal? Tc 'Boolean e)
  7528. (check-type-equal? Tt Te e)
  7529. (values (If cnd^ thn^ els^) Te)]
  7530. [else ((super type-check-exp env) e)])))
  7531. ))
  7532. (define (type-check-Lif p)
  7533. (send (new type-check-Lif-class) type-check-program p))
  7534. \end{lstlisting}
  7535. \fi}
  7536. {\if\edition\pythonEd
  7537. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7538. class TypeCheckLif(TypeCheckLvar):
  7539. def type_check_exp(self, e, env):
  7540. match e:
  7541. case Constant(value) if isinstance(value, bool):
  7542. return bool
  7543. case BinOp(left, Sub(), right):
  7544. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7545. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7546. return int
  7547. case UnaryOp(Not(), v):
  7548. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7549. return bool
  7550. case BoolOp(op, values):
  7551. left = values[0] ; right = values[1]
  7552. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7553. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7554. return bool
  7555. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7556. or isinstance(cmp, NotEq):
  7557. l = self.type_check_exp(left, env)
  7558. r = self.type_check_exp(right, env)
  7559. check_type_equal(l, r, e)
  7560. return bool
  7561. case Compare(left, [cmp], [right]):
  7562. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7563. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7564. return bool
  7565. case IfExp(test, body, orelse):
  7566. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7567. b = self.type_check_exp(body, env)
  7568. o = self.type_check_exp(orelse, env)
  7569. check_type_equal(b, o, e)
  7570. return b
  7571. case _:
  7572. return super().type_check_exp(e, env)
  7573. def type_check_stmts(self, ss, env):
  7574. if len(ss) == 0:
  7575. return
  7576. match ss[0]:
  7577. case If(test, body, orelse):
  7578. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7579. b = self.type_check_stmts(body, env)
  7580. o = self.type_check_stmts(orelse, env)
  7581. check_type_equal(b, o, ss[0])
  7582. return self.type_check_stmts(ss[1:], env)
  7583. case _:
  7584. return super().type_check_stmts(ss, env)
  7585. \end{lstlisting}
  7586. \fi}
  7587. \end{tcolorbox}
  7588. \caption{Type checker for the \LangIf{} language.}
  7589. \label{fig:type-check-Lif}
  7590. \end{figure}
  7591. The definition of the type checker for \LangIf{} is shown in
  7592. figure~\ref{fig:type-check-Lif}.
  7593. %
  7594. The type of a Boolean constant is \BOOLTY{}.
  7595. %
  7596. \racket{The \code{operator-types} function adds dictionary entries for
  7597. the new operators.}
  7598. %
  7599. \python{Logical not requires its argument to be a \BOOLTY{} and
  7600. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  7601. %
  7602. The equality operator requires the two arguments to have the same type,
  7603. and therefore we handle it separately from the other operators.
  7604. %
  7605. \python{The other comparisons (less-than, etc.) require their
  7606. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  7607. %
  7608. The condition of an \code{if} must
  7609. be of \BOOLTY{} type, and the two branches must have the same type.
  7610. \begin{exercise}\normalfont\normalsize
  7611. Create ten new test programs in \LangIf{}. Half the programs should
  7612. have a type error. For those programs, create an empty file with the
  7613. same base name and with file extension \code{.tyerr}. For example, if
  7614. the test
  7615. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  7616. is expected to error, then create
  7617. an empty file named \code{cond\_test\_14.tyerr}.
  7618. %
  7619. \racket{This indicates to \code{interp-tests} and
  7620. \code{compiler-tests} that a type error is expected. }
  7621. %
  7622. The other half of the test programs should not have type errors.
  7623. %
  7624. \racket{In the \code{run-tests.rkt} script, change the second argument
  7625. of \code{interp-tests} and \code{compiler-tests} to
  7626. \code{type-check-Lif}, which causes the type checker to run prior to
  7627. the compiler passes. Temporarily change the \code{passes} to an
  7628. empty list and run the script, thereby checking that the new test
  7629. programs either type check or do not, as intended.}
  7630. %
  7631. Run the test script to check that these test programs type check as
  7632. expected.
  7633. \end{exercise}
  7634. \clearpage
  7635. \section{The \LangCIf{} Intermediate Language}
  7636. \label{sec:Cif}
  7637. {\if\edition\racketEd
  7638. %
  7639. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7640. comparison operators to the \Exp{} nonterminal and the literals
  7641. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7642. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7643. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7644. comparison operation and the branches are \code{goto} statements,
  7645. making it straightforward to compile \code{if} statements to x86. The
  7646. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7647. expressions. A \code{goto} statement transfers control to the $\Tail$
  7648. expression corresponding to its label.
  7649. %
  7650. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7651. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7652. defines its abstract syntax.
  7653. %
  7654. \fi}
  7655. %
  7656. {\if\edition\pythonEd
  7657. %
  7658. The output of \key{explicate\_control} is a language similar to the
  7659. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7660. \code{goto} statements, so we name it \LangCIf{}.
  7661. %
  7662. The \LangCIf{} language supports the same operators as \LangIf{} but
  7663. the arguments of operators are restricted to atomic expressions. The
  7664. \LangCIf{} language does not include \code{if} expressions but it does
  7665. include a restricted form of \code{if} statement. The condition must be
  7666. a comparison and the two branches may only contain \code{goto}
  7667. statements. These restrictions make it easier to translate \code{if}
  7668. statements to x86. The \LangCIf{} language also adds a \code{return}
  7669. statement to finish the program with a specified value.
  7670. %
  7671. The \key{CProgram} construct contains a dictionary mapping labels to
  7672. lists of statements that end with a \code{return} statement, a
  7673. \code{goto}, or a conditional \code{goto}.
  7674. %% Statement lists of this
  7675. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7676. %% is a control transfer at the end and control only enters at the
  7677. %% beginning of the list, which is marked by the label.
  7678. %
  7679. A \code{goto} statement transfers control to the sequence of statements
  7680. associated with its label.
  7681. %
  7682. The concrete syntax for \LangCIf{} is defined in
  7683. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7684. in figure~\ref{fig:c1-syntax}.
  7685. %
  7686. \fi}
  7687. %
  7688. \newcommand{\CifGrammarRacket}{
  7689. \begin{array}{lcl}
  7690. \Atm &::=& \itm{bool} \\
  7691. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7692. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7693. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7694. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7695. \end{array}
  7696. }
  7697. \newcommand{\CifASTRacket}{
  7698. \begin{array}{lcl}
  7699. \Atm &::=& \BOOL{\itm{bool}} \\
  7700. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7701. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7702. \Tail &::= & \GOTO{\itm{label}} \\
  7703. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7704. \end{array}
  7705. }
  7706. \newcommand{\CifGrammarPython}{
  7707. \begin{array}{lcl}
  7708. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7709. \Exp &::= & \Atm \MID \CREAD{}
  7710. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7711. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7712. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7713. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7714. &\MID& \CASSIGN{\Var}{\Exp}
  7715. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7716. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7717. \end{array}
  7718. }
  7719. \newcommand{\CifASTPython}{
  7720. \begin{array}{lcl}
  7721. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7722. \Exp &::= & \Atm \MID \READ{} \\
  7723. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7724. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7725. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7726. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7727. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7728. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7729. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7730. \end{array}
  7731. }
  7732. \begin{figure}[tbp]
  7733. \begin{tcolorbox}[colback=white]
  7734. \small
  7735. {\if\edition\racketEd
  7736. \[
  7737. \begin{array}{l}
  7738. \gray{\CvarGrammarRacket} \\ \hline
  7739. \CifGrammarRacket \\
  7740. \begin{array}{lcl}
  7741. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7742. \end{array}
  7743. \end{array}
  7744. \]
  7745. \fi}
  7746. {\if\edition\pythonEd
  7747. \[
  7748. \begin{array}{l}
  7749. \CifGrammarPython \\
  7750. \begin{array}{lcl}
  7751. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7752. \end{array}
  7753. \end{array}
  7754. \]
  7755. \fi}
  7756. \end{tcolorbox}
  7757. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7758. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7759. \label{fig:c1-concrete-syntax}
  7760. \end{figure}
  7761. \begin{figure}[tp]
  7762. \begin{tcolorbox}[colback=white]
  7763. \small
  7764. {\if\edition\racketEd
  7765. \[
  7766. \begin{array}{l}
  7767. \gray{\CvarASTRacket} \\ \hline
  7768. \CifASTRacket \\
  7769. \begin{array}{lcl}
  7770. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7771. \end{array}
  7772. \end{array}
  7773. \]
  7774. \fi}
  7775. {\if\edition\pythonEd
  7776. \[
  7777. \begin{array}{l}
  7778. \CifASTPython \\
  7779. \begin{array}{lcl}
  7780. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7781. \end{array}
  7782. \end{array}
  7783. \]
  7784. \fi}
  7785. \end{tcolorbox}
  7786. \racket{
  7787. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7788. }
  7789. \index{subject}{Goto@\texttt{Goto}}
  7790. \index{subject}{Return@\texttt{Return}}
  7791. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7792. (figure~\ref{fig:c0-syntax})}.}
  7793. \label{fig:c1-syntax}
  7794. \end{figure}
  7795. \section{The \LangXIf{} Language}
  7796. \label{sec:x86-if}
  7797. \index{subject}{x86} To implement the new logical operations, the
  7798. comparison operations, and the \key{if} expression\python{ and
  7799. statement}, we delve further into the x86
  7800. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7801. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7802. subset of x86, which includes instructions for logical operations,
  7803. comparisons, and \racket{conditional} jumps.
  7804. %
  7805. \python{The abstract syntax for an \LangXIf{} program contains a
  7806. dictionary mapping labels to sequences of instructions, each of
  7807. which we refer to as a \emph{basic block}\index{subject}{basic
  7808. block}.}
  7809. One challenge is that x86 does not provide an instruction that
  7810. directly implements logical negation (\code{not} in \LangIf{} and
  7811. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7812. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7813. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7814. bit of its arguments, and writes the results into its second argument.
  7815. Recall the following truth table for exclusive-or:
  7816. \begin{center}
  7817. \begin{tabular}{l|cc}
  7818. & 0 & 1 \\ \hline
  7819. 0 & 0 & 1 \\
  7820. 1 & 1 & 0
  7821. \end{tabular}
  7822. \end{center}
  7823. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7824. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7825. for the bit $1$, the result is the opposite of the second bit. Thus,
  7826. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7827. the first argument, as follows, where $\Arg$ is the translation of
  7828. $\Atm$ to x86:
  7829. \[
  7830. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7831. \qquad\Rightarrow\qquad
  7832. \begin{array}{l}
  7833. \key{movq}~ \Arg\key{,} \Var\\
  7834. \key{xorq}~ \key{\$1,} \Var
  7835. \end{array}
  7836. \]
  7837. \newcommand{\GrammarXIf}{
  7838. \begin{array}{lcl}
  7839. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7840. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7841. \Arg &::=& \key{\%}\itm{bytereg}\\
  7842. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7843. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7844. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7845. \MID \key{set}cc~\Arg
  7846. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7847. &\MID& \key{j}cc~\itm{label} \\
  7848. \end{array}
  7849. }
  7850. \begin{figure}[tp]
  7851. \begin{tcolorbox}[colback=white]
  7852. \[
  7853. \begin{array}{l}
  7854. \gray{\GrammarXInt} \\ \hline
  7855. \GrammarXIf \\
  7856. \begin{array}{lcl}
  7857. \LangXIfM{} &::= & \key{.globl main} \\
  7858. & & \key{main:} \; \Instr\ldots
  7859. \end{array}
  7860. \end{array}
  7861. \]
  7862. \end{tcolorbox}
  7863. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7864. \label{fig:x86-1-concrete}
  7865. \end{figure}
  7866. \newcommand{\ASTXIfRacket}{
  7867. \begin{array}{lcl}
  7868. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7869. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7870. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7871. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7872. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7873. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7874. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7875. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7876. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7877. \end{array}
  7878. }
  7879. \begin{figure}[tp]
  7880. \begin{tcolorbox}[colback=white]
  7881. \small
  7882. {\if\edition\racketEd
  7883. \[\arraycolsep=3pt
  7884. \begin{array}{l}
  7885. \gray{\ASTXIntRacket} \\ \hline
  7886. \ASTXIfRacket \\
  7887. \begin{array}{lcl}
  7888. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7889. \end{array}
  7890. \end{array}
  7891. \]
  7892. \fi}
  7893. %
  7894. {\if\edition\pythonEd
  7895. \[
  7896. \begin{array}{lcl}
  7897. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7898. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7899. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7900. \MID \BYTEREG{\itm{bytereg}} \\
  7901. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7902. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7903. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7904. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7905. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7906. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7907. \MID \PUSHQ{\Arg}} \\
  7908. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7909. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7910. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7911. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7912. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7913. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7914. \Block &::= & \Instr^{+} \\
  7915. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7916. \end{array}
  7917. \]
  7918. \fi}
  7919. \end{tcolorbox}
  7920. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7921. \label{fig:x86-1}
  7922. \end{figure}
  7923. Next we consider the x86 instructions that are relevant for compiling
  7924. the comparison operations. The \key{cmpq} instruction compares its two
  7925. arguments to determine whether one argument is less than, equal to, or
  7926. greater than the other argument. The \key{cmpq} instruction is unusual
  7927. regarding the order of its arguments and where the result is
  7928. placed. The argument order is backward: if you want to test whether
  7929. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7930. \key{cmpq} is placed in the special EFLAGS register. This register
  7931. cannot be accessed directly, but it can be queried by a number of
  7932. instructions, including the \key{set} instruction. The instruction
  7933. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7934. depending on whether the contents of the EFLAGS register matches the
  7935. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7936. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7937. The \key{set} instruction has a quirk in that its destination argument
  7938. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7939. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7940. register. Thankfully, the \key{movzbq} instruction can be used to
  7941. move from a single-byte register to a normal 64-bit register. The
  7942. abstract syntax for the \code{set} instruction differs from the
  7943. concrete syntax in that it separates the instruction name from the
  7944. condition code.
  7945. \python{The x86 instructions for jumping are relevant to the
  7946. compilation of \key{if} expressions.}
  7947. %
  7948. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7949. counter to the address of the instruction after the specified
  7950. label.}
  7951. %
  7952. \racket{The x86 instruction for conditional jump is relevant to the
  7953. compilation of \key{if} expressions.}
  7954. %
  7955. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7956. counter to point to the instruction after \itm{label}, depending on
  7957. whether the result in the EFLAGS register matches the condition code
  7958. \itm{cc}; otherwise, the jump instruction falls through to the next
  7959. instruction. Like the abstract syntax for \code{set}, the abstract
  7960. syntax for conditional jump separates the instruction name from the
  7961. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7962. corresponds to \code{jle foo}. Because the conditional jump instruction
  7963. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7964. a \key{cmpq} instruction to set the EFLAGS register.
  7965. \section{Shrink the \LangIf{} Language}
  7966. \label{sec:shrink-Lif}
  7967. The \LangIf{} language includes several features that are easily
  7968. expressible with other features. For example, \code{and} and \code{or}
  7969. are expressible using \code{if} as follows.
  7970. \begin{align*}
  7971. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7972. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7973. \end{align*}
  7974. By performing these translations in the front end of the compiler,
  7975. subsequent passes of the compiler do not need to deal with these features,
  7976. thus making the passes shorter.
  7977. On the other hand, translations sometimes reduce the efficiency of the
  7978. generated code by increasing the number of instructions. For example,
  7979. expressing subtraction in terms of negation
  7980. \[
  7981. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7982. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7983. \]
  7984. produces code with two x86 instructions (\code{negq} and \code{addq})
  7985. instead of just one (\code{subq}).
  7986. \begin{exercise}\normalfont\normalsize
  7987. %
  7988. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7989. the language by translating them to \code{if} expressions in \LangIf{}.
  7990. %
  7991. Create four test programs that involve these operators.
  7992. %
  7993. {\if\edition\racketEd
  7994. In the \code{run-tests.rkt} script, add the following entry for
  7995. \code{shrink} to the list of passes (it should be the only pass at
  7996. this point).
  7997. \begin{lstlisting}
  7998. (list "shrink" shrink interp_Lif type-check-Lif)
  7999. \end{lstlisting}
  8000. This instructs \code{interp-tests} to run the interpreter
  8001. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8002. output of \code{shrink}.
  8003. \fi}
  8004. %
  8005. Run the script to test your compiler on all the test programs.
  8006. \end{exercise}
  8007. {\if\edition\racketEd
  8008. \section{Uniquify Variables}
  8009. \label{sec:uniquify-Lif}
  8010. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8011. \code{if} expressions.
  8012. \begin{exercise}\normalfont\normalsize
  8013. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8014. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8015. \begin{lstlisting}
  8016. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8017. \end{lstlisting}
  8018. Run the script to test your compiler.
  8019. \end{exercise}
  8020. \fi}
  8021. \section{Remove Complex Operands}
  8022. \label{sec:remove-complex-opera-Lif}
  8023. The output language of \code{remove\_complex\_operands} is
  8024. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8025. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8026. but the \code{if} expression is not. All three subexpressions of an
  8027. \code{if} are allowed to be complex expressions, but the operands of
  8028. the \code{not} operator and comparison operators must be atomic.
  8029. %
  8030. \python{We add a new language form, the \code{Begin} expression, to aid
  8031. in the translation of \code{if} expressions. When we recursively
  8032. process the two branches of the \code{if}, we generate temporary
  8033. variables and their initializing expressions. However, these
  8034. expressions may contain side effects and should only be executed
  8035. when the condition of the \code{if} is true (for the ``then''
  8036. branch) or false (for the ``else'' branch). The \code{Begin} provides
  8037. a way to initialize the temporary variables within the two branches
  8038. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8039. form execute the statements $ss$ and then returns the result of
  8040. expression $e$.}
  8041. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8042. the new features in \LangIf{}. In recursively processing
  8043. subexpressions, recall that you should invoke \code{rco\_atom} when
  8044. the output needs to be an \Atm{} (as specified in the grammar for
  8045. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8046. \Exp{}. Regarding \code{if}, it is particularly important
  8047. \textbf{not} to replace its condition with a temporary variable, because
  8048. that would interfere with the generation of high-quality output in the
  8049. upcoming \code{explicate\_control} pass.
  8050. \newcommand{\LifMonadASTRacket}{
  8051. \begin{array}{rcl}
  8052. \Atm &::=& \BOOL{\itm{bool}}\\
  8053. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8054. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8055. \MID \IF{\Exp}{\Exp}{\Exp}
  8056. \end{array}
  8057. }
  8058. \newcommand{\LifMonadASTPython}{
  8059. \begin{array}{rcl}
  8060. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  8061. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  8062. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  8063. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  8064. \Atm &::=& \BOOL{\itm{bool}}\\
  8065. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  8066. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  8067. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8068. \end{array}
  8069. }
  8070. \begin{figure}[tp]
  8071. \centering
  8072. \begin{tcolorbox}[colback=white]
  8073. {\if\edition\racketEd
  8074. \[
  8075. \begin{array}{l}
  8076. \gray{\LvarMonadASTRacket} \\ \hline
  8077. \LifMonadASTRacket \\
  8078. \begin{array}{rcl}
  8079. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8080. \end{array}
  8081. \end{array}
  8082. \]
  8083. \fi}
  8084. {\if\edition\pythonEd
  8085. \[
  8086. \begin{array}{l}
  8087. \gray{\LvarMonadASTPython} \\ \hline
  8088. \LifMonadASTPython \\
  8089. \begin{array}{rcl}
  8090. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8091. \end{array}
  8092. \end{array}
  8093. \]
  8094. \fi}
  8095. \end{tcolorbox}
  8096. \python{\index{subject}{Begin@\texttt{Begin}}}
  8097. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8098. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8099. \label{fig:Lif-anf-syntax}
  8100. \end{figure}
  8101. \begin{exercise}\normalfont\normalsize
  8102. %
  8103. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8104. and \code{rco\_exp} functions in \code{compiler.rkt}.
  8105. %
  8106. Create three new \LangIf{} programs that exercise the interesting
  8107. code in this pass.
  8108. %
  8109. {\if\edition\racketEd
  8110. In the \code{run-tests.rkt} script, add the following entry to the
  8111. list of \code{passes} and then run the script to test your compiler.
  8112. \begin{lstlisting}
  8113. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8114. \end{lstlisting}
  8115. \fi}
  8116. \end{exercise}
  8117. \section{Explicate Control}
  8118. \label{sec:explicate-control-Lif}
  8119. \racket{Recall that the purpose of \code{explicate\_control} is to
  8120. make the order of evaluation explicit in the syntax of the program.
  8121. With the addition of \key{if}, this becomes more interesting.}
  8122. %
  8123. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8124. %
  8125. The main challenge to overcome is that the condition of an \key{if}
  8126. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8127. condition must be a comparison.
  8128. As a motivating example, consider the following program that has an
  8129. \key{if} expression nested in the condition of another \key{if}:%
  8130. \python{\footnote{Programmers rarely write nested \code{if}
  8131. expressions, but it is not uncommon for the condition of an
  8132. \code{if} statement to be a call of a function that also contains an
  8133. \code{if} statement. When such a function is inlined, the result is
  8134. a nested \code{if} that requires the techniques discussed in this
  8135. section.}}
  8136. % cond_test_41.rkt, if_lt_eq.py
  8137. \begin{center}
  8138. \begin{minipage}{0.96\textwidth}
  8139. {\if\edition\racketEd
  8140. \begin{lstlisting}
  8141. (let ([x (read)])
  8142. (let ([y (read)])
  8143. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8144. (+ y 2)
  8145. (+ y 10))))
  8146. \end{lstlisting}
  8147. \fi}
  8148. {\if\edition\pythonEd
  8149. \begin{lstlisting}
  8150. x = input_int()
  8151. y = input_int()
  8152. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8153. \end{lstlisting}
  8154. \fi}
  8155. \end{minipage}
  8156. \end{center}
  8157. %
  8158. The naive way to compile \key{if} and the comparison operations would
  8159. be to handle each of them in isolation, regardless of their context.
  8160. Each comparison would be translated into a \key{cmpq} instruction
  8161. followed by several instructions to move the result from the EFLAGS
  8162. register into a general purpose register or stack location. Each
  8163. \key{if} would be translated into a \key{cmpq} instruction followed by
  8164. a conditional jump. The generated code for the inner \key{if} in this
  8165. example would be as follows:
  8166. \begin{center}
  8167. \begin{minipage}{0.96\textwidth}
  8168. \begin{lstlisting}
  8169. cmpq $1, x
  8170. setl %al
  8171. movzbq %al, tmp
  8172. cmpq $1, tmp
  8173. je then_branch_1
  8174. jmp else_branch_1
  8175. \end{lstlisting}
  8176. \end{minipage}
  8177. \end{center}
  8178. Notice that the three instructions starting with \code{setl} are
  8179. redundant: the conditional jump could come immediately after the first
  8180. \code{cmpq}.
  8181. Our goal is to compile \key{if} expressions so that the relevant
  8182. comparison instruction appears directly before the conditional jump.
  8183. For example, we want to generate the following code for the inner
  8184. \code{if}:
  8185. \begin{center}
  8186. \begin{minipage}{0.96\textwidth}
  8187. \begin{lstlisting}
  8188. cmpq $1, x
  8189. jl then_branch_1
  8190. jmp else_branch_1
  8191. \end{lstlisting}
  8192. \end{minipage}
  8193. \end{center}
  8194. One way to achieve this goal is to reorganize the code at the level of
  8195. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8196. the following code:
  8197. \begin{center}
  8198. \begin{minipage}{0.96\textwidth}
  8199. {\if\edition\racketEd
  8200. \begin{lstlisting}
  8201. (let ([x (read)])
  8202. (let ([y (read)])
  8203. (if (< x 1)
  8204. (if (eq? x 0)
  8205. (+ y 2)
  8206. (+ y 10))
  8207. (if (eq? x 2)
  8208. (+ y 2)
  8209. (+ y 10)))))
  8210. \end{lstlisting}
  8211. \fi}
  8212. {\if\edition\pythonEd
  8213. \begin{lstlisting}
  8214. x = input_int()
  8215. y = input_int()
  8216. print(((y + 2) if x == 0 else (y + 10)) \
  8217. if (x < 1) \
  8218. else ((y + 2) if (x == 2) else (y + 10)))
  8219. \end{lstlisting}
  8220. \fi}
  8221. \end{minipage}
  8222. \end{center}
  8223. Unfortunately, this approach duplicates the two branches from the
  8224. outer \code{if}, and a compiler must never duplicate code! After all,
  8225. the two branches could be very large expressions.
  8226. How can we apply this transformation without duplicating code? In
  8227. other words, how can two different parts of a program refer to one
  8228. piece of code?
  8229. %
  8230. The answer is that we must move away from abstract syntax \emph{trees}
  8231. and instead use \emph{graphs}.
  8232. %
  8233. At the level of x86 assembly, this is straightforward because we can
  8234. label the code for each branch and insert jumps in all the places that
  8235. need to execute the branch. In this way, jump instructions are edges
  8236. in the graph and the basic blocks are the nodes.
  8237. %
  8238. Likewise, our language \LangCIf{} provides the ability to label a
  8239. sequence of statements and to jump to a label via \code{goto}.
  8240. As a preview of what \code{explicate\_control} will do,
  8241. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8242. \code{explicate\_control} on this example. Note how the condition of
  8243. every \code{if} is a comparison operation and that we have not
  8244. duplicated any code but instead have used labels and \code{goto} to
  8245. enable sharing of code.
  8246. \begin{figure}[tbp]
  8247. \begin{tcolorbox}[colback=white]
  8248. {\if\edition\racketEd
  8249. \begin{tabular}{lll}
  8250. \begin{minipage}{0.4\textwidth}
  8251. % cond_test_41.rkt
  8252. \begin{lstlisting}
  8253. (let ([x (read)])
  8254. (let ([y (read)])
  8255. (if (if (< x 1)
  8256. (eq? x 0)
  8257. (eq? x 2))
  8258. (+ y 2)
  8259. (+ y 10))))
  8260. \end{lstlisting}
  8261. \end{minipage}
  8262. &
  8263. $\Rightarrow$
  8264. &
  8265. \begin{minipage}{0.55\textwidth}
  8266. \begin{lstlisting}
  8267. start:
  8268. x = (read);
  8269. y = (read);
  8270. if (< x 1)
  8271. goto block_4;
  8272. else
  8273. goto block_5;
  8274. block_4:
  8275. if (eq? x 0)
  8276. goto block_2;
  8277. else
  8278. goto block_3;
  8279. block_5:
  8280. if (eq? x 2)
  8281. goto block_2;
  8282. else
  8283. goto block_3;
  8284. block_2:
  8285. return (+ y 2);
  8286. block_3:
  8287. return (+ y 10);
  8288. \end{lstlisting}
  8289. \end{minipage}
  8290. \end{tabular}
  8291. \fi}
  8292. {\if\edition\pythonEd
  8293. \begin{tabular}{lll}
  8294. \begin{minipage}{0.4\textwidth}
  8295. % cond_test_41.rkt
  8296. \begin{lstlisting}
  8297. x = input_int()
  8298. y = input_int()
  8299. print(y + 2 \
  8300. if (x == 0 \
  8301. if x < 1 \
  8302. else x == 2) \
  8303. else y + 10)
  8304. \end{lstlisting}
  8305. \end{minipage}
  8306. &
  8307. $\Rightarrow$
  8308. &
  8309. \begin{minipage}{0.55\textwidth}
  8310. \begin{lstlisting}
  8311. start:
  8312. x = input_int()
  8313. y = input_int()
  8314. if x < 1:
  8315. goto block_8
  8316. else:
  8317. goto block_9
  8318. block_8:
  8319. if x == 0:
  8320. goto block_4
  8321. else:
  8322. goto block_5
  8323. block_9:
  8324. if x == 2:
  8325. goto block_6
  8326. else:
  8327. goto block_7
  8328. block_4:
  8329. goto block_2
  8330. block_5:
  8331. goto block_3
  8332. block_6:
  8333. goto block_2
  8334. block_7:
  8335. goto block_3
  8336. block_2:
  8337. tmp_0 = y + 2
  8338. goto block_1
  8339. block_3:
  8340. tmp_0 = y + 10
  8341. goto block_1
  8342. block_1:
  8343. print(tmp_0)
  8344. return 0
  8345. \end{lstlisting}
  8346. \end{minipage}
  8347. \end{tabular}
  8348. \fi}
  8349. \end{tcolorbox}
  8350. \caption{Translation from \LangIf{} to \LangCIf{}
  8351. via the \code{explicate\_control}.}
  8352. \label{fig:explicate-control-s1-38}
  8353. \end{figure}
  8354. {\if\edition\racketEd
  8355. %
  8356. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8357. \code{explicate\_control} for \LangVar{} using two recursive
  8358. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8359. former function translates expressions in tail position, whereas the
  8360. latter function translates expressions on the right-hand side of a
  8361. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8362. have a new kind of position to deal with: the predicate position of
  8363. the \key{if}. We need another function, \code{explicate\_pred}, that
  8364. decides how to compile an \key{if} by analyzing its condition. So,
  8365. \code{explicate\_pred} takes an \LangIf{} expression and two
  8366. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8367. and outputs a tail. In the following paragraphs we discuss specific
  8368. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8369. \code{explicate\_pred} functions.
  8370. %
  8371. \fi}
  8372. %
  8373. {\if\edition\pythonEd
  8374. %
  8375. We recommend implementing \code{explicate\_control} using the
  8376. following four auxiliary functions.
  8377. \begin{description}
  8378. \item[\code{explicate\_effect}] generates code for expressions as
  8379. statements, so their result is ignored and only their side effects
  8380. matter.
  8381. \item[\code{explicate\_assign}] generates code for expressions
  8382. on the right-hand side of an assignment.
  8383. \item[\code{explicate\_pred}] generates code for an \code{if}
  8384. expression or statement by analyzing the condition expression.
  8385. \item[\code{explicate\_stmt}] generates code for statements.
  8386. \end{description}
  8387. These four functions should build the dictionary of basic blocks. The
  8388. following auxiliary function can be used to create a new basic block
  8389. from a list of statements. It returns a \code{goto} statement that
  8390. jumps to the new basic block.
  8391. \begin{center}
  8392. \begin{minipage}{\textwidth}
  8393. \begin{lstlisting}
  8394. def create_block(stmts, basic_blocks):
  8395. label = label_name(generate_name('block'))
  8396. basic_blocks[label] = stmts
  8397. return Goto(label)
  8398. \end{lstlisting}
  8399. \end{minipage}
  8400. \end{center}
  8401. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8402. \code{explicate\_control} pass.
  8403. The \code{explicate\_effect} function has three parameters: 1) the
  8404. expression to be compiled, 2) the already-compiled code for this
  8405. expression's \emph{continuation}, that is, the list of statements that
  8406. should execute after this expression, and 3) the dictionary of
  8407. generated basic blocks. The \code{explicate\_effect} function returns
  8408. a list of \LangCIf{} statements and it may add to the dictionary of
  8409. basic blocks.
  8410. %
  8411. Let's consider a few of the cases for the expression to be compiled.
  8412. If the expression to be compiled is a constant, then it can be
  8413. discarded because it has no side effects. If it's a \CREAD{}, then it
  8414. has a side-effect and should be preserved. So the expression should be
  8415. translated into a statement using the \code{Expr} AST class. If the
  8416. expression to be compiled is an \code{if} expression, we translate the
  8417. two branches using \code{explicate\_effect} and then translate the
  8418. condition expression using \code{explicate\_pred}, which generates
  8419. code for the entire \code{if}.
  8420. The \code{explicate\_assign} function has four parameters: 1) the
  8421. right-hand side of the assignment, 2) the left-hand side of the
  8422. assignment (the variable), 3) the continuation, and 4) the dictionary
  8423. of basic blocks. The \code{explicate\_assign} function returns a list
  8424. of \LangCIf{} statements and it may add to the dictionary of basic
  8425. blocks.
  8426. When the right-hand side is an \code{if} expression, there is some
  8427. work to do. In particular, the two branches should be translated using
  8428. \code{explicate\_assign} and the condition expression should be
  8429. translated using \code{explicate\_pred}. Otherwise we can simply
  8430. generate an assignment statement, with the given left and right-hand
  8431. sides, concatenated with its continuation.
  8432. \begin{figure}[tbp]
  8433. \begin{tcolorbox}[colback=white]
  8434. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8435. def explicate_effect(e, cont, basic_blocks):
  8436. match e:
  8437. case IfExp(test, body, orelse):
  8438. ...
  8439. case Call(func, args):
  8440. ...
  8441. case Begin(body, result):
  8442. ...
  8443. case _:
  8444. ...
  8445. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8446. match rhs:
  8447. case IfExp(test, body, orelse):
  8448. ...
  8449. case Begin(body, result):
  8450. ...
  8451. case _:
  8452. return [Assign([lhs], rhs)] + cont
  8453. def explicate_pred(cnd, thn, els, basic_blocks):
  8454. match cnd:
  8455. case Compare(left, [op], [right]):
  8456. goto_thn = create_block(thn, basic_blocks)
  8457. goto_els = create_block(els, basic_blocks)
  8458. return [If(cnd, [goto_thn], [goto_els])]
  8459. case Constant(True):
  8460. return thn;
  8461. case Constant(False):
  8462. return els;
  8463. case UnaryOp(Not(), operand):
  8464. ...
  8465. case IfExp(test, body, orelse):
  8466. ...
  8467. case Begin(body, result):
  8468. ...
  8469. case _:
  8470. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8471. [create_block(els, basic_blocks)],
  8472. [create_block(thn, basic_blocks)])]
  8473. def explicate_stmt(s, cont, basic_blocks):
  8474. match s:
  8475. case Assign([lhs], rhs):
  8476. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8477. case Expr(value):
  8478. return explicate_effect(value, cont, basic_blocks)
  8479. case If(test, body, orelse):
  8480. ...
  8481. def explicate_control(p):
  8482. match p:
  8483. case Module(body):
  8484. new_body = [Return(Constant(0))]
  8485. basic_blocks = {}
  8486. for s in reversed(body):
  8487. new_body = explicate_stmt(s, new_body, basic_blocks)
  8488. basic_blocks[label_name('start')] = new_body
  8489. return CProgram(basic_blocks)
  8490. \end{lstlisting}
  8491. \end{tcolorbox}
  8492. \caption{Skeleton for the \code{explicate\_control} pass.}
  8493. \label{fig:explicate-control-Lif}
  8494. \end{figure}
  8495. \fi}
  8496. {\if\edition\racketEd
  8497. \subsection{Explicate Tail and Assign}
  8498. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8499. additional cases for Boolean constants and \key{if}. The cases for
  8500. \code{if} should recursively compile the two branches using either
  8501. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8502. cases should then invoke \code{explicate\_pred} on the condition
  8503. expression, passing in the generated code for the two branches. For
  8504. example, consider the following program with an \code{if} in tail
  8505. position.
  8506. % cond_test_6.rkt
  8507. \begin{lstlisting}
  8508. (let ([x (read)])
  8509. (if (eq? x 0) 42 777))
  8510. \end{lstlisting}
  8511. The two branches are recursively compiled to return statements. We
  8512. then delegate to \code{explicate\_pred}, passing the condition
  8513. \code{(eq? x 0)} and the two return statements. We return to this
  8514. example shortly when we discuss \code{explicate\_pred}.
  8515. Next let us consider a program with an \code{if} on the right-hand
  8516. side of a \code{let}.
  8517. \begin{lstlisting}
  8518. (let ([y (read)])
  8519. (let ([x (if (eq? y 0) 40 777)])
  8520. (+ x 2)))
  8521. \end{lstlisting}
  8522. Note that the body of the inner \code{let} will have already been
  8523. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8524. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8525. to recursively process both branches of the \code{if}, and we do not
  8526. want to duplicate code, so we generate the following block using an
  8527. auxiliary function named \code{create\_block}, discussed in the next
  8528. section.
  8529. \begin{lstlisting}
  8530. block_6:
  8531. return (+ x 2)
  8532. \end{lstlisting}
  8533. We then use \code{goto block\_6;} as the \code{cont} argument for
  8534. compiling the branches. So the two branches compile to
  8535. \begin{center}
  8536. \begin{minipage}{0.2\textwidth}
  8537. \begin{lstlisting}
  8538. x = 40;
  8539. goto block_6;
  8540. \end{lstlisting}
  8541. \end{minipage}
  8542. \hspace{0.5in} and \hspace{0.5in}
  8543. \begin{minipage}{0.2\textwidth}
  8544. \begin{lstlisting}
  8545. x = 777;
  8546. goto block_6;
  8547. \end{lstlisting}
  8548. \end{minipage}
  8549. \end{center}
  8550. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8551. \code{(eq? y 0)} and the previously presented code for the branches.
  8552. \subsection{Create Block}
  8553. We recommend implementing the \code{create\_block} auxiliary function
  8554. as follows, using a global variable \code{basic-blocks} to store a
  8555. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8556. that \code{create\_block} generates a new label and then associates
  8557. the given \code{tail} with the new label in the \code{basic-blocks}
  8558. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8559. new label. However, if the given \code{tail} is already a \code{Goto},
  8560. then there is no need to generate a new label and entry in
  8561. \code{basic-blocks}; we can simply return that \code{Goto}.
  8562. %
  8563. \begin{lstlisting}
  8564. (define (create_block tail)
  8565. (match tail
  8566. [(Goto label) (Goto label)]
  8567. [else
  8568. (let ([label (gensym 'block)])
  8569. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8570. (Goto label))]))
  8571. \end{lstlisting}
  8572. \fi}
  8573. {\if\edition\racketEd
  8574. \subsection{Explicate Predicate}
  8575. \begin{figure}[tbp]
  8576. \begin{tcolorbox}[colback=white]
  8577. \begin{lstlisting}
  8578. (define (explicate_pred cnd thn els)
  8579. (match cnd
  8580. [(Var x) ___]
  8581. [(Let x rhs body) ___]
  8582. [(Prim 'not (list e)) ___]
  8583. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8584. (IfStmt (Prim op es) (create_block thn)
  8585. (create_block els))]
  8586. [(Bool b) (if b thn els)]
  8587. [(If cnd^ thn^ els^) ___]
  8588. [else (error "explicate_pred unhandled case" cnd)]))
  8589. \end{lstlisting}
  8590. \end{tcolorbox}
  8591. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8592. \label{fig:explicate-pred}
  8593. \end{figure}
  8594. \fi}
  8595. \racket{The skeleton for the \code{explicate\_pred} function is given
  8596. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  8597. (1) \code{cnd}, the condition expression of the \code{if};
  8598. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  8599. and (3) \code{els}, the code generated by
  8600. explicate for the \emph{else} branch. The \code{explicate\_pred}
  8601. function should match on \code{cnd} with a case for
  8602. every kind of expression that can have type \BOOLTY{}.}
  8603. %
  8604. \python{The \code{explicate\_pred} function has four parameters: 1)
  8605. the condition expression, 2) the generated statements for the
  8606. ``then'' branch, 3) the generated statements for the ``else''
  8607. branch, and 4) the dictionary of basic blocks. The
  8608. \code{explicate\_pred} function returns a list of \LangCIf{}
  8609. statements and it may add to the dictionary of basic blocks.}
  8610. Consider the case for comparison operators. We translate the
  8611. comparison to an \code{if} statement whose branches are \code{goto}
  8612. statements created by applying \code{create\_block} to the code
  8613. generated for the \code{thn} and \code{els} branches. Let us
  8614. illustrate this translation by returning to the program with an
  8615. \code{if} expression in tail position, shown next. We invoke
  8616. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  8617. \python{\code{x == 0}}.
  8618. %
  8619. {\if\edition\racketEd
  8620. \begin{lstlisting}
  8621. (let ([x (read)])
  8622. (if (eq? x 0) 42 777))
  8623. \end{lstlisting}
  8624. \fi}
  8625. %
  8626. {\if\edition\pythonEd
  8627. \begin{lstlisting}
  8628. x = input_int()
  8629. 42 if x == 0 else 777
  8630. \end{lstlisting}
  8631. \fi}
  8632. %
  8633. \noindent The two branches \code{42} and \code{777} were already
  8634. compiled to \code{return} statements, from which we now create the
  8635. following blocks:
  8636. %
  8637. \begin{center}
  8638. \begin{minipage}{\textwidth}
  8639. \begin{lstlisting}
  8640. block_1:
  8641. return 42;
  8642. block_2:
  8643. return 777;
  8644. \end{lstlisting}
  8645. \end{minipage}
  8646. \end{center}
  8647. %
  8648. After that, \code{explicate\_pred} compiles the comparison
  8649. \racket{\code{(eq? x 0)}}
  8650. \python{\code{x == 0}}
  8651. to the following \code{if} statement:
  8652. %
  8653. {\if\edition\racketEd
  8654. \begin{center}
  8655. \begin{minipage}{\textwidth}
  8656. \begin{lstlisting}
  8657. if (eq? x 0)
  8658. goto block_1;
  8659. else
  8660. goto block_2;
  8661. \end{lstlisting}
  8662. \end{minipage}
  8663. \end{center}
  8664. \fi}
  8665. {\if\edition\pythonEd
  8666. \begin{center}
  8667. \begin{minipage}{\textwidth}
  8668. \begin{lstlisting}
  8669. if x == 0:
  8670. goto block_1;
  8671. else
  8672. goto block_2;
  8673. \end{lstlisting}
  8674. \end{minipage}
  8675. \end{center}
  8676. \fi}
  8677. Next consider the case for Boolean constants. We perform a kind of
  8678. partial evaluation\index{subject}{partial evaluation} and output
  8679. either the \code{thn} or \code{els} branch, depending on whether the
  8680. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8681. following program:
  8682. {\if\edition\racketEd
  8683. \begin{lstlisting}
  8684. (if #t 42 777)
  8685. \end{lstlisting}
  8686. \fi}
  8687. {\if\edition\pythonEd
  8688. \begin{lstlisting}
  8689. 42 if True else 777
  8690. \end{lstlisting}
  8691. \fi}
  8692. %
  8693. \noindent Again, the two branches \code{42} and \code{777} were
  8694. compiled to \code{return} statements, so \code{explicate\_pred}
  8695. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8696. code for the \emph{then} branch.
  8697. \begin{lstlisting}
  8698. return 42;
  8699. \end{lstlisting}
  8700. This case demonstrates that we sometimes discard the \code{thn} or
  8701. \code{els} blocks that are input to \code{explicate\_pred}.
  8702. The case for \key{if} expressions in \code{explicate\_pred} is
  8703. particularly illuminating because it deals with the challenges
  8704. discussed previously regarding nested \key{if} expressions
  8705. (figure~\ref{fig:explicate-control-s1-38}). The
  8706. \racket{\lstinline{thn^}}\python{\code{body}} and
  8707. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8708. \key{if} inherit their context from the current one, that is,
  8709. predicate context. So, you should recursively apply
  8710. \code{explicate\_pred} to the
  8711. \racket{\lstinline{thn^}}\python{\code{body}} and
  8712. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8713. those recursive calls, pass \code{thn} and \code{els} as the extra
  8714. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8715. inside each recursive call. As discussed previously, to avoid
  8716. duplicating code, we need to add them to the dictionary of basic
  8717. blocks so that we can instead refer to them by name and execute them
  8718. with a \key{goto}.
  8719. {\if\edition\pythonEd
  8720. %
  8721. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8722. three parameters: 1) the statement to be compiled, 2) the code for its
  8723. continuation, and 3) the dictionary of basic blocks. The
  8724. \code{explicate\_stmt} returns a list of statements and it may add to
  8725. the dictionary of basic blocks. The cases for assignment and an
  8726. expression-statement are given in full in the skeleton code: they
  8727. simply dispatch to \code{explicate\_assign} and
  8728. \code{explicate\_effect}, respectively. The case for \code{if}
  8729. statements is not given, and is similar to the case for \code{if}
  8730. expressions.
  8731. The \code{explicate\_control} function itself is given in
  8732. figure~\ref{fig:explicate-control-Lif}. It applies
  8733. \code{explicate\_stmt} to each statement in the program, from back to
  8734. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8735. used as the continuation parameter in the next call to
  8736. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8737. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8738. the dictionary of basic blocks, labeling it as the ``start'' block.
  8739. %
  8740. \fi}
  8741. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8742. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8743. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8744. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8745. %% results from the two recursive calls. We complete the case for
  8746. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8747. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8748. %% the result $B_5$.
  8749. %% \[
  8750. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8751. %% \quad\Rightarrow\quad
  8752. %% B_5
  8753. %% \]
  8754. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8755. %% inherit the current context, so they are in tail position. Thus, the
  8756. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8757. %% \code{explicate\_tail}.
  8758. %% %
  8759. %% We need to pass $B_0$ as the accumulator argument for both of these
  8760. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8761. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8762. %% to the control-flow graph and obtain a promised goto $G_0$.
  8763. %% %
  8764. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8765. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8766. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8767. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8768. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8769. %% \[
  8770. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8771. %% \]
  8772. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8773. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8774. %% should not be confused with the labels for the blocks that appear in
  8775. %% the generated code. We initially construct unlabeled blocks; we only
  8776. %% attach labels to blocks when we add them to the control-flow graph, as
  8777. %% we see in the next case.
  8778. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8779. %% function. The context of the \key{if} is an assignment to some
  8780. %% variable $x$ and then the control continues to some promised block
  8781. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8782. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8783. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8784. %% branches of the \key{if} inherit the current context, so they are in
  8785. %% assignment positions. Let $B_2$ be the result of applying
  8786. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8787. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8788. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8789. %% the result of applying \code{explicate\_pred} to the predicate
  8790. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8791. %% translates to the promise $B_4$.
  8792. %% \[
  8793. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8794. %% \]
  8795. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8796. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8797. \code{remove\_complex\_operands} pass and then the
  8798. \code{explicate\_control} pass on the example program. We walk through
  8799. the output program.
  8800. %
  8801. Following the order of evaluation in the output of
  8802. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8803. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8804. in the predicate of the inner \key{if}. In the output of
  8805. \code{explicate\_control}, in the
  8806. block labeled \code{start}, two assignment statements are followed by an
  8807. \code{if} statement that branches to \code{block\_4} or
  8808. \code{block\_5}. The blocks associated with those labels contain the
  8809. translations of the code
  8810. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8811. and
  8812. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8813. respectively. In particular, we start \code{block\_4} with the
  8814. comparison
  8815. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8816. and then branch to \code{block\_2} or \code{block\_3},
  8817. which correspond to the two branches of the outer \key{if}, that is,
  8818. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8819. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8820. %
  8821. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8822. %
  8823. \python{The \code{block\_1} corresponds to the \code{print} statement
  8824. at the end of the program.}
  8825. {\if\edition\racketEd
  8826. \subsection{Interactions between Explicate and Shrink}
  8827. The way in which the \code{shrink} pass transforms logical operations
  8828. such as \code{and} and \code{or} can impact the quality of code
  8829. generated by \code{explicate\_control}. For example, consider the
  8830. following program:
  8831. % cond_test_21.rkt, and_eq_input.py
  8832. \begin{lstlisting}
  8833. (if (and (eq? (read) 0) (eq? (read) 1))
  8834. 0
  8835. 42)
  8836. \end{lstlisting}
  8837. The \code{and} operation should transform into something that the
  8838. \code{explicate\_pred} function can analyze and descend through to
  8839. reach the underlying \code{eq?} conditions. Ideally, for this program
  8840. your \code{explicate\_control} pass should generate code similar to
  8841. the following:
  8842. \begin{center}
  8843. \begin{minipage}{\textwidth}
  8844. \begin{lstlisting}
  8845. start:
  8846. tmp1 = (read);
  8847. if (eq? tmp1 0) goto block40;
  8848. else goto block39;
  8849. block40:
  8850. tmp2 = (read);
  8851. if (eq? tmp2 1) goto block38;
  8852. else goto block39;
  8853. block38:
  8854. return 0;
  8855. block39:
  8856. return 42;
  8857. \end{lstlisting}
  8858. \end{minipage}
  8859. \end{center}
  8860. \fi}
  8861. \begin{exercise}\normalfont\normalsize
  8862. \racket{
  8863. Implement the pass \code{explicate\_control} by adding the cases for
  8864. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8865. \code{explicate\_assign} functions. Implement the auxiliary function
  8866. \code{explicate\_pred} for predicate contexts.}
  8867. \python{Implement \code{explicate\_control} pass with its
  8868. four auxiliary functions.}
  8869. %
  8870. Create test cases that exercise all the new cases in the code for
  8871. this pass.
  8872. %
  8873. {\if\edition\racketEd
  8874. Add the following entry to the list of \code{passes} in
  8875. \code{run-tests.rkt}:
  8876. \begin{lstlisting}
  8877. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8878. \end{lstlisting}
  8879. and then run \code{run-tests.rkt} to test your compiler.
  8880. \fi}
  8881. \end{exercise}
  8882. \section{Select Instructions}
  8883. \label{sec:select-Lif}
  8884. \index{subject}{instruction selection}
  8885. The \code{select\_instructions} pass translates \LangCIf{} to
  8886. \LangXIfVar{}.
  8887. %
  8888. \racket{Recall that we implement this pass using three auxiliary
  8889. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8890. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8891. %
  8892. \racket{For $\Atm$, we have new cases for the Booleans.}
  8893. %
  8894. \python{We begin with the Boolean constants.}
  8895. We take the usual approach of encoding them as integers.
  8896. \[
  8897. \TRUE{} \quad\Rightarrow\quad \key{1}
  8898. \qquad\qquad
  8899. \FALSE{} \quad\Rightarrow\quad \key{0}
  8900. \]
  8901. For translating statements, we discuss some of the cases. The
  8902. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8903. discussed at the beginning of this section. Given an assignment, if
  8904. the left-hand-side variable is the same as the argument of \code{not},
  8905. then just the \code{xorq} instruction suffices.
  8906. \[
  8907. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8908. \quad\Rightarrow\quad
  8909. \key{xorq}~\key{\$}1\key{,}~\Var
  8910. \]
  8911. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8912. semantics of x86. In the following translation, let $\Arg$ be the
  8913. result of translating $\Atm$ to x86.
  8914. \[
  8915. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8916. \quad\Rightarrow\quad
  8917. \begin{array}{l}
  8918. \key{movq}~\Arg\key{,}~\Var\\
  8919. \key{xorq}~\key{\$}1\key{,}~\Var
  8920. \end{array}
  8921. \]
  8922. Next consider the cases for equality comparisons. Translating this
  8923. operation to x86 is slightly involved due to the unusual nature of the
  8924. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8925. We recommend translating an assignment with an equality on the
  8926. right-hand side into a sequence of three instructions. \\
  8927. \begin{tabular}{lll}
  8928. \begin{minipage}{0.4\textwidth}
  8929. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8930. \end{minipage}
  8931. &
  8932. $\Rightarrow$
  8933. &
  8934. \begin{minipage}{0.4\textwidth}
  8935. \begin{lstlisting}
  8936. cmpq |$\Arg_2$|, |$\Arg_1$|
  8937. sete %al
  8938. movzbq %al, |$\Var$|
  8939. \end{lstlisting}
  8940. \end{minipage}
  8941. \end{tabular} \\
  8942. The translations for the other comparison operators are similar to
  8943. this but use different condition codes for the \code{set} instruction.
  8944. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8945. \key{goto} and \key{if} statements. Both are straightforward to
  8946. translate to x86.}
  8947. %
  8948. A \key{goto} statement becomes a jump instruction.
  8949. \[
  8950. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8951. \]
  8952. %
  8953. An \key{if} statement becomes a compare instruction followed by a
  8954. conditional jump (for the \emph{then} branch), and the fall-through is to
  8955. a regular jump (for the \emph{else} branch).\\
  8956. \begin{tabular}{lll}
  8957. \begin{minipage}{0.4\textwidth}
  8958. \begin{lstlisting}
  8959. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8960. goto |$\ell_1$||$\racket{\key{;}}$|
  8961. else|$\python{\key{:}}$|
  8962. goto |$\ell_2$||$\racket{\key{;}}$|
  8963. \end{lstlisting}
  8964. \end{minipage}
  8965. &
  8966. $\Rightarrow$
  8967. &
  8968. \begin{minipage}{0.4\textwidth}
  8969. \begin{lstlisting}
  8970. cmpq |$\Arg_2$|, |$\Arg_1$|
  8971. je |$\ell_1$|
  8972. jmp |$\ell_2$|
  8973. \end{lstlisting}
  8974. \end{minipage}
  8975. \end{tabular} \\
  8976. Again, the translations for the other comparison operators are similar to this
  8977. but use different condition codes for the conditional jump instruction.
  8978. \python{Regarding the \key{return} statement, we recommend treating it
  8979. as an assignment to the \key{rax} register followed by a jump to the
  8980. conclusion of the \code{main} function.}
  8981. \begin{exercise}\normalfont\normalsize
  8982. Expand your \code{select\_instructions} pass to handle the new
  8983. features of the \LangCIf{} language.
  8984. %
  8985. {\if\edition\racketEd
  8986. Add the following entry to the list of \code{passes} in
  8987. \code{run-tests.rkt}
  8988. \begin{lstlisting}
  8989. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8990. \end{lstlisting}
  8991. \fi}
  8992. %
  8993. Run the script to test your compiler on all the test programs.
  8994. \end{exercise}
  8995. \section{Register Allocation}
  8996. \label{sec:register-allocation-Lif}
  8997. \index{subject}{register allocation}
  8998. The changes required for compiling \LangIf{} affect liveness analysis,
  8999. building the interference graph, and assigning homes, but the graph
  9000. coloring algorithm itself does not change.
  9001. \subsection{Liveness Analysis}
  9002. \label{sec:liveness-analysis-Lif}
  9003. \index{subject}{liveness analysis}
  9004. Recall that for \LangVar{} we implemented liveness analysis for a
  9005. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9006. the addition of \key{if} expressions to \LangIf{},
  9007. \code{explicate\_control} produces many basic blocks.
  9008. %% We recommend that you create a new auxiliary function named
  9009. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9010. %% control-flow graph.
  9011. The first question is, in what order should we process the basic blocks?
  9012. Recall that to perform liveness analysis on a basic block we need to
  9013. know the live-after set for the last instruction in the block. If a
  9014. basic block has no successors (i.e., contains no jumps to other
  9015. blocks), then it has an empty live-after set and we can immediately
  9016. apply liveness analysis to it. If a basic block has some successors,
  9017. then we need to complete liveness analysis on those blocks
  9018. first. These ordering constraints are the reverse of a
  9019. \emph{topological order}\index{subject}{topological order} on a graph
  9020. representation of the program. In particular, the \emph{control flow
  9021. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9022. of a program has a node for each basic block and an edge for each jump
  9023. from one block to another. It is straightforward to generate a CFG
  9024. from the dictionary of basic blocks. One then transposes the CFG and
  9025. applies the topological sort algorithm.
  9026. %
  9027. %
  9028. \racket{We recommend using the \code{tsort} and \code{transpose}
  9029. functions of the Racket \code{graph} package to accomplish this.}
  9030. %
  9031. \python{We provide implementations of \code{topological\_sort} and
  9032. \code{transpose} in the file \code{graph.py} of the support code.}
  9033. %
  9034. As an aside, a topological ordering is only guaranteed to exist if the
  9035. graph does not contain any cycles. This is the case for the
  9036. control-flow graphs that we generate from \LangIf{} programs.
  9037. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9038. and learn how to handle cycles in the control-flow graph.
  9039. \racket{You need to construct a directed graph to represent the
  9040. control-flow graph. Do not use the \code{directed-graph} of the
  9041. \code{graph} package because that allows at most one edge
  9042. between each pair of vertices, whereas a control-flow graph may have
  9043. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9044. file in the support code implements a graph representation that
  9045. allows multiple edges between a pair of vertices.}
  9046. {\if\edition\racketEd
  9047. The next question is how to analyze jump instructions. Recall that in
  9048. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9049. \code{label->live} that maps each label to the set of live locations
  9050. at the beginning of its block. We use \code{label->live} to determine
  9051. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9052. that we have many basic blocks, \code{label->live} needs to be updated
  9053. as we process the blocks. In particular, after performing liveness
  9054. analysis on a block, we take the live-before set of its first
  9055. instruction and associate that with the block's label in the
  9056. \code{label->live} alist.
  9057. \fi}
  9058. %
  9059. {\if\edition\pythonEd
  9060. %
  9061. The next question is how to analyze jump instructions. The locations
  9062. that are live before a \code{jmp} should be the locations in
  9063. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9064. maintaining a dictionary named \code{live\_before\_block} that maps each
  9065. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9066. block. After performing liveness analysis on each block, we take the
  9067. live-before set of its first instruction and associate that with the
  9068. block's label in the \code{live\_before\_block} dictionary.
  9069. %
  9070. \fi}
  9071. In \LangXIfVar{} we also have the conditional jump
  9072. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9073. this instruction is particularly interesting because during
  9074. compilation, we do not know which way a conditional jump will go. Thus
  9075. we do not know whether to use the live-before set for the block
  9076. associated with the $\itm{label}$ or the live-before set for the
  9077. following instruction. However, there is no harm to the correctness
  9078. of the generated code if we classify more locations as live than the
  9079. ones that are truly live during one particular execution of the
  9080. instruction. Thus, we can take the union of the live-before sets from
  9081. the following instruction and from the mapping for $\itm{label}$ in
  9082. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9083. The auxiliary functions for computing the variables in an
  9084. instruction's argument and for computing the variables read-from ($R$)
  9085. or written-to ($W$) by an instruction need to be updated to handle the
  9086. new kinds of arguments and instructions in \LangXIfVar{}.
  9087. \begin{exercise}\normalfont\normalsize
  9088. {\if\edition\racketEd
  9089. %
  9090. Update the \code{uncover\_live} pass to apply liveness analysis to
  9091. every basic block in the program.
  9092. %
  9093. Add the following entry to the list of \code{passes} in the
  9094. \code{run-tests.rkt} script:
  9095. \begin{lstlisting}
  9096. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9097. \end{lstlisting}
  9098. \fi}
  9099. {\if\edition\pythonEd
  9100. %
  9101. Update the \code{uncover\_live} function to perform liveness analysis,
  9102. in reverse topological order, on all the basic blocks in the
  9103. program.
  9104. %
  9105. \fi}
  9106. % Check that the live-after sets that you generate for
  9107. % example X matches the following... -Jeremy
  9108. \end{exercise}
  9109. \subsection{Build the Interference Graph}
  9110. \label{sec:build-interference-Lif}
  9111. Many of the new instructions in \LangXIfVar{} can be handled in the
  9112. same way as the instructions in \LangXVar{}.
  9113. % Thus, if your code was
  9114. % already quite general, it will not need to be changed to handle the
  9115. % new instructions. If your code is not general enough, we recommend that
  9116. % you change your code to be more general. For example, you can factor
  9117. % out the computing of the the read and write sets for each kind of
  9118. % instruction into auxiliary functions.
  9119. %
  9120. Some instructions, such as the \key{movzbq} instruction, require special care,
  9121. similar to the \key{movq} instruction. Refer to rule number 1 in
  9122. section~\ref{sec:build-interference}.
  9123. \begin{exercise}\normalfont\normalsize
  9124. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9125. {\if\edition\racketEd
  9126. Add the following entries to the list of \code{passes} in the
  9127. \code{run-tests.rkt} script:
  9128. \begin{lstlisting}
  9129. (list "build_interference" build_interference interp-pseudo-x86-1)
  9130. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9131. \end{lstlisting}
  9132. \fi}
  9133. % Check that the interference graph that you generate for
  9134. % example X matches the following graph G... -Jeremy
  9135. \end{exercise}
  9136. \section{Patch Instructions}
  9137. The new instructions \key{cmpq} and \key{movzbq} have some special
  9138. restrictions that need to be handled in the \code{patch\_instructions}
  9139. pass.
  9140. %
  9141. The second argument of the \key{cmpq} instruction must not be an
  9142. immediate value (such as an integer). So, if you are comparing two
  9143. immediates, we recommend inserting a \key{movq} instruction to put the
  9144. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  9145. one memory reference.
  9146. %
  9147. The second argument of the \key{movzbq} must be a register.
  9148. \begin{exercise}\normalfont\normalsize
  9149. %
  9150. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9151. %
  9152. {\if\edition\racketEd
  9153. Add the following entry to the list of \code{passes} in
  9154. \code{run-tests.rkt}, and then run this script to test your compiler.
  9155. \begin{lstlisting}
  9156. (list "patch_instructions" patch_instructions interp-x86-1)
  9157. \end{lstlisting}
  9158. \fi}
  9159. \end{exercise}
  9160. {\if\edition\pythonEd
  9161. \section{Prelude and Conclusion}
  9162. \label{sec:prelude-conclusion-cond}
  9163. The generation of the \code{main} function with its prelude and
  9164. conclusion must change to accommodate how the program now consists of
  9165. one or more basic blocks. After the prelude in \code{main}, jump to
  9166. the \code{start} block. Place the conclusion in a basic block labeled
  9167. with \code{conclusion}.
  9168. \fi}
  9169. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9170. \LangIf{} translated to x86, showing the results of
  9171. \code{explicate\_control}, \code{select\_instructions}, and the final
  9172. x86 assembly.
  9173. \begin{figure}[tbp]
  9174. \begin{tcolorbox}[colback=white]
  9175. {\if\edition\racketEd
  9176. \begin{tabular}{lll}
  9177. \begin{minipage}{0.4\textwidth}
  9178. % cond_test_20.rkt, eq_input.py
  9179. \begin{lstlisting}
  9180. (if (eq? (read) 1) 42 0)
  9181. \end{lstlisting}
  9182. $\Downarrow$
  9183. \begin{lstlisting}
  9184. start:
  9185. tmp7951 = (read);
  9186. if (eq? tmp7951 1)
  9187. goto block7952;
  9188. else
  9189. goto block7953;
  9190. block7952:
  9191. return 42;
  9192. block7953:
  9193. return 0;
  9194. \end{lstlisting}
  9195. $\Downarrow$
  9196. \begin{lstlisting}
  9197. start:
  9198. callq read_int
  9199. movq %rax, tmp7951
  9200. cmpq $1, tmp7951
  9201. je block7952
  9202. jmp block7953
  9203. block7953:
  9204. movq $0, %rax
  9205. jmp conclusion
  9206. block7952:
  9207. movq $42, %rax
  9208. jmp conclusion
  9209. \end{lstlisting}
  9210. \end{minipage}
  9211. &
  9212. $\Rightarrow\qquad$
  9213. \begin{minipage}{0.4\textwidth}
  9214. \begin{lstlisting}
  9215. start:
  9216. callq read_int
  9217. movq %rax, %rcx
  9218. cmpq $1, %rcx
  9219. je block7952
  9220. jmp block7953
  9221. block7953:
  9222. movq $0, %rax
  9223. jmp conclusion
  9224. block7952:
  9225. movq $42, %rax
  9226. jmp conclusion
  9227. .globl main
  9228. main:
  9229. pushq %rbp
  9230. movq %rsp, %rbp
  9231. pushq %r13
  9232. pushq %r12
  9233. pushq %rbx
  9234. pushq %r14
  9235. subq $0, %rsp
  9236. jmp start
  9237. conclusion:
  9238. addq $0, %rsp
  9239. popq %r14
  9240. popq %rbx
  9241. popq %r12
  9242. popq %r13
  9243. popq %rbp
  9244. retq
  9245. \end{lstlisting}
  9246. \end{minipage}
  9247. \end{tabular}
  9248. \fi}
  9249. {\if\edition\pythonEd
  9250. \begin{tabular}{lll}
  9251. \begin{minipage}{0.4\textwidth}
  9252. % cond_test_20.rkt, eq_input.py
  9253. \begin{lstlisting}
  9254. print(42 if input_int() == 1 else 0)
  9255. \end{lstlisting}
  9256. $\Downarrow$
  9257. \begin{lstlisting}
  9258. start:
  9259. tmp_0 = input_int()
  9260. if tmp_0 == 1:
  9261. goto block_3
  9262. else:
  9263. goto block_4
  9264. block_3:
  9265. tmp_1 = 42
  9266. goto block_2
  9267. block_4:
  9268. tmp_1 = 0
  9269. goto block_2
  9270. block_2:
  9271. print(tmp_1)
  9272. return 0
  9273. \end{lstlisting}
  9274. $\Downarrow$
  9275. \begin{lstlisting}
  9276. start:
  9277. callq read_int
  9278. movq %rax, tmp_0
  9279. cmpq 1, tmp_0
  9280. je block_3
  9281. jmp block_4
  9282. block_3:
  9283. movq 42, tmp_1
  9284. jmp block_2
  9285. block_4:
  9286. movq 0, tmp_1
  9287. jmp block_2
  9288. block_2:
  9289. movq tmp_1, %rdi
  9290. callq print_int
  9291. movq 0, %rax
  9292. jmp conclusion
  9293. \end{lstlisting}
  9294. \end{minipage}
  9295. &
  9296. $\Rightarrow\qquad$
  9297. \begin{minipage}{0.4\textwidth}
  9298. \begin{lstlisting}
  9299. .globl main
  9300. main:
  9301. pushq %rbp
  9302. movq %rsp, %rbp
  9303. subq $0, %rsp
  9304. jmp start
  9305. start:
  9306. callq read_int
  9307. movq %rax, %rcx
  9308. cmpq $1, %rcx
  9309. je block_3
  9310. jmp block_4
  9311. block_3:
  9312. movq $42, %rcx
  9313. jmp block_2
  9314. block_4:
  9315. movq $0, %rcx
  9316. jmp block_2
  9317. block_2:
  9318. movq %rcx, %rdi
  9319. callq print_int
  9320. movq $0, %rax
  9321. jmp conclusion
  9322. conclusion:
  9323. addq $0, %rsp
  9324. popq %rbp
  9325. retq
  9326. \end{lstlisting}
  9327. \end{minipage}
  9328. \end{tabular}
  9329. \fi}
  9330. \end{tcolorbox}
  9331. \caption{Example compilation of an \key{if} expression to x86, showing
  9332. the results of \code{explicate\_control},
  9333. \code{select\_instructions}, and the final x86 assembly code. }
  9334. \label{fig:if-example-x86}
  9335. \end{figure}
  9336. \begin{figure}[tbp]
  9337. \begin{tcolorbox}[colback=white]
  9338. {\if\edition\racketEd
  9339. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9340. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9341. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9342. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9343. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9344. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9345. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9346. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9347. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9348. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9349. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9350. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9351. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9352. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9353. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9354. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  9355. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9356. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9357. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9358. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9359. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9360. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9361. \end{tikzpicture}
  9362. \fi}
  9363. {\if\edition\pythonEd
  9364. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9365. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9366. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9367. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9368. \node (C-1) at (0,0) {\large \LangCIf{}};
  9369. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9370. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9371. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9372. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9373. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9374. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9375. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  9376. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9377. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9378. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9379. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9380. \end{tikzpicture}
  9381. \fi}
  9382. \end{tcolorbox}
  9383. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9384. \label{fig:Lif-passes}
  9385. \end{figure}
  9386. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9387. compilation of \LangIf{}.
  9388. \section{Challenge: Optimize Blocks and Remove Jumps}
  9389. \label{sec:opt-jumps}
  9390. We discuss two optional challenges that involve optimizing the
  9391. control-flow of the program.
  9392. \subsection{Optimize Blocks}
  9393. The algorithm for \code{explicate\_control} that we discussed in
  9394. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9395. blocks. It creates a basic block whenever a continuation \emph{might}
  9396. get used more than once (e.g., whenever the \code{cont} parameter is
  9397. passed into two or more recursive calls). However, some continuation
  9398. arguments may not be used at all. For example, consider the case for
  9399. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  9400. \code{els} continuation.
  9401. %
  9402. {\if\edition\racketEd
  9403. The following example program falls into this
  9404. case, and it creates two unused blocks.
  9405. \begin{center}
  9406. \begin{tabular}{lll}
  9407. \begin{minipage}{0.4\textwidth}
  9408. % cond_test_82.rkt
  9409. \begin{lstlisting}
  9410. (let ([y (if #t
  9411. (read)
  9412. (if (eq? (read) 0)
  9413. 777
  9414. (let ([x (read)])
  9415. (+ 1 x))))])
  9416. (+ y 2))
  9417. \end{lstlisting}
  9418. \end{minipage}
  9419. &
  9420. $\Rightarrow$
  9421. &
  9422. \begin{minipage}{0.55\textwidth}
  9423. \begin{lstlisting}
  9424. start:
  9425. y = (read);
  9426. goto block_5;
  9427. block_5:
  9428. return (+ y 2);
  9429. block_6:
  9430. y = 777;
  9431. goto block_5;
  9432. block_7:
  9433. x = (read);
  9434. y = (+ 1 x2);
  9435. goto block_5;
  9436. \end{lstlisting}
  9437. \end{minipage}
  9438. \end{tabular}
  9439. \end{center}
  9440. \fi}
  9441. The question is, how can we decide whether to create a basic block?
  9442. \emph{Lazy evaluation}\index{subject}{lazy
  9443. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9444. delaying the creation of a basic block until the point in time at which
  9445. we know that it will be used.
  9446. %
  9447. {\if\edition\racketEd
  9448. %
  9449. Racket provides support for
  9450. lazy evaluation with the
  9451. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9452. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9453. \index{subject}{delay} creates a
  9454. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9455. expressions is postponed. When \key{(force}
  9456. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9457. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9458. result of $e_n$ is cached in the promise and returned. If \code{force}
  9459. is applied again to the same promise, then the cached result is
  9460. returned. If \code{force} is applied to an argument that is not a
  9461. promise, \code{force} simply returns the argument.
  9462. %
  9463. \fi}
  9464. %
  9465. {\if\edition\pythonEd
  9466. %
  9467. While Python does not provide direct support for lazy evaluation, it
  9468. is easy to mimic. We can \emph{delay} the evaluation of a computation
  9469. by wrapping it inside a function with no parameters. We can
  9470. \emph{force} its evaluation by calling the function. However, in some
  9471. cases of \code{explicate\_pred}, etc., we will return a list of
  9472. statements and in other cases we will return a function that computes
  9473. a list of statements. We use the term \emph{promise} to refer to a
  9474. value that may be delayed. To uniformly deal with
  9475. promises, we define the following \code{force} function that checks
  9476. whether its input is delayed (i.e., whether it is a function) and then
  9477. either 1) calls the function, or 2) returns the input.
  9478. \begin{lstlisting}
  9479. def force(promise):
  9480. if isinstance(promise, types.FunctionType):
  9481. return promise()
  9482. else:
  9483. return promise
  9484. \end{lstlisting}
  9485. %
  9486. \fi}
  9487. We use promises for the input and output of the functions
  9488. \code{explicate\_pred}, \code{explicate\_assign},
  9489. %
  9490. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9491. %
  9492. So, instead of taking and returning \racket{$\Tail$
  9493. expressions}\python{lists of statements}, they take and return
  9494. promises. Furthermore, when we come to a situation in which a
  9495. continuation might be used more than once, as in the case for
  9496. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9497. that creates a basic block for each continuation (if there is not
  9498. already one) and then returns a \code{goto} statement to that basic
  9499. block. When we come to a situation in which we have a promise but need an
  9500. actual piece of code, for example, to create a larger piece of code with a
  9501. constructor such as \code{Seq}, then insert a call to \code{force}.
  9502. %
  9503. {\if\edition\racketEd
  9504. %
  9505. Also, we must modify the \code{create\_block} function to begin with
  9506. \code{delay} to create a promise. When forced, this promise forces the
  9507. original promise. If that returns a \code{Goto} (because the block was
  9508. already added to \code{basic-blocks}), then we return the
  9509. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9510. return a \code{Goto} to the new label.
  9511. \begin{center}
  9512. \begin{minipage}{\textwidth}
  9513. \begin{lstlisting}
  9514. (define (create_block tail)
  9515. (delay
  9516. (define t (force tail))
  9517. (match t
  9518. [(Goto label) (Goto label)]
  9519. [else
  9520. (let ([label (gensym 'block)])
  9521. (set! basic-blocks (cons (cons label t) basic-blocks))
  9522. (Goto label))])))
  9523. \end{lstlisting}
  9524. \end{minipage}
  9525. \end{center}
  9526. \fi}
  9527. {\if\edition\pythonEd
  9528. %
  9529. Here is the new version of the \code{create\_block} auxiliary function
  9530. that works on promises and that checks whether the block consists of a
  9531. solitary \code{goto} statement.\\
  9532. \begin{minipage}{\textwidth}
  9533. \begin{lstlisting}
  9534. def create_block(promise, basic_blocks):
  9535. stmts = force(promise)
  9536. match stmts:
  9537. case [Goto(l)]:
  9538. return Goto(l)
  9539. case _:
  9540. label = label_name(generate_name('block'))
  9541. basic_blocks[label] = stmts
  9542. return Goto(label)
  9543. \end{lstlisting}
  9544. \end{minipage}
  9545. \fi}
  9546. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9547. improved \code{explicate\_control} on this example. As you can
  9548. see, the number of basic blocks has been reduced from four blocks (see
  9549. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  9550. \begin{figure}[tbp]
  9551. \begin{tcolorbox}[colback=white]
  9552. {\if\edition\racketEd
  9553. \begin{tabular}{lll}
  9554. \begin{minipage}{0.4\textwidth}
  9555. % cond_test_82.rkt
  9556. \begin{lstlisting}
  9557. (let ([y (if #t
  9558. (read)
  9559. (if (eq? (read) 0)
  9560. 777
  9561. (let ([x (read)])
  9562. (+ 1 x))))])
  9563. (+ y 2))
  9564. \end{lstlisting}
  9565. \end{minipage}
  9566. &
  9567. $\Rightarrow$
  9568. &
  9569. \begin{minipage}{0.55\textwidth}
  9570. \begin{lstlisting}
  9571. start:
  9572. y = (read);
  9573. goto block_5;
  9574. block_5:
  9575. return (+ y 2);
  9576. \end{lstlisting}
  9577. \end{minipage}
  9578. \end{tabular}
  9579. \fi}
  9580. {\if\edition\pythonEd
  9581. \begin{tabular}{lll}
  9582. \begin{minipage}{0.4\textwidth}
  9583. % cond_test_41.rkt
  9584. \begin{lstlisting}
  9585. x = input_int()
  9586. y = input_int()
  9587. print(y + 2 \
  9588. if (x == 0 \
  9589. if x < 1 \
  9590. else x == 2) \
  9591. else y + 10)
  9592. \end{lstlisting}
  9593. \end{minipage}
  9594. &
  9595. $\Rightarrow$
  9596. &
  9597. \begin{minipage}{0.55\textwidth}
  9598. \begin{lstlisting}
  9599. start:
  9600. x = input_int()
  9601. y = input_int()
  9602. if x < 1:
  9603. goto block_4
  9604. else:
  9605. goto block_5
  9606. block_4:
  9607. if x == 0:
  9608. goto block_2
  9609. else:
  9610. goto block_3
  9611. block_5:
  9612. if x == 2:
  9613. goto block_2
  9614. else:
  9615. goto block_3
  9616. block_2:
  9617. tmp_0 = y + 2
  9618. goto block_1
  9619. block_3:
  9620. tmp_0 = y + 10
  9621. goto block_1
  9622. block_1:
  9623. print(tmp_0)
  9624. return 0
  9625. \end{lstlisting}
  9626. \end{minipage}
  9627. \end{tabular}
  9628. \fi}
  9629. \end{tcolorbox}
  9630. \caption{Translation from \LangIf{} to \LangCIf{}
  9631. via the improved \code{explicate\_control}.}
  9632. \label{fig:explicate-control-challenge}
  9633. \end{figure}
  9634. %% Recall that in the example output of \code{explicate\_control} in
  9635. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9636. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9637. %% block. The first goal of this challenge assignment is to remove those
  9638. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9639. %% \code{explicate\_control} on the left and shows the result of bypassing
  9640. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9641. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9642. %% \code{block55}. The optimized code on the right of
  9643. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9644. %% \code{then} branch jumping directly to \code{block55}. The story is
  9645. %% similar for the \code{else} branch, as well as for the two branches in
  9646. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9647. %% have been optimized in this way, there are no longer any jumps to
  9648. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9649. %% \begin{figure}[tbp]
  9650. %% \begin{tabular}{lll}
  9651. %% \begin{minipage}{0.4\textwidth}
  9652. %% \begin{lstlisting}
  9653. %% block62:
  9654. %% tmp54 = (read);
  9655. %% if (eq? tmp54 2) then
  9656. %% goto block59;
  9657. %% else
  9658. %% goto block60;
  9659. %% block61:
  9660. %% tmp53 = (read);
  9661. %% if (eq? tmp53 0) then
  9662. %% goto block57;
  9663. %% else
  9664. %% goto block58;
  9665. %% block60:
  9666. %% goto block56;
  9667. %% block59:
  9668. %% goto block55;
  9669. %% block58:
  9670. %% goto block56;
  9671. %% block57:
  9672. %% goto block55;
  9673. %% block56:
  9674. %% return (+ 700 77);
  9675. %% block55:
  9676. %% return (+ 10 32);
  9677. %% start:
  9678. %% tmp52 = (read);
  9679. %% if (eq? tmp52 1) then
  9680. %% goto block61;
  9681. %% else
  9682. %% goto block62;
  9683. %% \end{lstlisting}
  9684. %% \end{minipage}
  9685. %% &
  9686. %% $\Rightarrow$
  9687. %% &
  9688. %% \begin{minipage}{0.55\textwidth}
  9689. %% \begin{lstlisting}
  9690. %% block62:
  9691. %% tmp54 = (read);
  9692. %% if (eq? tmp54 2) then
  9693. %% goto block55;
  9694. %% else
  9695. %% goto block56;
  9696. %% block61:
  9697. %% tmp53 = (read);
  9698. %% if (eq? tmp53 0) then
  9699. %% goto block55;
  9700. %% else
  9701. %% goto block56;
  9702. %% block56:
  9703. %% return (+ 700 77);
  9704. %% block55:
  9705. %% return (+ 10 32);
  9706. %% start:
  9707. %% tmp52 = (read);
  9708. %% if (eq? tmp52 1) then
  9709. %% goto block61;
  9710. %% else
  9711. %% goto block62;
  9712. %% \end{lstlisting}
  9713. %% \end{minipage}
  9714. %% \end{tabular}
  9715. %% \caption{Optimize jumps by removing trivial blocks.}
  9716. %% \label{fig:optimize-jumps}
  9717. %% \end{figure}
  9718. %% The name of this pass is \code{optimize-jumps}. We recommend
  9719. %% implementing this pass in two phases. The first phrase builds a hash
  9720. %% table that maps labels to possibly improved labels. The second phase
  9721. %% changes the target of each \code{goto} to use the improved label. If
  9722. %% the label is for a trivial block, then the hash table should map the
  9723. %% label to the first non-trivial block that can be reached from this
  9724. %% label by jumping through trivial blocks. If the label is for a
  9725. %% non-trivial block, then the hash table should map the label to itself;
  9726. %% we do not want to change jumps to non-trivial blocks.
  9727. %% The first phase can be accomplished by constructing an empty hash
  9728. %% table, call it \code{short-cut}, and then iterating over the control
  9729. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9730. %% then update the hash table, mapping the block's source to the target
  9731. %% of the \code{goto}. Also, the hash table may already have mapped some
  9732. %% labels to the block's source, to you must iterate through the hash
  9733. %% table and update all of those so that they instead map to the target
  9734. %% of the \code{goto}.
  9735. %% For the second phase, we recommend iterating through the $\Tail$ of
  9736. %% each block in the program, updating the target of every \code{goto}
  9737. %% according to the mapping in \code{short-cut}.
  9738. \begin{exercise}\normalfont\normalsize
  9739. Implement the improvements to the \code{explicate\_control} pass.
  9740. Check that it removes trivial blocks in a few example programs. Then
  9741. check that your compiler still passes all your tests.
  9742. \end{exercise}
  9743. \subsection{Remove Jumps}
  9744. There is an opportunity for removing jumps that is apparent in the
  9745. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9746. ends with a jump to \code{block\_5}, and there are no other jumps to
  9747. \code{block\_5} in the rest of the program. In this situation we can
  9748. avoid the runtime overhead of this jump by merging \code{block\_5}
  9749. into the preceding block, which in this case is the \code{start} block.
  9750. Figure~\ref{fig:remove-jumps} shows the output of
  9751. \code{allocate\_registers} on the left and the result of this
  9752. optimization on the right.
  9753. \begin{figure}[tbp]
  9754. \begin{tcolorbox}[colback=white]
  9755. {\if\edition\racketEd
  9756. \begin{tabular}{lll}
  9757. \begin{minipage}{0.5\textwidth}
  9758. % cond_test_82.rkt
  9759. \begin{lstlisting}
  9760. start:
  9761. callq read_int
  9762. movq %rax, %rcx
  9763. jmp block_5
  9764. block_5:
  9765. movq %rcx, %rax
  9766. addq $2, %rax
  9767. jmp conclusion
  9768. \end{lstlisting}
  9769. \end{minipage}
  9770. &
  9771. $\Rightarrow\qquad$
  9772. \begin{minipage}{0.4\textwidth}
  9773. \begin{lstlisting}
  9774. start:
  9775. callq read_int
  9776. movq %rax, %rcx
  9777. movq %rcx, %rax
  9778. addq $2, %rax
  9779. jmp conclusion
  9780. \end{lstlisting}
  9781. \end{minipage}
  9782. \end{tabular}
  9783. \fi}
  9784. {\if\edition\pythonEd
  9785. \begin{tabular}{lll}
  9786. \begin{minipage}{0.5\textwidth}
  9787. % cond_test_20.rkt
  9788. \begin{lstlisting}
  9789. start:
  9790. callq read_int
  9791. movq %rax, tmp_0
  9792. cmpq 1, tmp_0
  9793. je block_3
  9794. jmp block_4
  9795. block_3:
  9796. movq 42, tmp_1
  9797. jmp block_2
  9798. block_4:
  9799. movq 0, tmp_1
  9800. jmp block_2
  9801. block_2:
  9802. movq tmp_1, %rdi
  9803. callq print_int
  9804. movq 0, %rax
  9805. jmp conclusion
  9806. \end{lstlisting}
  9807. \end{minipage}
  9808. &
  9809. $\Rightarrow\qquad$
  9810. \begin{minipage}{0.4\textwidth}
  9811. \begin{lstlisting}
  9812. start:
  9813. callq read_int
  9814. movq %rax, tmp_0
  9815. cmpq 1, tmp_0
  9816. je block_3
  9817. movq 0, tmp_1
  9818. jmp block_2
  9819. block_3:
  9820. movq 42, tmp_1
  9821. jmp block_2
  9822. block_2:
  9823. movq tmp_1, %rdi
  9824. callq print_int
  9825. movq 0, %rax
  9826. jmp conclusion
  9827. \end{lstlisting}
  9828. \end{minipage}
  9829. \end{tabular}
  9830. \fi}
  9831. \end{tcolorbox}
  9832. \caption{Merging basic blocks by removing unnecessary jumps.}
  9833. \label{fig:remove-jumps}
  9834. \end{figure}
  9835. \begin{exercise}\normalfont\normalsize
  9836. %
  9837. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9838. into their preceding basic block, when there is only one preceding
  9839. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9840. %
  9841. {\if\edition\racketEd
  9842. In the \code{run-tests.rkt} script, add the following entry to the
  9843. list of \code{passes} between \code{allocate\_registers}
  9844. and \code{patch\_instructions}:
  9845. \begin{lstlisting}
  9846. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9847. \end{lstlisting}
  9848. \fi}
  9849. %
  9850. Run the script to test your compiler.
  9851. %
  9852. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9853. blocks on several test programs.
  9854. \end{exercise}
  9855. \section{Further Reading}
  9856. \label{sec:cond-further-reading}
  9857. The algorithm for the \code{explicate\_control} pass is based on the
  9858. \code{expose-basic-blocks} pass in the course notes of
  9859. \citet{Dybvig:2010aa}.
  9860. %
  9861. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9862. \citet{Appel:2003fk}, and is related to translations into continuation
  9863. passing
  9864. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9865. %
  9866. The treatment of conditionals in the \code{explicate\_control} pass is
  9867. similar to short-cut boolean
  9868. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9869. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9870. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9871. \chapter{Loops and Dataflow Analysis}
  9872. \label{ch:Lwhile}
  9873. \setcounter{footnote}{0}
  9874. % TODO: define R'_8
  9875. % TODO: multi-graph
  9876. {\if\edition\racketEd
  9877. %
  9878. In this chapter we study two features that are the hallmarks of
  9879. imperative programming languages: loops and assignments to local
  9880. variables. The following example demonstrates these new features by
  9881. computing the sum of the first five positive integers:
  9882. % similar to loop_test_1.rkt
  9883. \begin{lstlisting}
  9884. (let ([sum 0])
  9885. (let ([i 5])
  9886. (begin
  9887. (while (> i 0)
  9888. (begin
  9889. (set! sum (+ sum i))
  9890. (set! i (- i 1))))
  9891. sum)))
  9892. \end{lstlisting}
  9893. The \code{while} loop consists of a condition and a
  9894. body.\footnote{The \code{while} loop is not a built-in
  9895. feature of the Racket language, but Racket includes many looping
  9896. constructs and it is straightforward to define \code{while} as a
  9897. macro.} The body is evaluated repeatedly so long as the condition
  9898. remains true.
  9899. %
  9900. The \code{set!} consists of a variable and a right-hand side
  9901. expression. The \code{set!} updates value of the variable to the
  9902. value of the right-hand side.
  9903. %
  9904. The primary purpose of both the \code{while} loop and \code{set!} is
  9905. to cause side effects, so they do not give a meaningful result
  9906. value. Instead, their result is the \code{\#<void>} value. The
  9907. expression \code{(void)} is an explicit way to create the
  9908. \code{\#<void>} value, and it has type \code{Void}. The
  9909. \code{\#<void>} value can be passed around just like other values
  9910. inside an \LangLoop{} program, and it can be compared for equality with
  9911. another \code{\#<void>} value. However, there are no other operations
  9912. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9913. Racket defines the \code{void?} predicate that returns \code{\#t}
  9914. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9915. %
  9916. \footnote{Racket's \code{Void} type corresponds to what is often
  9917. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9918. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9919. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9920. %
  9921. With the addition of side effect-producing features such as
  9922. \code{while} loop and \code{set!}, it is helpful to include a language
  9923. feature for sequencing side effects: the \code{begin} expression. It
  9924. consists of one or more subexpressions that are evaluated
  9925. left to right.
  9926. %
  9927. \fi}
  9928. {\if\edition\pythonEd
  9929. %
  9930. In this chapter we study loops, one of the hallmarks of imperative
  9931. programming languages. The following example demonstrates the
  9932. \code{while} loop by computing the sum of the first five positive
  9933. integers.
  9934. \begin{lstlisting}
  9935. sum = 0
  9936. i = 5
  9937. while i > 0:
  9938. sum = sum + i
  9939. i = i - 1
  9940. print(sum)
  9941. \end{lstlisting}
  9942. The \code{while} loop consists of a condition expression and a body (a
  9943. sequence of statements). The body is evaluated repeatedly so long as
  9944. the condition remains true.
  9945. %
  9946. \fi}
  9947. \section{The \LangLoop{} Language}
  9948. \newcommand{\LwhileGrammarRacket}{
  9949. \begin{array}{lcl}
  9950. \Type &::=& \key{Void}\\
  9951. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9952. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9953. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9954. \end{array}
  9955. }
  9956. \newcommand{\LwhileASTRacket}{
  9957. \begin{array}{lcl}
  9958. \Type &::=& \key{Void}\\
  9959. \Exp &::=& \SETBANG{\Var}{\Exp}
  9960. \MID \BEGIN{\Exp^{*}}{\Exp}
  9961. \MID \WHILE{\Exp}{\Exp}
  9962. \MID \VOID{}
  9963. \end{array}
  9964. }
  9965. \newcommand{\LwhileGrammarPython}{
  9966. \begin{array}{rcl}
  9967. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9968. \end{array}
  9969. }
  9970. \newcommand{\LwhileASTPython}{
  9971. \begin{array}{lcl}
  9972. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9973. \end{array}
  9974. }
  9975. \begin{figure}[tp]
  9976. \centering
  9977. \begin{tcolorbox}[colback=white]
  9978. \small
  9979. {\if\edition\racketEd
  9980. \[
  9981. \begin{array}{l}
  9982. \gray{\LintGrammarRacket{}} \\ \hline
  9983. \gray{\LvarGrammarRacket{}} \\ \hline
  9984. \gray{\LifGrammarRacket{}} \\ \hline
  9985. \LwhileGrammarRacket \\
  9986. \begin{array}{lcl}
  9987. \LangLoopM{} &::=& \Exp
  9988. \end{array}
  9989. \end{array}
  9990. \]
  9991. \fi}
  9992. {\if\edition\pythonEd
  9993. \[
  9994. \begin{array}{l}
  9995. \gray{\LintGrammarPython} \\ \hline
  9996. \gray{\LvarGrammarPython} \\ \hline
  9997. \gray{\LifGrammarPython} \\ \hline
  9998. \LwhileGrammarPython \\
  9999. \begin{array}{rcl}
  10000. \LangLoopM{} &::=& \Stmt^{*}
  10001. \end{array}
  10002. \end{array}
  10003. \]
  10004. \fi}
  10005. \end{tcolorbox}
  10006. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10007. \label{fig:Lwhile-concrete-syntax}
  10008. \end{figure}
  10009. \begin{figure}[tp]
  10010. \centering
  10011. \begin{tcolorbox}[colback=white]
  10012. \small
  10013. {\if\edition\racketEd
  10014. \[
  10015. \begin{array}{l}
  10016. \gray{\LintOpAST} \\ \hline
  10017. \gray{\LvarASTRacket{}} \\ \hline
  10018. \gray{\LifASTRacket{}} \\ \hline
  10019. \LwhileASTRacket{} \\
  10020. \begin{array}{lcl}
  10021. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10022. \end{array}
  10023. \end{array}
  10024. \]
  10025. \fi}
  10026. {\if\edition\pythonEd
  10027. \[
  10028. \begin{array}{l}
  10029. \gray{\LintASTPython} \\ \hline
  10030. \gray{\LvarASTPython} \\ \hline
  10031. \gray{\LifASTPython} \\ \hline
  10032. \LwhileASTPython \\
  10033. \begin{array}{lcl}
  10034. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10035. \end{array}
  10036. \end{array}
  10037. \]
  10038. \fi}
  10039. \end{tcolorbox}
  10040. \python{
  10041. \index{subject}{While@\texttt{While}}
  10042. }
  10043. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10044. \label{fig:Lwhile-syntax}
  10045. \end{figure}
  10046. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10047. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10048. shows the definition of its abstract syntax.
  10049. %
  10050. The definitional interpreter for \LangLoop{} is shown in
  10051. figure~\ref{fig:interp-Lwhile}.
  10052. %
  10053. {\if\edition\racketEd
  10054. %
  10055. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10056. and \code{Void}, and we make changes to the cases for \code{Var} and
  10057. \code{Let} regarding variables. To support assignment to variables and
  10058. to make their lifetimes indefinite (see the second example in
  10059. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10060. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10061. value.
  10062. %
  10063. Now we discuss the new cases. For \code{SetBang}, we find the
  10064. variable in the environment to obtain a boxed value, and then we change
  10065. it using \code{set-box!} to the result of evaluating the right-hand
  10066. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10067. %
  10068. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10069. if the result is true, (2) evaluate the body.
  10070. The result value of a \code{while} loop is also \code{\#<void>}.
  10071. %
  10072. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10073. subexpressions \itm{es} for their effects and then evaluates
  10074. and returns the result from \itm{body}.
  10075. %
  10076. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10077. %
  10078. \fi}
  10079. {\if\edition\pythonEd
  10080. %
  10081. We add a new case for \code{While} in the \code{interp\_stmts}
  10082. function, where we repeatedly interpret the \code{body} so long as the
  10083. \code{test} expression remains true.
  10084. %
  10085. \fi}
  10086. \begin{figure}[tbp]
  10087. \begin{tcolorbox}[colback=white]
  10088. {\if\edition\racketEd
  10089. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10090. (define interp-Lwhile-class
  10091. (class interp-Lif-class
  10092. (super-new)
  10093. (define/override ((interp-exp env) e)
  10094. (define recur (interp-exp env))
  10095. (match e
  10096. [(Let x e body)
  10097. (define new-env (dict-set env x (box (recur e))))
  10098. ((interp-exp new-env) body)]
  10099. [(Var x) (unbox (dict-ref env x))]
  10100. [(SetBang x rhs)
  10101. (set-box! (dict-ref env x) (recur rhs))]
  10102. [(WhileLoop cnd body)
  10103. (define (loop)
  10104. (cond [(recur cnd) (recur body) (loop)]
  10105. [else (void)]))
  10106. (loop)]
  10107. [(Begin es body)
  10108. (for ([e es]) (recur e))
  10109. (recur body)]
  10110. [(Void) (void)]
  10111. [else ((super interp-exp env) e)]))
  10112. ))
  10113. (define (interp-Lwhile p)
  10114. (send (new interp-Lwhile-class) interp-program p))
  10115. \end{lstlisting}
  10116. \fi}
  10117. {\if\edition\pythonEd
  10118. \begin{lstlisting}
  10119. class InterpLwhile(InterpLif):
  10120. def interp_stmts(self, ss, env):
  10121. if len(ss) == 0:
  10122. return
  10123. match ss[0]:
  10124. case While(test, body, []):
  10125. while self.interp_exp(test, env):
  10126. self.interp_stmts(body, env)
  10127. return self.interp_stmts(ss[1:], env)
  10128. case _:
  10129. return super().interp_stmts(ss, env)
  10130. \end{lstlisting}
  10131. \fi}
  10132. \end{tcolorbox}
  10133. \caption{Interpreter for \LangLoop{}.}
  10134. \label{fig:interp-Lwhile}
  10135. \end{figure}
  10136. The definition of the type checker for \LangLoop{} is shown in
  10137. figure~\ref{fig:type-check-Lwhile}.
  10138. %
  10139. {\if\edition\racketEd
  10140. %
  10141. The type checking of the \code{SetBang} expression requires the type
  10142. of the variable and the right-hand side to agree. The result type is
  10143. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10144. and the result type is \code{Void}. For \code{Begin}, the result type
  10145. is the type of its last subexpression.
  10146. %
  10147. \fi}
  10148. %
  10149. {\if\edition\pythonEd
  10150. %
  10151. A \code{while} loop is well typed if the type of the \code{test}
  10152. expression is \code{bool} and the statements in the \code{body} are
  10153. well typed.
  10154. %
  10155. \fi}
  10156. \begin{figure}[tbp]
  10157. \begin{tcolorbox}[colback=white]
  10158. {\if\edition\racketEd
  10159. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10160. (define type-check-Lwhile-class
  10161. (class type-check-Lif-class
  10162. (super-new)
  10163. (inherit check-type-equal?)
  10164. (define/override (type-check-exp env)
  10165. (lambda (e)
  10166. (define recur (type-check-exp env))
  10167. (match e
  10168. [(SetBang x rhs)
  10169. (define-values (rhs^ rhsT) (recur rhs))
  10170. (define varT (dict-ref env x))
  10171. (check-type-equal? rhsT varT e)
  10172. (values (SetBang x rhs^) 'Void)]
  10173. [(WhileLoop cnd body)
  10174. (define-values (cnd^ Tc) (recur cnd))
  10175. (check-type-equal? Tc 'Boolean e)
  10176. (define-values (body^ Tbody) ((type-check-exp env) body))
  10177. (values (WhileLoop cnd^ body^) 'Void)]
  10178. [(Begin es body)
  10179. (define-values (es^ ts)
  10180. (for/lists (l1 l2) ([e es]) (recur e)))
  10181. (define-values (body^ Tbody) (recur body))
  10182. (values (Begin es^ body^) Tbody)]
  10183. [else ((super type-check-exp env) e)])))
  10184. ))
  10185. (define (type-check-Lwhile p)
  10186. (send (new type-check-Lwhile-class) type-check-program p))
  10187. \end{lstlisting}
  10188. \fi}
  10189. {\if\edition\pythonEd
  10190. \begin{lstlisting}
  10191. class TypeCheckLwhile(TypeCheckLif):
  10192. def type_check_stmts(self, ss, env):
  10193. if len(ss) == 0:
  10194. return
  10195. match ss[0]:
  10196. case While(test, body, []):
  10197. test_t = self.type_check_exp(test, env)
  10198. check_type_equal(bool, test_t, test)
  10199. body_t = self.type_check_stmts(body, env)
  10200. return self.type_check_stmts(ss[1:], env)
  10201. case _:
  10202. return super().type_check_stmts(ss, env)
  10203. \end{lstlisting}
  10204. \fi}
  10205. \end{tcolorbox}
  10206. \caption{Type checker for the \LangLoop{} language.}
  10207. \label{fig:type-check-Lwhile}
  10208. \end{figure}
  10209. {\if\edition\racketEd
  10210. %
  10211. At first glance, the translation of these language features to x86
  10212. seems straightforward because the \LangCIf{} intermediate language
  10213. already supports all the ingredients that we need: assignment,
  10214. \code{goto}, conditional branching, and sequencing. However, there are
  10215. complications that arise, which we discuss in the next section. After
  10216. that we introduce the changes necessary to the existing passes.
  10217. %
  10218. \fi}
  10219. {\if\edition\pythonEd
  10220. %
  10221. At first glance, the translation of \code{while} loops to x86 seems
  10222. straightforward because the \LangCIf{} intermediate language already
  10223. supports \code{goto} and conditional branching. However, there are
  10224. complications that arise which we discuss in the next section. After
  10225. that we introduce the changes necessary to the existing passes.
  10226. %
  10227. \fi}
  10228. \section{Cyclic Control Flow and Dataflow Analysis}
  10229. \label{sec:dataflow-analysis}
  10230. Up until this point, the programs generated in
  10231. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10232. \code{while} loop introduces a cycle. Does that matter?
  10233. %
  10234. Indeed, it does. Recall that for register allocation, the compiler
  10235. performs liveness analysis to determine which variables can share the
  10236. same register. To accomplish this, we analyzed the control-flow graph
  10237. in reverse topological order
  10238. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10239. well defined only for acyclic graphs.
  10240. Let us return to the example of computing the sum of the first five
  10241. positive integers. Here is the program after instruction selection but
  10242. before register allocation.
  10243. \begin{center}
  10244. {\if\edition\racketEd
  10245. \begin{minipage}{0.45\textwidth}
  10246. \begin{lstlisting}
  10247. (define (main) : Integer
  10248. mainstart:
  10249. movq $0, sum
  10250. movq $5, i
  10251. jmp block5
  10252. block5:
  10253. movq i, tmp3
  10254. cmpq tmp3, $0
  10255. jl block7
  10256. jmp block8
  10257. \end{lstlisting}
  10258. \end{minipage}
  10259. \begin{minipage}{0.45\textwidth}
  10260. \begin{lstlisting}
  10261. block7:
  10262. addq i, sum
  10263. movq $1, tmp4
  10264. negq tmp4
  10265. addq tmp4, i
  10266. jmp block5
  10267. block8:
  10268. movq $27, %rax
  10269. addq sum, %rax
  10270. jmp mainconclusion
  10271. )
  10272. \end{lstlisting}
  10273. \end{minipage}
  10274. \fi}
  10275. {\if\edition\pythonEd
  10276. \begin{minipage}{0.45\textwidth}
  10277. \begin{lstlisting}
  10278. mainstart:
  10279. movq $0, sum
  10280. movq $5, i
  10281. jmp block5
  10282. block5:
  10283. cmpq $0, i
  10284. jg block7
  10285. jmp block8
  10286. \end{lstlisting}
  10287. \end{minipage}
  10288. \begin{minipage}{0.45\textwidth}
  10289. \begin{lstlisting}
  10290. block7:
  10291. addq i, sum
  10292. subq $1, i
  10293. jmp block5
  10294. block8:
  10295. movq sum, %rdi
  10296. callq print_int
  10297. movq $0, %rax
  10298. jmp mainconclusion
  10299. \end{lstlisting}
  10300. \end{minipage}
  10301. \fi}
  10302. \end{center}
  10303. Recall that liveness analysis works backward, starting at the end
  10304. of each function. For this example we could start with \code{block8}
  10305. because we know what is live at the beginning of the conclusion:
  10306. only \code{rax} and \code{rsp}. So the live-before set
  10307. for \code{block8} is \code{\{rsp,sum\}}.
  10308. %
  10309. Next we might try to analyze \code{block5} or \code{block7}, but
  10310. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10311. we are stuck.
  10312. The way out of this impasse is to realize that we can compute an
  10313. underapproximation of each live-before set by starting with empty
  10314. live-after sets. By \emph{underapproximation}, we mean that the set
  10315. contains only variables that are live for some execution of the
  10316. program, but the set may be missing some variables that are live.
  10317. Next, the underapproximations for each block can be improved by (1)
  10318. updating the live-after set for each block using the approximate
  10319. live-before sets from the other blocks, and (2) performing liveness
  10320. analysis again on each block. In fact, by iterating this process, the
  10321. underapproximations eventually become the correct solutions!
  10322. %
  10323. This approach of iteratively analyzing a control-flow graph is
  10324. applicable to many static analysis problems and goes by the name
  10325. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10326. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10327. Washington.
  10328. Let us apply this approach to the previously presented example. We use
  10329. the empty set for the initial live-before set for each block. Let
  10330. $m_0$ be the following mapping from label names to sets of locations
  10331. (variables and registers):
  10332. \begin{center}
  10333. \begin{lstlisting}
  10334. mainstart: {}, block5: {}, block7: {}, block8: {}
  10335. \end{lstlisting}
  10336. \end{center}
  10337. Using the above live-before approximations, we determine the
  10338. live-after for each block and then apply liveness analysis to each
  10339. block. This produces our next approximation $m_1$ of the live-before
  10340. sets.
  10341. \begin{center}
  10342. \begin{lstlisting}
  10343. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10344. \end{lstlisting}
  10345. \end{center}
  10346. For the second round, the live-after for \code{mainstart} is the
  10347. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10348. the liveness analysis for \code{mainstart} computes the empty set. The
  10349. live-after for \code{block5} is the union of the live-before sets for
  10350. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  10351. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  10352. sum\}}. The live-after for \code{block7} is the live-before for
  10353. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10354. So the liveness analysis for \code{block7} remains \code{\{i,
  10355. sum\}}. Together these yield the following approximation $m_2$ of
  10356. the live-before sets:
  10357. \begin{center}
  10358. \begin{lstlisting}
  10359. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10360. \end{lstlisting}
  10361. \end{center}
  10362. In the preceding iteration, only \code{block5} changed, so we can
  10363. limit our attention to \code{mainstart} and \code{block7}, the two
  10364. blocks that jump to \code{block5}. As a result, the live-before sets
  10365. for \code{mainstart} and \code{block7} are updated to include
  10366. \code{rsp}, yielding the following approximation $m_3$:
  10367. \begin{center}
  10368. \begin{lstlisting}
  10369. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10370. \end{lstlisting}
  10371. \end{center}
  10372. Because \code{block7} changed, we analyze \code{block5} once more, but
  10373. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10374. our approximations have converged, so $m_3$ is the solution.
  10375. This iteration process is guaranteed to converge to a solution by the
  10376. Kleene fixed-point theorem, a general theorem about functions on
  10377. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10378. any collection that comes with a partial ordering $\sqsubseteq$ on its
  10379. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10380. join operator
  10381. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  10382. ordering}\index{subject}{join}\footnote{Technically speaking, we
  10383. will be working with join semilattices.} When two elements are
  10384. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10385. as much information as $m_i$, so we can think of $m_j$ as a
  10386. better-than-or-equal-to approximation in relation to $m_i$. The
  10387. bottom element $\bot$ represents the complete lack of information,
  10388. that is, the worst approximation. The join operator takes two lattice
  10389. elements and combines their information; that is, it produces the
  10390. least upper bound of the two.\index{subject}{least upper bound}
  10391. A dataflow analysis typically involves two lattices: one lattice to
  10392. represent abstract states and another lattice that aggregates the
  10393. abstract states of all the blocks in the control-flow graph. For
  10394. liveness analysis, an abstract state is a set of locations. We form
  10395. the lattice $L$ by taking its elements to be sets of locations, the
  10396. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10397. set, and the join operator to be set union.
  10398. %
  10399. We form a second lattice $M$ by taking its elements to be mappings
  10400. from the block labels to sets of locations (elements of $L$). We
  10401. order the mappings point-wise, using the ordering of $L$. So, given any
  10402. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10403. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10404. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10405. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  10406. We can think of one iteration of liveness analysis applied to the
  10407. whole program as being a function $f$ on the lattice $M$. It takes a
  10408. mapping as input and computes a new mapping.
  10409. \[
  10410. f(m_i) = m_{i+1}
  10411. \]
  10412. Next let us think for a moment about what a final solution $m_s$
  10413. should look like. If we perform liveness analysis using the solution
  10414. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10415. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10416. \[
  10417. f(m_s) = m_s
  10418. \]
  10419. Furthermore, the solution should include only locations that are
  10420. forced to be there by performing liveness analysis on the program, so
  10421. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10422. The Kleene fixed-point theorem states that if a function $f$ is
  10423. monotone (better inputs produce better outputs), then the least fixed
  10424. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10425. chain} obtained by starting at $\bot$ and iterating $f$, as
  10426. follows:\index{subject}{Kleene fixed-point theorem}
  10427. \[
  10428. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10429. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10430. \]
  10431. When a lattice contains only finitely long ascending chains, then
  10432. every Kleene chain tops out at some fixed point after some number of
  10433. iterations of $f$.
  10434. \[
  10435. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10436. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10437. \]
  10438. The liveness analysis is indeed a monotone function and the lattice
  10439. $M$ has finitely long ascending chains because there are only a
  10440. finite number of variables and blocks in the program. Thus we are
  10441. guaranteed that iteratively applying liveness analysis to all blocks
  10442. in the program will eventually produce the least fixed point solution.
  10443. Next let us consider dataflow analysis in general and discuss the
  10444. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10445. %
  10446. The algorithm has four parameters: the control-flow graph \code{G}, a
  10447. function \code{transfer} that applies the analysis to one block, and the
  10448. \code{bottom} and \code{join} operators for the lattice of abstract
  10449. states. The \code{analyze\_dataflow} function is formulated as a
  10450. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10451. function come from the predecessor nodes in the control-flow
  10452. graph. However, liveness analysis is a \emph{backward} dataflow
  10453. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10454. function with the transpose of the control-flow graph.
  10455. The algorithm begins by creating the bottom mapping, represented by a
  10456. hash table. It then pushes all the nodes in the control-flow graph
  10457. onto the work list (a queue). The algorithm repeats the \code{while}
  10458. loop as long as there are items in the work list. In each iteration, a
  10459. node is popped from the work list and processed. The \code{input} for
  10460. the node is computed by taking the join of the abstract states of all
  10461. the predecessor nodes. The \code{transfer} function is then applied to
  10462. obtain the \code{output} abstract state. If the output differs from
  10463. the previous state for this block, the mapping for this block is
  10464. updated and its successor nodes are pushed onto the work list.
  10465. \begin{figure}[tb]
  10466. \begin{tcolorbox}[colback=white]
  10467. {\if\edition\racketEd
  10468. \begin{lstlisting}
  10469. (define (analyze_dataflow G transfer bottom join)
  10470. (define mapping (make-hash))
  10471. (for ([v (in-vertices G)])
  10472. (dict-set! mapping v bottom))
  10473. (define worklist (make-queue))
  10474. (for ([v (in-vertices G)])
  10475. (enqueue! worklist v))
  10476. (define trans-G (transpose G))
  10477. (while (not (queue-empty? worklist))
  10478. (define node (dequeue! worklist))
  10479. (define input (for/fold ([state bottom])
  10480. ([pred (in-neighbors trans-G node)])
  10481. (join state (dict-ref mapping pred))))
  10482. (define output (transfer node input))
  10483. (cond [(not (equal? output (dict-ref mapping node)))
  10484. (dict-set! mapping node output)
  10485. (for ([v (in-neighbors G node)])
  10486. (enqueue! worklist v))]))
  10487. mapping)
  10488. \end{lstlisting}
  10489. \fi}
  10490. {\if\edition\pythonEd
  10491. \begin{lstlisting}
  10492. def analyze_dataflow(G, transfer, bottom, join):
  10493. trans_G = transpose(G)
  10494. mapping = dict((v, bottom) for v in G.vertices())
  10495. worklist = deque(G.vertices)
  10496. while worklist:
  10497. node = worklist.pop()
  10498. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10499. input = reduce(join, inputs, bottom)
  10500. output = transfer(node, input)
  10501. if output != mapping[node]:
  10502. mapping[node] = output
  10503. worklist.extend(G.adjacent(node))
  10504. \end{lstlisting}
  10505. \fi}
  10506. \end{tcolorbox}
  10507. \caption{Generic work list algorithm for dataflow analysis}
  10508. \label{fig:generic-dataflow}
  10509. \end{figure}
  10510. {\if\edition\racketEd
  10511. \section{Mutable Variables and Remove Complex Operands}
  10512. There is a subtle interaction between the
  10513. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10514. and the left-to-right order of evaluation of Racket. Consider the
  10515. following example:
  10516. \begin{lstlisting}
  10517. (let ([x 2])
  10518. (+ x (begin (set! x 40) x)))
  10519. \end{lstlisting}
  10520. The result of this program is \code{42} because the first read from
  10521. \code{x} produces \code{2} and the second produces \code{40}. However,
  10522. if we naively apply the \code{remove\_complex\_operands} pass to this
  10523. example we obtain the following program whose result is \code{80}!
  10524. \begin{lstlisting}
  10525. (let ([x 2])
  10526. (let ([tmp (begin (set! x 40) x)])
  10527. (+ x tmp)))
  10528. \end{lstlisting}
  10529. The problem is that with mutable variables, the ordering between
  10530. reads and writes is important, and the
  10531. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10532. before the first read of \code{x}.
  10533. We recommend solving this problem by giving special treatment to reads
  10534. from mutable variables, that is, variables that occur on the left-hand
  10535. side of a \code{set!}. We mark each read from a mutable variable with
  10536. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10537. that the read operation is effectful in that it can produce different
  10538. results at different points in time. Let's apply this idea to the
  10539. following variation that also involves a variable that is not mutated:
  10540. % loop_test_24.rkt
  10541. \begin{lstlisting}
  10542. (let ([x 2])
  10543. (let ([y 0])
  10544. (+ y (+ x (begin (set! x 40) x)))))
  10545. \end{lstlisting}
  10546. We first analyze this program to discover that variable \code{x}
  10547. is mutable but \code{y} is not. We then transform the program as
  10548. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10549. \begin{lstlisting}
  10550. (let ([x 2])
  10551. (let ([y 0])
  10552. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10553. \end{lstlisting}
  10554. Now that we have a clear distinction between reads from mutable and
  10555. immutable variables, we can apply the \code{remove\_complex\_operands}
  10556. pass, where reads from immutable variables are still classified as
  10557. atomic expressions but reads from mutable variables are classified as
  10558. complex. Thus, \code{remove\_complex\_operands} yields the following
  10559. program:\\
  10560. \begin{minipage}{\textwidth}
  10561. \begin{lstlisting}
  10562. (let ([x 2])
  10563. (let ([y 0])
  10564. (+ y (let ([t1 (get! x)])
  10565. (let ([t2 (begin (set! x 40) (get! x))])
  10566. (+ t1 t2))))))
  10567. \end{lstlisting}
  10568. \end{minipage}
  10569. The temporary variable \code{t1} gets the value of \code{x} before the
  10570. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10571. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10572. do not generate a temporary variable for the occurrence of \code{y}
  10573. because it's an immutable variable. We want to avoid such unnecessary
  10574. extra temporaries because they would needless increase the number of
  10575. variables, making it more likely for some of them to be spilled. The
  10576. result of this program is \code{42}, the same as the result prior to
  10577. \code{remove\_complex\_operands}.
  10578. The approach that we've sketched requires only a small
  10579. modification to \code{remove\_complex\_operands} to handle
  10580. \code{get!}. However, it requires a new pass, called
  10581. \code{uncover-get!}, that we discuss in
  10582. section~\ref{sec:uncover-get-bang}.
  10583. As an aside, this problematic interaction between \code{set!} and the
  10584. pass \code{remove\_complex\_operands} is particular to Racket and not
  10585. its predecessor, the Scheme language. The key difference is that
  10586. Scheme does not specify an order of evaluation for the arguments of an
  10587. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10588. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10589. would be correct results for the example program. Interestingly,
  10590. Racket is implemented on top of the Chez Scheme
  10591. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10592. presented in this section (using extra \code{let} bindings to control
  10593. the order of evaluation) is used in the translation from Racket to
  10594. Scheme~\citep{Flatt:2019tb}.
  10595. \fi} % racket
  10596. Having discussed the complications that arise from adding support for
  10597. assignment and loops, we turn to discussing the individual compilation
  10598. passes.
  10599. {\if\edition\racketEd
  10600. \section{Uncover \texttt{get!}}
  10601. \label{sec:uncover-get-bang}
  10602. The goal of this pass is to mark uses of mutable variables so that
  10603. \code{remove\_complex\_operands} can treat them as complex expressions
  10604. and thereby preserve their ordering relative to the side effects in
  10605. other operands. So, the first step is to collect all the mutable
  10606. variables. We recommend creating an auxiliary function for this,
  10607. named \code{collect-set!}, that recursively traverses expressions,
  10608. returning the set of all variables that occur on the left-hand side of a
  10609. \code{set!}. Here's an excerpt of its implementation.
  10610. \begin{center}
  10611. \begin{minipage}{\textwidth}
  10612. \begin{lstlisting}
  10613. (define (collect-set! e)
  10614. (match e
  10615. [(Var x) (set)]
  10616. [(Int n) (set)]
  10617. [(Let x rhs body)
  10618. (set-union (collect-set! rhs) (collect-set! body))]
  10619. [(SetBang var rhs)
  10620. (set-union (set var) (collect-set! rhs))]
  10621. ...))
  10622. \end{lstlisting}
  10623. \end{minipage}
  10624. \end{center}
  10625. By placing this pass after \code{uniquify}, we need not worry about
  10626. variable shadowing, and our logic for \code{Let} can remain simple, as
  10627. in this excerpt.
  10628. The second step is to mark the occurrences of the mutable variables
  10629. with the new \code{GetBang} AST node (\code{get!} in concrete
  10630. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10631. function, which takes two parameters: the set of mutable variables
  10632. \code{set!-vars} and the expression \code{e} to be processed. The
  10633. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10634. mutable variable or leaves it alone if not.
  10635. \begin{center}
  10636. \begin{minipage}{\textwidth}
  10637. \begin{lstlisting}
  10638. (define ((uncover-get!-exp set!-vars) e)
  10639. (match e
  10640. [(Var x)
  10641. (if (set-member? set!-vars x)
  10642. (GetBang x)
  10643. (Var x))]
  10644. ...))
  10645. \end{lstlisting}
  10646. \end{minipage}
  10647. \end{center}
  10648. To wrap things up, define the \code{uncover-get!} function for
  10649. processing a whole program, using \code{collect-set!} to obtain the
  10650. set of mutable variables and then \code{uncover-get!-exp} to replace
  10651. their occurrences with \code{GetBang}.
  10652. \fi}
  10653. \section{Remove Complex Operands}
  10654. \label{sec:rco-loop}
  10655. {\if\edition\racketEd
  10656. %
  10657. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10658. \code{while} are all complex expressions. The subexpressions of
  10659. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10660. %
  10661. \fi}
  10662. {\if\edition\pythonEd
  10663. %
  10664. The change needed for this pass is to add a case for the \code{while}
  10665. statement. The condition of a \code{while} loop is allowed to be a
  10666. complex expression, just like the condition of the \code{if}
  10667. statement.
  10668. %
  10669. \fi}
  10670. %
  10671. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10672. \LangLoopANF{} of this pass.
  10673. \newcommand{\LwhileMonadASTRacket}{
  10674. \begin{array}{rcl}
  10675. \Atm &::=& \VOID{} \\
  10676. \Exp &::=& \GETBANG{\Var}
  10677. \MID \SETBANG{\Var}{\Exp}
  10678. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10679. &\MID& \WHILE{\Exp}{\Exp}
  10680. \end{array}
  10681. }
  10682. \newcommand{\LwhileMonadASTPython}{
  10683. \begin{array}{rcl}
  10684. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10685. \end{array}
  10686. }
  10687. \begin{figure}[tp]
  10688. \centering
  10689. \begin{tcolorbox}[colback=white]
  10690. \small
  10691. {\if\edition\racketEd
  10692. \[
  10693. \begin{array}{l}
  10694. \gray{\LvarMonadASTRacket} \\ \hline
  10695. \gray{\LifMonadASTRacket} \\ \hline
  10696. \LwhileMonadASTRacket \\
  10697. \begin{array}{rcl}
  10698. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10699. \end{array}
  10700. \end{array}
  10701. \]
  10702. \fi}
  10703. {\if\edition\pythonEd
  10704. \[
  10705. \begin{array}{l}
  10706. \gray{\LvarMonadASTPython} \\ \hline
  10707. \gray{\LifMonadASTPython} \\ \hline
  10708. \LwhileMonadASTPython \\
  10709. \begin{array}{rcl}
  10710. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10711. \end{array}
  10712. \end{array}
  10713. %% \begin{array}{rcl}
  10714. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10715. %% \Exp &::=& \Atm \MID \READ{} \\
  10716. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10717. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10718. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10719. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10720. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10721. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10722. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10723. %% \end{array}
  10724. \]
  10725. \fi}
  10726. \end{tcolorbox}
  10727. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10728. \label{fig:Lwhile-anf-syntax}
  10729. \end{figure}
  10730. {\if\edition\racketEd
  10731. %
  10732. As usual, when a complex expression appears in a grammar position that
  10733. needs to be atomic, such as the argument of a primitive operator, we
  10734. must introduce a temporary variable and bind it to the complex
  10735. expression. This approach applies, unchanged, to handle the new
  10736. language forms. For example, in the following code there are two
  10737. \code{begin} expressions appearing as arguments to the \code{+}
  10738. operator. The output of \code{rco\_exp} is then shown, in which the
  10739. \code{begin} expressions have been bound to temporary
  10740. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10741. allowed to have arbitrary expressions in their right-hand side
  10742. expression, so it is fine to place \code{begin} there.
  10743. %
  10744. \begin{center}
  10745. \begin{tabular}{lcl}
  10746. \begin{minipage}{0.4\textwidth}
  10747. \begin{lstlisting}
  10748. (let ([x2 10])
  10749. (let ([y3 0])
  10750. (+ (+ (begin
  10751. (set! y3 (read))
  10752. (get! x2))
  10753. (begin
  10754. (set! x2 (read))
  10755. (get! y3)))
  10756. (get! x2))))
  10757. \end{lstlisting}
  10758. \end{minipage}
  10759. &
  10760. $\Rightarrow$
  10761. &
  10762. \begin{minipage}{0.4\textwidth}
  10763. \begin{lstlisting}
  10764. (let ([x2 10])
  10765. (let ([y3 0])
  10766. (let ([tmp4 (begin
  10767. (set! y3 (read))
  10768. x2)])
  10769. (let ([tmp5 (begin
  10770. (set! x2 (read))
  10771. y3)])
  10772. (let ([tmp6 (+ tmp4 tmp5)])
  10773. (let ([tmp7 x2])
  10774. (+ tmp6 tmp7)))))))
  10775. \end{lstlisting}
  10776. \end{minipage}
  10777. \end{tabular}
  10778. \end{center}
  10779. \fi}
  10780. \section{Explicate Control \racket{and \LangCLoop{}}}
  10781. \label{sec:explicate-loop}
  10782. \newcommand{\CloopASTRacket}{
  10783. \begin{array}{lcl}
  10784. \Atm &::=& \VOID \\
  10785. \Stmt &::=& \READ{}
  10786. \end{array}
  10787. }
  10788. {\if\edition\racketEd
  10789. Recall that in the \code{explicate\_control} pass we define one helper
  10790. function for each kind of position in the program. For the \LangVar{}
  10791. language of integers and variables, we needed assignment and tail
  10792. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10793. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10794. another kind of position: effect position. Except for the last
  10795. subexpression, the subexpressions inside a \code{begin} are evaluated
  10796. only for their effect. Their result values are discarded. We can
  10797. generate better code by taking this fact into account.
  10798. The output language of \code{explicate\_control} is \LangCLoop{}
  10799. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10800. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10801. and that \code{read} may appear as a statement. The most significant
  10802. difference between the programs generated by \code{explicate\_control}
  10803. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10804. chapter is that the control-flow graphs of the latter may contain
  10805. cycles.
  10806. \begin{figure}[tp]
  10807. \begin{tcolorbox}[colback=white]
  10808. \small
  10809. \[
  10810. \begin{array}{l}
  10811. \gray{\CvarASTRacket} \\ \hline
  10812. \gray{\CifASTRacket} \\ \hline
  10813. \CloopASTRacket \\
  10814. \begin{array}{lcl}
  10815. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10816. \end{array}
  10817. \end{array}
  10818. \]
  10819. \end{tcolorbox}
  10820. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10821. \label{fig:c7-syntax}
  10822. \end{figure}
  10823. The new auxiliary function \code{explicate\_effect} takes an
  10824. expression (in an effect position) and the code for its
  10825. continuation. The function returns a $\Tail$ that includes the
  10826. generated code for the input expression followed by the
  10827. continuation. If the expression is obviously pure, that is, never
  10828. causes side effects, then the expression can be removed, so the result
  10829. is just the continuation.
  10830. %
  10831. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10832. interesting; the generated code is depicted in the following diagram:
  10833. \begin{center}
  10834. \begin{minipage}{0.3\textwidth}
  10835. \xymatrix{
  10836. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10837. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10838. & *+[F]{\txt{\itm{cont}}} \\
  10839. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10840. }
  10841. \end{minipage}
  10842. \end{center}
  10843. We start by creating a fresh label $\itm{loop}$ for the top of the
  10844. loop. Next, recursively process the \itm{body} (in effect position)
  10845. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10846. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10847. \itm{body'} as the \emph{then} branch and the continuation block as the
  10848. \emph{else} branch. The result should be added to the dictionary of
  10849. \code{basic-blocks} with the label \itm{loop}. The result for the
  10850. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10851. The auxiliary functions for tail, assignment, and predicate positions
  10852. need to be updated. The three new language forms, \code{while},
  10853. \code{set!}, and \code{begin}, can appear in assignment and tail
  10854. positions. Only \code{begin} may appear in predicate positions; the
  10855. other two have result type \code{Void}.
  10856. \fi}
  10857. %
  10858. {\if\edition\pythonEd
  10859. %
  10860. The output of this pass is the language \LangCIf{}. No new language
  10861. features are needed in the output because a \code{while} loop can be
  10862. expressed in terms of \code{goto} and \code{if} statements, which are
  10863. already in \LangCIf{}.
  10864. %
  10865. Add a case for the \code{while} statement to the
  10866. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10867. the condition expression.
  10868. %
  10869. \fi}
  10870. {\if\edition\racketEd
  10871. \section{Select Instructions}
  10872. \label{sec:select-instructions-loop}
  10873. Only two small additions are needed in the \code{select\_instructions}
  10874. pass to handle the changes to \LangCLoop{}. First, to handle the
  10875. addition of \VOID{} we simply translate it to \code{0}. Second,
  10876. \code{read} may appear as a stand-alone statement instead of
  10877. appearing only on the right-hand side of an assignment statement. The code
  10878. generation is nearly identical to the one for assignment; just leave
  10879. off the instruction for moving the result into the left-hand side.
  10880. \fi}
  10881. \section{Register Allocation}
  10882. \label{sec:register-allocation-loop}
  10883. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10884. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10885. which complicates the liveness analysis needed for register
  10886. allocation.
  10887. %
  10888. We recommend using the generic \code{analyze\_dataflow} function that
  10889. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10890. perform liveness analysis, replacing the code in
  10891. \code{uncover\_live} that processed the basic blocks in topological
  10892. order (section~\ref{sec:liveness-analysis-Lif}).
  10893. The \code{analyze\_dataflow} function has the following four parameters.
  10894. \begin{enumerate}
  10895. \item The first parameter \code{G} should be passed the transpose
  10896. of the control-flow graph.
  10897. \item The second parameter \code{transfer} should be passed a function
  10898. that applies liveness analysis to a basic block. It takes two
  10899. parameters: the label for the block to analyze and the live-after
  10900. set for that block. The transfer function should return the
  10901. live-before set for the block.
  10902. %
  10903. \racket{Also, as a side effect, it should update the block's
  10904. $\itm{info}$ with the liveness information for each instruction.}
  10905. %
  10906. \python{Also, as a side-effect, it should update the live-before and
  10907. live-after sets for each instruction.}
  10908. %
  10909. To implement the \code{transfer} function, you should be able to
  10910. reuse the code you already have for analyzing basic blocks.
  10911. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10912. \code{bottom} and \code{join} for the lattice of abstract states,
  10913. that is, sets of locations. For liveness analysis, the bottom of the
  10914. lattice is the empty set, and the join operator is set union.
  10915. \end{enumerate}
  10916. \begin{figure}[p]
  10917. \begin{tcolorbox}[colback=white]
  10918. {\if\edition\racketEd
  10919. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10920. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10921. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10922. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10923. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10924. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10925. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10926. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10927. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10928. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10929. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10930. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10931. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10932. \path[->,bend left=15] (Lfun) edge [above] node
  10933. {\ttfamily\footnotesize shrink} (Lfun-2);
  10934. \path[->,bend left=15] (Lfun-2) edge [above] node
  10935. {\ttfamily\footnotesize uniquify} (F1-4);
  10936. \path[->,bend left=15] (F1-4) edge [above] node
  10937. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10938. \path[->,bend left=15] (F1-5) edge [left] node
  10939. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10940. \path[->,bend left=10] (F1-6) edge [above] node
  10941. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10942. \path[->,bend left=15] (C3-2) edge [right] node
  10943. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10944. \path[->,bend right=15] (x86-2) edge [right] node
  10945. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10946. \path[->,bend right=15] (x86-2-1) edge [below] node
  10947. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10948. \path[->,bend right=15] (x86-2-2) edge [right] node
  10949. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10950. \path[->,bend left=15] (x86-3) edge [above] node
  10951. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10952. \path[->,bend left=15] (x86-4) edge [right] node
  10953. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10954. \end{tikzpicture}
  10955. \fi}
  10956. {\if\edition\pythonEd
  10957. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10958. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10959. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10960. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10961. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10962. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10963. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10964. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10965. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  10966. \path[->,bend left=15] (Lfun) edge [above] node
  10967. {\ttfamily\footnotesize shrink} (Lfun-2);
  10968. \path[->,bend left=15] (Lfun-2) edge [above] node
  10969. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10970. \path[->,bend left=10] (F1-6) edge [right] node
  10971. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10972. \path[->,bend right=15] (C3-2) edge [right] node
  10973. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10974. \path[->,bend right=15] (x86-2) edge [below] node
  10975. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10976. \path[->,bend left=15] (x86-3) edge [above] node
  10977. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10978. \path[->,bend right=15] (x86-4) edge [below] node
  10979. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10980. \end{tikzpicture}
  10981. \fi}
  10982. \end{tcolorbox}
  10983. \caption{Diagram of the passes for \LangLoop{}.}
  10984. \label{fig:Lwhile-passes}
  10985. \end{figure}
  10986. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10987. for the compilation of \LangLoop{}.
  10988. % Further Reading: dataflow analysis
  10989. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10990. \chapter{Tuples and Garbage Collection}
  10991. \label{ch:Lvec}
  10992. \index{subject}{tuple}
  10993. \index{subject}{vector}
  10994. \index{subject}{allocate}
  10995. \index{subject}{heap allocate}
  10996. \setcounter{footnote}{0}
  10997. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10998. %% all the IR grammars are spelled out! \\ --Jeremy}
  10999. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11000. %% the root stack. \\ --Jeremy}
  11001. In this chapter we study the implementation of tuples\racket{, called
  11002. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11003. in which each element may have a different type.
  11004. %
  11005. This language feature is the first to use the computer's
  11006. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11007. indefinite; that is, a tuple lives forever from the programmer's
  11008. viewpoint. Of course, from an implementer's viewpoint, it is important
  11009. to reclaim the space associated with a tuple when it is no longer
  11010. needed, which is why we also study \emph{garbage collection}
  11011. \index{subject}{garbage collection} techniques in this chapter.
  11012. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11013. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11014. language (chapter~\ref{ch:Lwhile}) with tuples.
  11015. %
  11016. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11017. copying live tuples back and forth between two halves of the heap. The
  11018. garbage collector requires coordination with the compiler so that it
  11019. can find all the live tuples.
  11020. %
  11021. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11022. discuss the necessary changes and additions to the compiler passes,
  11023. including a new compiler pass named \code{expose\_allocation}.
  11024. \section{The \LangVec{} Language}
  11025. \label{sec:r3}
  11026. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11027. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11028. the definition of the abstract syntax.
  11029. %
  11030. \racket{The \LangVec{} language includes the forms: \code{vector} for
  11031. creating a tuple, \code{vector-ref} for reading an element of a
  11032. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11033. \code{vector-length} for obtaining the number of elements of a
  11034. tuple.}
  11035. %
  11036. \python{The \LangVec{} language adds 1) tuple creation via a
  11037. comma-separated list of expressions, 2) accessing an element of a
  11038. tuple with the square bracket notation, i.e., \code{t[n]} returns
  11039. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  11040. operator, and 4) obtaining the number of elements (the length) of a
  11041. tuple. In this chapter, we restrict access indices to constant
  11042. integers.}
  11043. %
  11044. The following program shows an example use of tuples. It creates a tuple
  11045. \code{t} containing the elements \code{40},
  11046. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11047. contains just \code{2}. The element at index $1$ of \code{t} is
  11048. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11049. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11050. to which we add \code{2}, the element at index $0$ of the tuple.
  11051. The result of the program is \code{42}.
  11052. %
  11053. {\if\edition\racketEd
  11054. \begin{lstlisting}
  11055. (let ([t (vector 40 #t (vector 2))])
  11056. (if (vector-ref t 1)
  11057. (+ (vector-ref t 0)
  11058. (vector-ref (vector-ref t 2) 0))
  11059. 44))
  11060. \end{lstlisting}
  11061. \fi}
  11062. {\if\edition\pythonEd
  11063. \begin{lstlisting}
  11064. t = 40, True, (2,)
  11065. print( t[0] + t[2][0] if t[1] else 44 )
  11066. \end{lstlisting}
  11067. \fi}
  11068. \newcommand{\LtupGrammarRacket}{
  11069. \begin{array}{lcl}
  11070. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11071. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11072. \MID \LP\key{vector-length}\;\Exp\RP \\
  11073. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11074. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11075. \end{array}
  11076. }
  11077. \newcommand{\LtupASTRacket}{
  11078. \begin{array}{lcl}
  11079. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11080. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11081. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11082. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11083. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11084. \end{array}
  11085. }
  11086. \newcommand{\LtupGrammarPython}{
  11087. \begin{array}{rcl}
  11088. \itm{cmp} &::= & \key{is} \\
  11089. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11090. \end{array}
  11091. }
  11092. \newcommand{\LtupASTPython}{
  11093. \begin{array}{lcl}
  11094. \itm{cmp} &::= & \code{Is()} \\
  11095. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11096. &\MID& \LEN{\Exp}
  11097. \end{array}
  11098. }
  11099. \begin{figure}[tbp]
  11100. \centering
  11101. \begin{tcolorbox}[colback=white]
  11102. \small
  11103. {\if\edition\racketEd
  11104. \[
  11105. \begin{array}{l}
  11106. \gray{\LintGrammarRacket{}} \\ \hline
  11107. \gray{\LvarGrammarRacket{}} \\ \hline
  11108. \gray{\LifGrammarRacket{}} \\ \hline
  11109. \gray{\LwhileGrammarRacket} \\ \hline
  11110. \LtupGrammarRacket \\
  11111. \begin{array}{lcl}
  11112. \LangVecM{} &::=& \Exp
  11113. \end{array}
  11114. \end{array}
  11115. \]
  11116. \fi}
  11117. {\if\edition\pythonEd
  11118. \[
  11119. \begin{array}{l}
  11120. \gray{\LintGrammarPython{}} \\ \hline
  11121. \gray{\LvarGrammarPython{}} \\ \hline
  11122. \gray{\LifGrammarPython{}} \\ \hline
  11123. \gray{\LwhileGrammarPython} \\ \hline
  11124. \LtupGrammarPython \\
  11125. \begin{array}{rcl}
  11126. \LangVecM{} &::=& \Stmt^{*}
  11127. \end{array}
  11128. \end{array}
  11129. \]
  11130. \fi}
  11131. \end{tcolorbox}
  11132. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11133. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11134. \label{fig:Lvec-concrete-syntax}
  11135. \end{figure}
  11136. \begin{figure}[tp]
  11137. \centering
  11138. \begin{tcolorbox}[colback=white]
  11139. \small
  11140. {\if\edition\racketEd
  11141. \[
  11142. \begin{array}{l}
  11143. \gray{\LintOpAST} \\ \hline
  11144. \gray{\LvarASTRacket{}} \\ \hline
  11145. \gray{\LifASTRacket{}} \\ \hline
  11146. \gray{\LwhileASTRacket{}} \\ \hline
  11147. \LtupASTRacket{} \\
  11148. \begin{array}{lcl}
  11149. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11150. \end{array}
  11151. \end{array}
  11152. \]
  11153. \fi}
  11154. {\if\edition\pythonEd
  11155. \[
  11156. \begin{array}{l}
  11157. \gray{\LintASTPython} \\ \hline
  11158. \gray{\LvarASTPython} \\ \hline
  11159. \gray{\LifASTPython} \\ \hline
  11160. \gray{\LwhileASTPython} \\ \hline
  11161. \LtupASTPython \\
  11162. \begin{array}{lcl}
  11163. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11164. \end{array}
  11165. \end{array}
  11166. \]
  11167. \fi}
  11168. \end{tcolorbox}
  11169. \caption{The abstract syntax of \LangVec{}.}
  11170. \label{fig:Lvec-syntax}
  11171. \end{figure}
  11172. Tuples raise several interesting new issues. First, variable binding
  11173. performs a shallow copy in dealing with tuples, which means that
  11174. different variables can refer to the same tuple; that is, two
  11175. variables can be \emph{aliases}\index{subject}{alias} for the same
  11176. entity. Consider the following example, in which \code{t1} and
  11177. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11178. different tuple value with equal elements. The result of the
  11179. program is \code{42}.
  11180. \begin{center}
  11181. \begin{minipage}{0.96\textwidth}
  11182. {\if\edition\racketEd
  11183. \begin{lstlisting}
  11184. (let ([t1 (vector 3 7)])
  11185. (let ([t2 t1])
  11186. (let ([t3 (vector 3 7)])
  11187. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11188. 42
  11189. 0))))
  11190. \end{lstlisting}
  11191. \fi}
  11192. {\if\edition\pythonEd
  11193. \begin{lstlisting}
  11194. t1 = 3, 7
  11195. t2 = t1
  11196. t3 = 3, 7
  11197. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  11198. \end{lstlisting}
  11199. \fi}
  11200. \end{minipage}
  11201. \end{center}
  11202. {\if\edition\racketEd
  11203. Whether two variables are aliased or not affects what happens
  11204. when the underlying tuple is mutated\index{subject}{mutation}.
  11205. Consider the following example in which \code{t1} and \code{t2}
  11206. again refer to the same tuple value.
  11207. \begin{center}
  11208. \begin{minipage}{0.96\textwidth}
  11209. \begin{lstlisting}
  11210. (let ([t1 (vector 3 7)])
  11211. (let ([t2 t1])
  11212. (let ([_ (vector-set! t2 0 42)])
  11213. (vector-ref t1 0))))
  11214. \end{lstlisting}
  11215. \end{minipage}
  11216. \end{center}
  11217. The mutation through \code{t2} is visible in referencing the tuple
  11218. from \code{t1}, so the result of this program is \code{42}.
  11219. \fi}
  11220. The next issue concerns the lifetime of tuples. When does a tuple's
  11221. lifetime end? Notice that \LangVec{} does not include an operation
  11222. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11223. to any notion of static scoping.
  11224. %
  11225. {\if\edition\racketEd
  11226. %
  11227. For example, the following program returns \code{42} even though the
  11228. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11229. that reads from the vector to which it was bound.
  11230. \begin{center}
  11231. \begin{minipage}{0.96\textwidth}
  11232. \begin{lstlisting}
  11233. (let ([v (vector (vector 44))])
  11234. (let ([x (let ([w (vector 42)])
  11235. (let ([_ (vector-set! v 0 w)])
  11236. 0))])
  11237. (+ x (vector-ref (vector-ref v 0) 0))))
  11238. \end{lstlisting}
  11239. \end{minipage}
  11240. \end{center}
  11241. \fi}
  11242. %
  11243. {\if\edition\pythonEd
  11244. %
  11245. For example, the following program returns \code{42} even though the
  11246. variable \code{x} goes out of scope when the function returns, prior
  11247. to reading the tuple element at index zero. (We study the compilation
  11248. of functions in chapter~\ref{ch:Lfun}.)
  11249. %
  11250. \begin{center}
  11251. \begin{minipage}{0.96\textwidth}
  11252. \begin{lstlisting}
  11253. def f():
  11254. x = 42, 43
  11255. return x
  11256. t = f()
  11257. print( t[0] )
  11258. \end{lstlisting}
  11259. \end{minipage}
  11260. \end{center}
  11261. \fi}
  11262. %
  11263. From the perspective of programmer-observable behavior, tuples live
  11264. forever. However, if they really lived forever then many long-running
  11265. programs would run out of memory. To solve this problem, the
  11266. language's runtime system performs automatic garbage collection.
  11267. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11268. \LangVec{} language.
  11269. %
  11270. \racket{We define the \code{vector}, \code{vector-ref},
  11271. \code{vector-set!}, and \code{vector-length} operations for
  11272. \LangVec{} in terms of the corresponding operations in Racket. One
  11273. subtle point is that the \code{vector-set!} operation returns the
  11274. \code{\#<void>} value.}
  11275. %
  11276. \python{We represent tuples with Python lists in the interpreter
  11277. because we need to write to them
  11278. (section~\ref{sec:expose-allocation}). (Python tuples are
  11279. immutable.) We define element access, the \code{is} operator, and
  11280. the \code{len} operator for \LangVec{} in terms of the corresponding
  11281. operations in Python.}
  11282. \begin{figure}[tbp]
  11283. \begin{tcolorbox}[colback=white]
  11284. {\if\edition\racketEd
  11285. \begin{lstlisting}
  11286. (define interp-Lvec-class
  11287. (class interp-Lwhile-class
  11288. (super-new)
  11289. (define/override (interp-op op)
  11290. (match op
  11291. ['eq? (lambda (v1 v2)
  11292. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11293. (and (boolean? v1) (boolean? v2))
  11294. (and (vector? v1) (vector? v2))
  11295. (and (void? v1) (void? v2)))
  11296. (eq? v1 v2)]))]
  11297. ['vector vector]
  11298. ['vector-length vector-length]
  11299. ['vector-ref vector-ref]
  11300. ['vector-set! vector-set!]
  11301. [else (super interp-op op)]
  11302. ))
  11303. (define/override ((interp-exp env) e)
  11304. (match e
  11305. [(HasType e t) ((interp-exp env) e)]
  11306. [else ((super interp-exp env) e)]
  11307. ))
  11308. ))
  11309. (define (interp-Lvec p)
  11310. (send (new interp-Lvec-class) interp-program p))
  11311. \end{lstlisting}
  11312. \fi}
  11313. %
  11314. {\if\edition\pythonEd
  11315. \begin{lstlisting}
  11316. class InterpLtup(InterpLwhile):
  11317. def interp_cmp(self, cmp):
  11318. match cmp:
  11319. case Is():
  11320. return lambda x, y: x is y
  11321. case _:
  11322. return super().interp_cmp(cmp)
  11323. def interp_exp(self, e, env):
  11324. match e:
  11325. case Tuple(es, Load()):
  11326. return tuple([self.interp_exp(e, env) for e in es])
  11327. case Subscript(tup, index, Load()):
  11328. t = self.interp_exp(tup, env)
  11329. n = self.interp_exp(index, env)
  11330. return t[n]
  11331. case _:
  11332. return super().interp_exp(e, env)
  11333. \end{lstlisting}
  11334. \fi}
  11335. \end{tcolorbox}
  11336. \caption{Interpreter for the \LangVec{} language.}
  11337. \label{fig:interp-Lvec}
  11338. \end{figure}
  11339. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11340. \LangVec{}.
  11341. %
  11342. The type of a tuple is a
  11343. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11344. type for each of its elements.
  11345. %
  11346. \racket{To create the s-expression for the \code{Vector} type, we use the
  11347. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11348. operator} \code{,@} to insert the list \code{t*} without its usual
  11349. start and end parentheses. \index{subject}{unquote-splicing}}
  11350. %
  11351. The type of accessing the ith element of a tuple is the ith element
  11352. type of the tuple's type, if there is one. If not, an error is
  11353. signaled. Note that the index \code{i} is required to be a constant
  11354. integer (and not, for example, a call to
  11355. \racket{\code{read}}\python{input\_int}) so that the type checker
  11356. can determine the element's type given the tuple type.
  11357. %
  11358. \racket{
  11359. Regarding writing an element to a tuple, the element's type must
  11360. be equal to the ith element type of the tuple's type.
  11361. The result type is \code{Void}.}
  11362. %% When allocating a tuple,
  11363. %% we need to know which elements of the tuple are themselves tuples for
  11364. %% the purposes of garbage collection. We can obtain this information
  11365. %% during type checking. The type checker shown in
  11366. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11367. %% expression; it also
  11368. %% %
  11369. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11370. %% where $T$ is the tuple's type.
  11371. %
  11372. %records the type of each tuple expression in a new field named \code{has\_type}.
  11373. \begin{figure}[tp]
  11374. \begin{tcolorbox}[colback=white]
  11375. {\if\edition\racketEd
  11376. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11377. (define type-check-Lvec-class
  11378. (class type-check-Lif-class
  11379. (super-new)
  11380. (inherit check-type-equal?)
  11381. (define/override (type-check-exp env)
  11382. (lambda (e)
  11383. (define recur (type-check-exp env))
  11384. (match e
  11385. [(Prim 'vector es)
  11386. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11387. (define t `(Vector ,@t*))
  11388. (values (Prim 'vector e*) t)]
  11389. [(Prim 'vector-ref (list e1 (Int i)))
  11390. (define-values (e1^ t) (recur e1))
  11391. (match t
  11392. [`(Vector ,ts ...)
  11393. (unless (and (0 . <= . i) (i . < . (length ts)))
  11394. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11395. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11396. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11397. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11398. (define-values (e-vec t-vec) (recur e1))
  11399. (define-values (e-elt^ t-elt) (recur elt))
  11400. (match t-vec
  11401. [`(Vector ,ts ...)
  11402. (unless (and (0 . <= . i) (i . < . (length ts)))
  11403. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11404. (check-type-equal? (list-ref ts i) t-elt e)
  11405. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11406. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11407. [(Prim 'vector-length (list e))
  11408. (define-values (e^ t) (recur e))
  11409. (match t
  11410. [`(Vector ,ts ...)
  11411. (values (Prim 'vector-length (list e^)) 'Integer)]
  11412. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11413. [(Prim 'eq? (list arg1 arg2))
  11414. (define-values (e1 t1) (recur arg1))
  11415. (define-values (e2 t2) (recur arg2))
  11416. (match* (t1 t2)
  11417. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11418. [(other wise) (check-type-equal? t1 t2 e)])
  11419. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11420. [else ((super type-check-exp env) e)]
  11421. )))
  11422. ))
  11423. (define (type-check-Lvec p)
  11424. (send (new type-check-Lvec-class) type-check-program p))
  11425. \end{lstlisting}
  11426. \fi}
  11427. {\if\edition\pythonEd
  11428. \begin{lstlisting}
  11429. class TypeCheckLtup(TypeCheckLwhile):
  11430. def type_check_exp(self, e, env):
  11431. match e:
  11432. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11433. l = self.type_check_exp(left, env)
  11434. r = self.type_check_exp(right, env)
  11435. check_type_equal(l, r, e)
  11436. return bool
  11437. case Tuple(es, Load()):
  11438. ts = [self.type_check_exp(e, env) for e in es]
  11439. e.has_type = TupleType(ts)
  11440. return e.has_type
  11441. case Subscript(tup, Constant(i), Load()):
  11442. tup_ty = self.type_check_exp(tup, env)
  11443. i_ty = self.type_check_exp(Constant(i), env)
  11444. check_type_equal(i_ty, int, i)
  11445. match tup_ty:
  11446. case TupleType(ts):
  11447. return ts[i]
  11448. case _:
  11449. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11450. case _:
  11451. return super().type_check_exp(e, env)
  11452. \end{lstlisting}
  11453. \fi}
  11454. \end{tcolorbox}
  11455. \caption{Type checker for the \LangVec{} language.}
  11456. \label{fig:type-check-Lvec}
  11457. \end{figure}
  11458. \section{Garbage Collection}
  11459. \label{sec:GC}
  11460. Garbage collection is a runtime technique for reclaiming space on the
  11461. heap that will not be used in the future of the running program. We
  11462. use the term \emph{object}\index{subject}{object} to refer to any
  11463. value that is stored in the heap, which for now includes only
  11464. tuples.%
  11465. %
  11466. \footnote{The term \emph{object} as it is used in the context of
  11467. object-oriented programming has a more specific meaning than the
  11468. way in which we use the term here.}
  11469. %
  11470. Unfortunately, it is impossible to know precisely which objects will
  11471. be accessed in the future and which will not. Instead, garbage
  11472. collectors overapproximate the set of objects that will be accessed by
  11473. identifying which objects can possibly be accessed. The running
  11474. program can directly access objects that are in registers and on the
  11475. procedure call stack. It can also transitively access the elements of
  11476. tuples, starting with a tuple whose address is in a register or on the
  11477. procedure call stack. We define the \emph{root
  11478. set}\index{subject}{root set} to be all the tuple addresses that are
  11479. in registers or on the procedure call stack. We define the \emph{live
  11480. objects}\index{subject}{live objects} to be the objects that are
  11481. reachable from the root set. Garbage collectors reclaim the space that
  11482. is allocated to objects that are no longer live. That means that some
  11483. objects may not get reclaimed as soon as they could be, but at least
  11484. garbage collectors do not reclaim the space dedicated to objects that
  11485. will be accessed in the future! The programmer can influence which
  11486. objects get reclaimed by causing them to become unreachable.
  11487. So the goal of the garbage collector is twofold:
  11488. \begin{enumerate}
  11489. \item to preserve all the live objects, and
  11490. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11491. \end{enumerate}
  11492. \subsection{Two-Space Copying Collector}
  11493. Here we study a relatively simple algorithm for garbage collection
  11494. that is the basis of many state-of-the-art garbage
  11495. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11496. particular, we describe a two-space copying
  11497. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11498. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11499. collector} \index{subject}{two-space copying collector}
  11500. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11501. what happens in a two-space collector, showing two time steps, prior
  11502. to garbage collection (on the top) and after garbage collection (on
  11503. the bottom). In a two-space collector, the heap is divided into two
  11504. parts named the FromSpace\index{subject}{FromSpace} and the
  11505. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11506. FromSpace until there is not enough room for the next allocation
  11507. request. At that point, the garbage collector goes to work to make
  11508. room for the next allocation.
  11509. A copying collector makes more room by copying all the live objects
  11510. from the FromSpace into the ToSpace and then performs a sleight of
  11511. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11512. as the new ToSpace. In the example shown in
  11513. figure~\ref{fig:copying-collector}, the root set consists of three
  11514. pointers, one in a register and two on the stack. All the live
  11515. objects have been copied to the ToSpace (the right-hand side of
  11516. figure~\ref{fig:copying-collector}) in a way that preserves the
  11517. pointer relationships. For example, the pointer in the register still
  11518. points to a tuple that in turn points to two other tuples. There are
  11519. four tuples that are not reachable from the root set and therefore do
  11520. not get copied into the ToSpace.
  11521. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11522. created by a well-typed program in \LangVec{} because it contains a
  11523. cycle. However, creating cycles will be possible once we get to
  11524. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11525. to deal with cycles to begin with, so we will not need to revisit this
  11526. issue.
  11527. \begin{figure}[tbp]
  11528. \centering
  11529. \begin{tcolorbox}[colback=white]
  11530. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11531. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11532. \\[5ex]
  11533. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11534. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11535. \end{tcolorbox}
  11536. \caption{A copying collector in action.}
  11537. \label{fig:copying-collector}
  11538. \end{figure}
  11539. \subsection{Graph Copying via Cheney's Algorithm}
  11540. \label{sec:cheney}
  11541. \index{subject}{Cheney's algorithm}
  11542. Let us take a closer look at the copying of the live objects. The
  11543. allocated objects and pointers can be viewed as a graph, and we need to
  11544. copy the part of the graph that is reachable from the root set. To
  11545. make sure that we copy all the reachable vertices in the graph, we need
  11546. an exhaustive graph traversal algorithm, such as depth-first search or
  11547. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  11548. such algorithms take into account the possibility of cycles by marking
  11549. which vertices have already been visited, so to ensure termination
  11550. of the algorithm. These search algorithms also use a data structure
  11551. such as a stack or queue as a to-do list to keep track of the vertices
  11552. that need to be visited. We use breadth-first search and a trick
  11553. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  11554. and copying tuples into the ToSpace.
  11555. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11556. copy progresses. The queue is represented by a chunk of contiguous
  11557. memory at the beginning of the ToSpace, using two pointers to track
  11558. the front and the back of the queue, called the \emph{free pointer}
  11559. and the \emph{scan pointer}, respectively. The algorithm starts by
  11560. copying all tuples that are immediately reachable from the root set
  11561. into the ToSpace to form the initial queue. When we copy a tuple, we
  11562. mark the old tuple to indicate that it has been visited. We discuss
  11563. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11564. that any pointers inside the copied tuples in the queue still point
  11565. back to the FromSpace. Once the initial queue has been created, the
  11566. algorithm enters a loop in which it repeatedly processes the tuple at
  11567. the front of the queue and pops it off the queue. To process a tuple,
  11568. the algorithm copies all the objects that are directly reachable from it
  11569. to the ToSpace, placing them at the back of the queue. The algorithm
  11570. then updates the pointers in the popped tuple so that they point to the
  11571. newly copied objects.
  11572. \begin{figure}[tbp]
  11573. \centering
  11574. \begin{tcolorbox}[colback=white]
  11575. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  11576. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  11577. \end{tcolorbox}
  11578. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11579. \label{fig:cheney}
  11580. \end{figure}
  11581. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11582. tuple whose second element is $42$ to the back of the queue. The other
  11583. pointer goes to a tuple that has already been copied, so we do not
  11584. need to copy it again, but we do need to update the pointer to the new
  11585. location. This can be accomplished by storing a \emph{forwarding
  11586. pointer}\index{subject}{forwarding pointer} to the new location in the
  11587. old tuple, when we initially copied the tuple into the
  11588. ToSpace. This completes one step of the algorithm. The algorithm
  11589. continues in this way until the queue is empty; that is, when the scan
  11590. pointer catches up with the free pointer.
  11591. \subsection{Data Representation}
  11592. \label{sec:data-rep-gc}
  11593. The garbage collector places some requirements on the data
  11594. representations used by our compiler. First, the garbage collector
  11595. needs to distinguish between pointers and other kinds of data such as
  11596. integers. The following are several ways to accomplish this:
  11597. \begin{enumerate}
  11598. \item Attach a tag to each object that identifies what type of
  11599. object it is~\citep{McCarthy:1960dz}.
  11600. \item Store different types of objects in different
  11601. regions~\citep{Steele:1977ab}.
  11602. \item Use type information from the program to either (a) generate
  11603. type-specific code for collecting, or (b) generate tables that
  11604. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11605. \end{enumerate}
  11606. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11607. need to tag objects in any case, so option 1 is a natural choice for those
  11608. languages. However, \LangVec{} is a statically typed language, so it
  11609. would be unfortunate to require tags on every object, especially small
  11610. and pervasive objects like integers and Booleans. Option 3 is the
  11611. best-performing choice for statically typed languages, but it comes with
  11612. a relatively high implementation complexity. To keep this chapter
  11613. within a reasonable scope of complexity, we recommend a combination of options
  11614. 1 and 2, using separate strategies for the stack and the heap.
  11615. Regarding the stack, we recommend using a separate stack for pointers,
  11616. which we call the \emph{root stack}\index{subject}{root stack}
  11617. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11618. That is, when a local variable needs to be spilled and is of type
  11619. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11620. root stack instead of putting it on the procedure call
  11621. stack. Furthermore, we always spill tuple-typed variables if they are
  11622. live during a call to the collector, thereby ensuring that no pointers
  11623. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11624. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11625. contrasts it with the data layout using a root stack. The root stack
  11626. contains the two pointers from the regular stack and also the pointer
  11627. in the second register.
  11628. \begin{figure}[tbp]
  11629. \centering
  11630. \begin{tcolorbox}[colback=white]
  11631. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11632. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11633. \end{tcolorbox}
  11634. \caption{Maintaining a root stack to facilitate garbage collection.}
  11635. \label{fig:shadow-stack}
  11636. \end{figure}
  11637. The problem of distinguishing between pointers and other kinds of data
  11638. also arises inside each tuple on the heap. We solve this problem by
  11639. attaching a tag, an extra 64 bits, to each
  11640. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11641. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11642. Note that we have drawn the bits in a big-endian way, from right to left,
  11643. with bit location 0 (the least significant bit) on the far right,
  11644. which corresponds to the direction of the x86 shifting instructions
  11645. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11646. is dedicated to specifying which elements of the tuple are pointers,
  11647. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11648. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11649. data. The pointer mask starts at bit location 7. We limit tuples to a
  11650. maximum size of fifty elements, so we need 50 bits for the pointer
  11651. mask.%
  11652. %
  11653. \footnote{A production-quality compiler would handle
  11654. arbitrarily sized tuples and use a more complex approach.}
  11655. %
  11656. The tag also contains two other pieces of information. The length of
  11657. the tuple (number of elements) is stored in bits at locations 1 through
  11658. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11659. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11660. has not yet been copied. If the bit has value 0, then the entire tag
  11661. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11662. zero in any case, because our tuples are 8-byte aligned.)
  11663. \begin{figure}[tbp]
  11664. \centering
  11665. \begin{tcolorbox}[colback=white]
  11666. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11667. \end{tcolorbox}
  11668. \caption{Representation of tuples in the heap.}
  11669. \label{fig:tuple-rep}
  11670. \end{figure}
  11671. \subsection{Implementation of the Garbage Collector}
  11672. \label{sec:organize-gz}
  11673. \index{subject}{prelude}
  11674. An implementation of the copying collector is provided in the
  11675. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11676. interface to the garbage collector that is used by the compiler. The
  11677. \code{initialize} function creates the FromSpace, ToSpace, and root
  11678. stack and should be called in the prelude of the \code{main}
  11679. function. The arguments of \code{initialize} are the root stack size
  11680. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11681. good choice for both. The \code{initialize} function puts the address
  11682. of the beginning of the FromSpace into the global variable
  11683. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11684. the address that is one past the last element of the FromSpace. We use
  11685. half-open intervals to represent chunks of
  11686. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11687. points to the first element of the root stack.
  11688. As long as there is room left in the FromSpace, your generated code
  11689. can allocate tuples simply by moving the \code{free\_ptr} forward.
  11690. %
  11691. The amount of room left in the FromSpace is the difference between the
  11692. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11693. function should be called when there is not enough room left in the
  11694. FromSpace for the next allocation. The \code{collect} function takes
  11695. a pointer to the current top of the root stack (one past the last item
  11696. that was pushed) and the number of bytes that need to be
  11697. allocated. The \code{collect} function performs the copying collection
  11698. and leaves the heap in a state such that there is enough room for the
  11699. next allocation.
  11700. \begin{figure}[tbp]
  11701. \begin{tcolorbox}[colback=white]
  11702. \begin{lstlisting}
  11703. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11704. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11705. int64_t* free_ptr;
  11706. int64_t* fromspace_begin;
  11707. int64_t* fromspace_end;
  11708. int64_t** rootstack_begin;
  11709. \end{lstlisting}
  11710. \end{tcolorbox}
  11711. \caption{The compiler's interface to the garbage collector.}
  11712. \label{fig:gc-header}
  11713. \end{figure}
  11714. %% \begin{exercise}
  11715. %% In the file \code{runtime.c} you will find the implementation of
  11716. %% \code{initialize} and a partial implementation of \code{collect}.
  11717. %% The \code{collect} function calls another function, \code{cheney},
  11718. %% to perform the actual copy, and that function is left to the reader
  11719. %% to implement. The following is the prototype for \code{cheney}.
  11720. %% \begin{lstlisting}
  11721. %% static void cheney(int64_t** rootstack_ptr);
  11722. %% \end{lstlisting}
  11723. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11724. %% rootstack (which is an array of pointers). The \code{cheney} function
  11725. %% also communicates with \code{collect} through the global
  11726. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11727. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11728. %% the ToSpace:
  11729. %% \begin{lstlisting}
  11730. %% static int64_t* tospace_begin;
  11731. %% static int64_t* tospace_end;
  11732. %% \end{lstlisting}
  11733. %% The job of the \code{cheney} function is to copy all the live
  11734. %% objects (reachable from the root stack) into the ToSpace, update
  11735. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11736. %% update the root stack so that it points to the objects in the
  11737. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11738. %% and ToSpace.
  11739. %% \end{exercise}
  11740. The introduction of garbage collection has a nontrivial impact on our
  11741. compiler passes. We introduce a new compiler pass named
  11742. \code{expose\_allocation} that elaborates the code for allocating
  11743. tuples. We also make significant changes to
  11744. \code{select\_instructions}, \code{build\_interference},
  11745. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11746. make minor changes in several more passes.
  11747. The following program serves as our running example. It creates
  11748. two tuples, one nested inside the other. Both tuples have length
  11749. one. The program accesses the element in the inner tuple.
  11750. % tests/vectors_test_17.rkt
  11751. {\if\edition\racketEd
  11752. \begin{lstlisting}
  11753. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11754. \end{lstlisting}
  11755. \fi}
  11756. {\if\edition\pythonEd
  11757. \begin{lstlisting}
  11758. print( ((42,),)[0][0] )
  11759. \end{lstlisting}
  11760. \fi}
  11761. %% {\if\edition\racketEd
  11762. %% \section{Shrink}
  11763. %% \label{sec:shrink-Lvec}
  11764. %% Recall that the \code{shrink} pass translates the primitives operators
  11765. %% into a smaller set of primitives.
  11766. %% %
  11767. %% This pass comes after type checking, and the type checker adds a
  11768. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11769. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11770. %% \fi}
  11771. \section{Expose Allocation}
  11772. \label{sec:expose-allocation}
  11773. The pass \code{expose\_allocation} lowers tuple creation into making a
  11774. conditional call to the collector followed by allocating the
  11775. appropriate amount of memory and initializing it. We choose to place
  11776. the \code{expose\_allocation} pass before
  11777. \code{remove\_complex\_operands} because it generates
  11778. code that contains complex operands.
  11779. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11780. that replaces tuple creation with new lower-level forms that we use in the
  11781. translation of tuple creation.
  11782. %
  11783. {\if\edition\racketEd
  11784. \[
  11785. \begin{array}{lcl}
  11786. \Exp &::=& \cdots
  11787. \MID (\key{collect} \,\itm{int})
  11788. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11789. \MID (\key{global-value} \,\itm{name})
  11790. \end{array}
  11791. \]
  11792. \fi}
  11793. {\if\edition\pythonEd
  11794. \[
  11795. \begin{array}{lcl}
  11796. \Exp &::=& \cdots\\
  11797. &\MID& \key{collect}(\itm{int})
  11798. \MID \key{allocate}(\itm{int},\itm{type})
  11799. \MID \key{global\_value}(\itm{name}) \\
  11800. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11801. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11802. \end{array}
  11803. \]
  11804. \fi}
  11805. %
  11806. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11807. make sure that there are $n$ bytes ready to be allocated. During
  11808. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11809. the \code{collect} function in \code{runtime.c}.
  11810. %
  11811. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11812. space at the front for the 64-bit tag), but the elements are not
  11813. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11814. of the tuple:
  11815. %
  11816. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11817. %
  11818. where $\Type_i$ is the type of the $i$th element.
  11819. %
  11820. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11821. variable, such as \code{free\_ptr}.
  11822. %
  11823. \python{The \code{begin} form is an expression that executes a
  11824. sequence of statements and then produces the value of the expression
  11825. at the end.}
  11826. \racket{
  11827. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11828. can be obtained by running the
  11829. \code{type-check-Lvec-has-type} type checker immediately before the
  11830. \code{expose\_allocation} pass. This version of the type checker
  11831. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11832. around each tuple creation. The concrete syntax
  11833. for \code{HasType} is \code{has-type}.}
  11834. The following shows the transformation of tuple creation into (1) a
  11835. sequence of temporary variable bindings for the initializing
  11836. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11837. \code{allocate}, and (4) the initialization of the tuple. The
  11838. \itm{len} placeholder refers to the length of the tuple, and
  11839. \itm{bytes} is the total number of bytes that need to be allocated for
  11840. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11841. %
  11842. \python{The \itm{type} needed for the second argument of the
  11843. \code{allocate} form can be obtained from the \code{has\_type} field
  11844. of the tuple AST node, which is stored there by running the type
  11845. checker for \LangVec{} immediately before this pass.}
  11846. %
  11847. \begin{center}
  11848. \begin{minipage}{\textwidth}
  11849. {\if\edition\racketEd
  11850. \begin{lstlisting}
  11851. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11852. |$\Longrightarrow$|
  11853. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11854. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11855. (global-value fromspace_end))
  11856. (void)
  11857. (collect |\itm{bytes}|))])
  11858. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11859. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11860. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11861. |$v$|) ... )))) ...)
  11862. \end{lstlisting}
  11863. \fi}
  11864. {\if\edition\pythonEd
  11865. \begin{lstlisting}
  11866. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11867. |$\Longrightarrow$|
  11868. begin:
  11869. |$x_0$| = |$e_0$|
  11870. |$\vdots$|
  11871. |$x_{n-1}$| = |$e_{n-1}$|
  11872. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11873. 0
  11874. else:
  11875. collect(|\itm{bytes}|)
  11876. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11877. |$v$|[0] = |$x_0$|
  11878. |$\vdots$|
  11879. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11880. |$v$|
  11881. \end{lstlisting}
  11882. \fi}
  11883. \end{minipage}
  11884. \end{center}
  11885. %
  11886. \noindent The sequencing of the initializing expressions
  11887. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11888. they may trigger garbage collection and we cannot have an allocated
  11889. but uninitialized tuple on the heap during a collection.
  11890. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11891. \code{expose\_allocation} pass on our running example.
  11892. \begin{figure}[tbp]
  11893. \begin{tcolorbox}[colback=white]
  11894. % tests/s2_17.rkt
  11895. {\if\edition\racketEd
  11896. \begin{lstlisting}
  11897. (vector-ref
  11898. (vector-ref
  11899. (let ([vecinit6
  11900. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11901. (global-value fromspace_end))
  11902. (void)
  11903. (collect 16))])
  11904. (let ([alloc2 (allocate 1 (Vector Integer))])
  11905. (let ([_3 (vector-set! alloc2 0 42)])
  11906. alloc2)))])
  11907. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11908. (global-value fromspace_end))
  11909. (void)
  11910. (collect 16))])
  11911. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11912. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11913. alloc5))))
  11914. 0)
  11915. 0)
  11916. \end{lstlisting}
  11917. \fi}
  11918. {\if\edition\pythonEd
  11919. \begin{lstlisting}
  11920. print( |$T_1$|[0][0] )
  11921. \end{lstlisting}
  11922. where $T_1$ is
  11923. \begin{lstlisting}
  11924. begin:
  11925. tmp.1 = |$T_2$|
  11926. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11927. 0
  11928. else:
  11929. collect(16)
  11930. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11931. tmp.2[0] = tmp.1
  11932. tmp.2
  11933. \end{lstlisting}
  11934. and $T_2$ is
  11935. \begin{lstlisting}
  11936. begin:
  11937. tmp.3 = 42
  11938. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11939. 0
  11940. else:
  11941. collect(16)
  11942. tmp.4 = allocate(1, TupleType([int]))
  11943. tmp.4[0] = tmp.3
  11944. tmp.4
  11945. \end{lstlisting}
  11946. \fi}
  11947. \end{tcolorbox}
  11948. \caption{Output of the \code{expose\_allocation} pass.}
  11949. \label{fig:expose-alloc-output}
  11950. \end{figure}
  11951. \section{Remove Complex Operands}
  11952. \label{sec:remove-complex-opera-Lvec}
  11953. {\if\edition\racketEd
  11954. %
  11955. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11956. should be treated as complex operands.
  11957. %
  11958. \fi}
  11959. %
  11960. {\if\edition\pythonEd
  11961. %
  11962. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11963. and tuple access should be treated as complex operands. The
  11964. sub-expressions of tuple access must be atomic.
  11965. %
  11966. \fi}
  11967. %% A new case for
  11968. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11969. %% handled carefully to prevent the \code{Prim} node from being separated
  11970. %% from its enclosing \code{HasType}.
  11971. Figure~\ref{fig:Lvec-anf-syntax}
  11972. shows the grammar for the output language \LangAllocANF{} of this
  11973. pass, which is \LangAlloc{} in monadic normal form.
  11974. \newcommand{\LtupMonadASTRacket}{
  11975. \begin{array}{rcl}
  11976. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11977. \MID \GLOBALVALUE{\Var}
  11978. \end{array}
  11979. }
  11980. \newcommand{\LtupMonadASTPython}{
  11981. \begin{array}{rcl}
  11982. \Exp &::=& \GET{\Atm}{\Atm} \\
  11983. &\MID& \LEN{\Atm}\\
  11984. &\MID& \ALLOCATE{\Int}{\Type}
  11985. \MID \GLOBALVALUE{\Var} \\
  11986. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11987. &\MID& \COLLECT{\Int}
  11988. \end{array}
  11989. }
  11990. \begin{figure}[tp]
  11991. \centering
  11992. \begin{tcolorbox}[colback=white]
  11993. \small
  11994. {\if\edition\racketEd
  11995. \[
  11996. \begin{array}{l}
  11997. \gray{\LvarMonadASTRacket} \\ \hline
  11998. \gray{\LifMonadASTRacket} \\ \hline
  11999. \gray{\LwhileMonadASTRacket} \\ \hline
  12000. \LtupMonadASTRacket \\
  12001. \begin{array}{rcl}
  12002. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12003. \end{array}
  12004. \end{array}
  12005. \]
  12006. \fi}
  12007. {\if\edition\pythonEd
  12008. \[
  12009. \begin{array}{l}
  12010. \gray{\LvarMonadASTPython} \\ \hline
  12011. \gray{\LifMonadASTPython} \\ \hline
  12012. \gray{\LwhileMonadASTPython} \\ \hline
  12013. \LtupMonadASTPython \\
  12014. \begin{array}{rcl}
  12015. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12016. \end{array}
  12017. \end{array}
  12018. \]
  12019. \fi}
  12020. \end{tcolorbox}
  12021. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12022. \label{fig:Lvec-anf-syntax}
  12023. \end{figure}
  12024. \section{Explicate Control and the \LangCVec{} language}
  12025. \label{sec:explicate-control-r3}
  12026. \newcommand{\CtupASTRacket}{
  12027. \begin{array}{lcl}
  12028. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12029. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12030. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12031. &\MID& \VECLEN{\Atm} \\
  12032. &\MID& \GLOBALVALUE{\Var} \\
  12033. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12034. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12035. \end{array}
  12036. }
  12037. \newcommand{\CtupASTPython}{
  12038. \begin{array}{lcl}
  12039. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12040. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12041. \Stmt &::=& \COLLECT{\Int} \\
  12042. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12043. \end{array}
  12044. }
  12045. \begin{figure}[tp]
  12046. \begin{tcolorbox}[colback=white]
  12047. \small
  12048. {\if\edition\racketEd
  12049. \[
  12050. \begin{array}{l}
  12051. \gray{\CvarASTRacket} \\ \hline
  12052. \gray{\CifASTRacket} \\ \hline
  12053. \gray{\CloopASTRacket} \\ \hline
  12054. \CtupASTRacket \\
  12055. \begin{array}{lcl}
  12056. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12057. \end{array}
  12058. \end{array}
  12059. \]
  12060. \fi}
  12061. {\if\edition\pythonEd
  12062. \[
  12063. \begin{array}{l}
  12064. \gray{\CifASTPython} \\ \hline
  12065. \CtupASTPython \\
  12066. \begin{array}{lcl}
  12067. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  12068. \end{array}
  12069. \end{array}
  12070. \]
  12071. \fi}
  12072. \end{tcolorbox}
  12073. \caption{The abstract syntax of \LangCVec{}, extending
  12074. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12075. (figure~\ref{fig:c1-syntax})}.}
  12076. \label{fig:c2-syntax}
  12077. \end{figure}
  12078. The output of \code{explicate\_control} is a program in the
  12079. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12080. shows the definition of the abstract syntax.
  12081. %
  12082. %% \racket{(The concrete syntax is defined in
  12083. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12084. %
  12085. The new expressions of \LangCVec{} include \key{allocate},
  12086. %
  12087. \racket{\key{vector-ref}, and \key{vector-set!},}
  12088. %
  12089. \python{accessing tuple elements,}
  12090. %
  12091. and \key{global\_value}.
  12092. %
  12093. \python{\LangCVec{} also includes the \code{collect} statement and
  12094. assignment to a tuple element.}
  12095. %
  12096. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12097. %
  12098. The \code{explicate\_control} pass can treat these new forms much like
  12099. the other forms that we've already encountered. The output of the
  12100. \code{explicate\_control} pass on the running example is shown on the
  12101. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12102. section.
  12103. \section{Select Instructions and the \LangXGlobal{} Language}
  12104. \label{sec:select-instructions-gc}
  12105. \index{subject}{instruction selection}
  12106. %% void (rep as zero)
  12107. %% allocate
  12108. %% collect (callq collect)
  12109. %% vector-ref
  12110. %% vector-set!
  12111. %% vector-length
  12112. %% global (postpone)
  12113. In this pass we generate x86 code for most of the new operations that
  12114. were needed to compile tuples, including \code{Allocate},
  12115. \code{Collect}, and accessing tuple elements.
  12116. %
  12117. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12118. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12119. \ref{fig:x86-2}). \index{subject}{x86}
  12120. The tuple read and write forms translate into \code{movq}
  12121. instructions. (The $+1$ in the offset serves to move past the tag at the
  12122. beginning of the tuple representation.)
  12123. %
  12124. \begin{center}
  12125. \begin{minipage}{\textwidth}
  12126. {\if\edition\racketEd
  12127. \begin{lstlisting}
  12128. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12129. |$\Longrightarrow$|
  12130. movq |$\itm{tup}'$|, %r11
  12131. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12132. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12133. |$\Longrightarrow$|
  12134. movq |$\itm{tup}'$|, %r11
  12135. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12136. movq $0, |$\itm{lhs'}$|
  12137. \end{lstlisting}
  12138. \fi}
  12139. {\if\edition\pythonEd
  12140. \begin{lstlisting}
  12141. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12142. |$\Longrightarrow$|
  12143. movq |$\itm{tup}'$|, %r11
  12144. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12145. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12146. |$\Longrightarrow$|
  12147. movq |$\itm{tup}'$|, %r11
  12148. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12149. \end{lstlisting}
  12150. \fi}
  12151. \end{minipage}
  12152. \end{center}
  12153. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12154. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12155. are obtained by translating from \LangCVec{} to x86.
  12156. %
  12157. The move of $\itm{tup}'$ to
  12158. register \code{r11} ensures that offset expression
  12159. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12160. removing \code{r11} from consideration by the register allocating.
  12161. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12162. \code{rax}. Then the generated code for tuple assignment would be
  12163. \begin{lstlisting}
  12164. movq |$\itm{tup}'$|, %rax
  12165. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12166. \end{lstlisting}
  12167. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12168. \code{patch\_instructions} would insert a move through \code{rax}
  12169. as follows:
  12170. \begin{lstlisting}
  12171. movq |$\itm{tup}'$|, %rax
  12172. movq |$\itm{rhs}'$|, %rax
  12173. movq %rax, |$8(n+1)$|(%rax)
  12174. \end{lstlisting}
  12175. However, this sequence of instructions does not work, because we're
  12176. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12177. $\itm{rhs}'$) at the same time!
  12178. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12179. be translated into a sequence of instructions that read the tag of the
  12180. tuple and extract the 6 bits that represent the tuple length, which
  12181. are the bits starting at index 1 and going up to and including bit 6.
  12182. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12183. (shift right) can be used to accomplish this.
  12184. We compile the \code{allocate} form to operations on the
  12185. \code{free\_ptr}, as shown next. This approach is called
  12186. \emph{inline allocation} because it implements allocation without a
  12187. function call by simply incrementing the allocation pointer. It is much
  12188. more efficient than calling a function for each allocation. The
  12189. address in the \code{free\_ptr} is the next free address in the
  12190. FromSpace, so we copy it into \code{r11} and then move it forward by
  12191. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12192. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12193. the tag. We then initialize the \itm{tag} and finally copy the
  12194. address in \code{r11} to the left-hand side. Refer to
  12195. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12196. %
  12197. \racket{We recommend using the Racket operations
  12198. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12199. during compilation.}
  12200. %
  12201. \python{We recommend using the bitwise-or operator \code{|} and the
  12202. shift-left operator \code{<<} to compute the tag during
  12203. compilation.}
  12204. %
  12205. The type annotation in the \code{allocate} form is used to determine
  12206. the pointer mask region of the tag.
  12207. %
  12208. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12209. address of the \code{free\_ptr} global variable using a special
  12210. instruction-pointer-relative addressing mode of the x86-64 processor.
  12211. In particular, the assembler computes the distance $d$ between the
  12212. address of \code{free\_ptr} and where the \code{rip} would be at that
  12213. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12214. \code{$d$(\%rip)}, which at runtime will compute the address of
  12215. \code{free\_ptr}.
  12216. %
  12217. {\if\edition\racketEd
  12218. \begin{lstlisting}
  12219. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12220. |$\Longrightarrow$|
  12221. movq free_ptr(%rip), %r11
  12222. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12223. movq $|$\itm{tag}$|, 0(%r11)
  12224. movq %r11, |$\itm{lhs}'$|
  12225. \end{lstlisting}
  12226. \fi}
  12227. {\if\edition\pythonEd
  12228. \begin{lstlisting}
  12229. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12230. |$\Longrightarrow$|
  12231. movq free_ptr(%rip), %r11
  12232. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12233. movq $|$\itm{tag}$|, 0(%r11)
  12234. movq %r11, |$\itm{lhs}'$|
  12235. \end{lstlisting}
  12236. \fi}
  12237. %
  12238. The \code{collect} form is compiled to a call to the \code{collect}
  12239. function in the runtime. The arguments to \code{collect} are (1) the
  12240. top of the root stack, and (2) the number of bytes that need to be
  12241. allocated. We use another dedicated register, \code{r15}, to store
  12242. the pointer to the top of the root stack. Therefore \code{r15} is not
  12243. available for use by the register allocator.
  12244. %
  12245. {\if\edition\racketEd
  12246. \begin{lstlisting}
  12247. (collect |$\itm{bytes}$|)
  12248. |$\Longrightarrow$|
  12249. movq %r15, %rdi
  12250. movq $|\itm{bytes}|, %rsi
  12251. callq collect
  12252. \end{lstlisting}
  12253. \fi}
  12254. {\if\edition\pythonEd
  12255. \begin{lstlisting}
  12256. collect(|$\itm{bytes}$|)
  12257. |$\Longrightarrow$|
  12258. movq %r15, %rdi
  12259. movq $|\itm{bytes}|, %rsi
  12260. callq collect
  12261. \end{lstlisting}
  12262. \fi}
  12263. \newcommand{\GrammarXGlobal}{
  12264. \begin{array}{lcl}
  12265. \Arg &::=& \itm{label} \key{(\%rip)}
  12266. \end{array}
  12267. }
  12268. \newcommand{\ASTXGlobalRacket}{
  12269. \begin{array}{lcl}
  12270. \Arg &::=& \GLOBAL{\itm{label}}
  12271. \end{array}
  12272. }
  12273. \begin{figure}[tp]
  12274. \begin{tcolorbox}[colback=white]
  12275. \[
  12276. \begin{array}{l}
  12277. \gray{\GrammarXInt} \\ \hline
  12278. \gray{\GrammarXIf} \\ \hline
  12279. \GrammarXGlobal \\
  12280. \begin{array}{lcl}
  12281. \LangXGlobalM{} &::= & \key{.globl main} \\
  12282. & & \key{main:} \; \Instr^{*}
  12283. \end{array}
  12284. \end{array}
  12285. \]
  12286. \end{tcolorbox}
  12287. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12288. \label{fig:x86-2-concrete}
  12289. \end{figure}
  12290. \begin{figure}[tp]
  12291. \begin{tcolorbox}[colback=white]
  12292. \small
  12293. \[
  12294. \begin{array}{l}
  12295. \gray{\ASTXIntRacket} \\ \hline
  12296. \gray{\ASTXIfRacket} \\ \hline
  12297. \ASTXGlobalRacket \\
  12298. \begin{array}{lcl}
  12299. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12300. \end{array}
  12301. \end{array}
  12302. \]
  12303. \end{tcolorbox}
  12304. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12305. \label{fig:x86-2}
  12306. \end{figure}
  12307. The definitions of the concrete and abstract syntax of the
  12308. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12309. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12310. of global variables.
  12311. %
  12312. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12313. \code{select\_instructions} pass on the running example.
  12314. \begin{figure}[tbp]
  12315. \centering
  12316. \begin{tcolorbox}[colback=white]
  12317. % tests/s2_17.rkt
  12318. \begin{tabular}{lll}
  12319. \begin{minipage}{0.5\textwidth}
  12320. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12321. start:
  12322. tmp9 = (global-value free_ptr);
  12323. tmp0 = (+ tmp9 16);
  12324. tmp1 = (global-value fromspace_end);
  12325. if (< tmp0 tmp1)
  12326. goto block0;
  12327. else
  12328. goto block1;
  12329. block0:
  12330. _4 = (void);
  12331. goto block9;
  12332. block1:
  12333. (collect 16)
  12334. goto block9;
  12335. block9:
  12336. alloc2 = (allocate 1 (Vector Integer));
  12337. _3 = (vector-set! alloc2 0 42);
  12338. vecinit6 = alloc2;
  12339. tmp2 = (global-value free_ptr);
  12340. tmp3 = (+ tmp2 16);
  12341. tmp4 = (global-value fromspace_end);
  12342. if (< tmp3 tmp4)
  12343. goto block7;
  12344. else
  12345. goto block8;
  12346. block7:
  12347. _8 = (void);
  12348. goto block6;
  12349. block8:
  12350. (collect 16)
  12351. goto block6;
  12352. block6:
  12353. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12354. _7 = (vector-set! alloc5 0 vecinit6);
  12355. tmp5 = (vector-ref alloc5 0);
  12356. return (vector-ref tmp5 0);
  12357. \end{lstlisting}
  12358. \end{minipage}
  12359. &$\Rightarrow$&
  12360. \begin{minipage}{0.4\textwidth}
  12361. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12362. start:
  12363. movq free_ptr(%rip), tmp9
  12364. movq tmp9, tmp0
  12365. addq $16, tmp0
  12366. movq fromspace_end(%rip), tmp1
  12367. cmpq tmp1, tmp0
  12368. jl block0
  12369. jmp block1
  12370. block0:
  12371. movq $0, _4
  12372. jmp block9
  12373. block1:
  12374. movq %r15, %rdi
  12375. movq $16, %rsi
  12376. callq collect
  12377. jmp block9
  12378. block9:
  12379. movq free_ptr(%rip), %r11
  12380. addq $16, free_ptr(%rip)
  12381. movq $3, 0(%r11)
  12382. movq %r11, alloc2
  12383. movq alloc2, %r11
  12384. movq $42, 8(%r11)
  12385. movq $0, _3
  12386. movq alloc2, vecinit6
  12387. movq free_ptr(%rip), tmp2
  12388. movq tmp2, tmp3
  12389. addq $16, tmp3
  12390. movq fromspace_end(%rip), tmp4
  12391. cmpq tmp4, tmp3
  12392. jl block7
  12393. jmp block8
  12394. block7:
  12395. movq $0, _8
  12396. jmp block6
  12397. block8:
  12398. movq %r15, %rdi
  12399. movq $16, %rsi
  12400. callq collect
  12401. jmp block6
  12402. block6:
  12403. movq free_ptr(%rip), %r11
  12404. addq $16, free_ptr(%rip)
  12405. movq $131, 0(%r11)
  12406. movq %r11, alloc5
  12407. movq alloc5, %r11
  12408. movq vecinit6, 8(%r11)
  12409. movq $0, _7
  12410. movq alloc5, %r11
  12411. movq 8(%r11), tmp5
  12412. movq tmp5, %r11
  12413. movq 8(%r11), %rax
  12414. jmp conclusion
  12415. \end{lstlisting}
  12416. \end{minipage}
  12417. \end{tabular}
  12418. \end{tcolorbox}
  12419. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  12420. \code{select\_instructions} (\emph{right}) passes on the running
  12421. example.}
  12422. \label{fig:select-instr-output-gc}
  12423. \end{figure}
  12424. \clearpage
  12425. \section{Register Allocation}
  12426. \label{sec:reg-alloc-gc}
  12427. \index{subject}{register allocation}
  12428. As discussed previously in this chapter, the garbage collector needs to
  12429. access all the pointers in the root set, that is, all variables that
  12430. are tuples. It will be the responsibility of the register allocator
  12431. to make sure that
  12432. \begin{enumerate}
  12433. \item the root stack is used for spilling tuple-typed variables, and
  12434. \item if a tuple-typed variable is live during a call to the
  12435. collector, it must be spilled to ensure that it is visible to the
  12436. collector.
  12437. \end{enumerate}
  12438. The latter responsibility can be handled during construction of the
  12439. interference graph, by adding interference edges between the call-live
  12440. tuple-typed variables and all the callee-saved registers. (They
  12441. already interfere with the caller-saved registers.)
  12442. %
  12443. \racket{The type information for variables is in the \code{Program}
  12444. form, so we recommend adding another parameter to the
  12445. \code{build\_interference} function to communicate this alist.}
  12446. %
  12447. \python{The type information for variables is generated by the type
  12448. checker for \LangCVec{}, stored a field named \code{var\_types} in
  12449. the \code{CProgram} AST mode. You'll need to propagate that
  12450. information so that it is available in this pass.}
  12451. The spilling of tuple-typed variables to the root stack can be handled
  12452. after graph coloring, in choosing how to assign the colors
  12453. (integers) to registers and stack locations. The
  12454. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12455. changes to also record the number of spills to the root stack.
  12456. % build-interference
  12457. %
  12458. % callq
  12459. % extra parameter for var->type assoc. list
  12460. % update 'program' and 'if'
  12461. % allocate-registers
  12462. % allocate spilled vectors to the rootstack
  12463. % don't change color-graph
  12464. % TODO:
  12465. %\section{Patch Instructions}
  12466. %[mention that global variables are memory references]
  12467. \section{Prelude and Conclusion}
  12468. \label{sec:print-x86-gc}
  12469. \label{sec:prelude-conclusion-x86-gc}
  12470. \index{subject}{prelude}\index{subject}{conclusion}
  12471. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12472. \code{prelude\_and\_conclusion} pass on the running example. In the
  12473. prelude of the \code{main} function, we allocate space
  12474. on the root stack to make room for the spills of tuple-typed
  12475. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12476. taking care that the root stack grows up instead of down. For the
  12477. running example, there was just one spill, so we increment \code{r15}
  12478. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12479. One issue that deserves special care is that there may be a call to
  12480. \code{collect} prior to the initializing assignments for all the
  12481. variables in the root stack. We do not want the garbage collector to
  12482. mistakenly determine that some uninitialized variable is a pointer that
  12483. needs to be followed. Thus, we zero out all locations on the root
  12484. stack in the prelude of \code{main}. In
  12485. figure~\ref{fig:print-x86-output-gc}, the instruction
  12486. %
  12487. \lstinline{movq $0, 0(%r15)}
  12488. %
  12489. is sufficient to accomplish this task because there is only one spill.
  12490. In general, we have to clear as many words as there are spills of
  12491. tuple-typed variables. The garbage collector tests each root to see
  12492. if it is null prior to dereferencing it.
  12493. \begin{figure}[htbp]
  12494. % TODO: Python Version -Jeremy
  12495. \begin{tcolorbox}[colback=white]
  12496. \begin{minipage}[t]{0.5\textwidth}
  12497. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12498. .globl main
  12499. main:
  12500. pushq %rbp
  12501. movq %rsp, %rbp
  12502. subq $0, %rsp
  12503. movq $65536, %rdi
  12504. movq $65536, %rsi
  12505. callq initialize
  12506. movq rootstack_begin(%rip), %r15
  12507. movq $0, 0(%r15)
  12508. addq $8, %r15
  12509. jmp start
  12510. conclusion:
  12511. subq $8, %r15
  12512. addq $0, %rsp
  12513. popq %rbp
  12514. retq
  12515. \end{lstlisting}
  12516. \end{minipage}
  12517. \end{tcolorbox}
  12518. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  12519. \label{fig:print-x86-output-gc}
  12520. \end{figure}
  12521. \begin{figure}[tbp]
  12522. \begin{tcolorbox}[colback=white]
  12523. {\if\edition\racketEd
  12524. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12525. \node (Lvec) at (0,2) {\large \LangVec{}};
  12526. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12527. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12528. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12529. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12530. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12531. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12532. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12533. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12534. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12535. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12536. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12537. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12538. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12539. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12540. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12541. \path[->,bend left=15] (Lvec-4) edge [right] node
  12542. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12543. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12544. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12545. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12546. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12547. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12548. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12549. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12550. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12551. \end{tikzpicture}
  12552. \fi}
  12553. {\if\edition\pythonEd
  12554. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12555. \node (Lvec) at (0,2) {\large \LangVec{}};
  12556. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12557. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12558. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12559. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12560. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12561. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12562. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12563. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12564. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12565. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12566. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12567. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12568. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12569. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12570. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12571. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12572. \end{tikzpicture}
  12573. \fi}
  12574. \end{tcolorbox}
  12575. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12576. \label{fig:Lvec-passes}
  12577. \end{figure}
  12578. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12579. for the compilation of \LangVec{}.
  12580. \clearpage
  12581. {\if\edition\racketEd
  12582. \section{Challenge: Simple Structures}
  12583. \label{sec:simple-structures}
  12584. \index{subject}{struct}
  12585. \index{subject}{structure}
  12586. The language \LangStruct{} extends \LangVec{} with support for simple
  12587. structures. The definition of its concrete syntax is shown in
  12588. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12589. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12590. in Typed Racket is a user-defined data type that contains named fields
  12591. and that is heap allocated, similarly to a vector. The following is an
  12592. example of a structure definition, in this case the definition of a
  12593. \code{point} type:
  12594. \begin{lstlisting}
  12595. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12596. \end{lstlisting}
  12597. \newcommand{\LstructGrammarRacket}{
  12598. \begin{array}{lcl}
  12599. \Type &::=& \Var \\
  12600. \Exp &::=& (\Var\;\Exp \ldots)\\
  12601. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12602. \end{array}
  12603. }
  12604. \newcommand{\LstructASTRacket}{
  12605. \begin{array}{lcl}
  12606. \Type &::=& \VAR{\Var} \\
  12607. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12608. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12609. \end{array}
  12610. }
  12611. \begin{figure}[tbp]
  12612. \centering
  12613. \begin{tcolorbox}[colback=white]
  12614. \[
  12615. \begin{array}{l}
  12616. \gray{\LintGrammarRacket{}} \\ \hline
  12617. \gray{\LvarGrammarRacket{}} \\ \hline
  12618. \gray{\LifGrammarRacket{}} \\ \hline
  12619. \gray{\LwhileGrammarRacket} \\ \hline
  12620. \gray{\LtupGrammarRacket} \\ \hline
  12621. \LstructGrammarRacket \\
  12622. \begin{array}{lcl}
  12623. \LangStruct{} &::=& \Def \ldots \; \Exp
  12624. \end{array}
  12625. \end{array}
  12626. \]
  12627. \end{tcolorbox}
  12628. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12629. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12630. \label{fig:Lstruct-concrete-syntax}
  12631. \end{figure}
  12632. \begin{figure}[tbp]
  12633. \centering
  12634. \begin{tcolorbox}[colback=white]
  12635. \small
  12636. \[
  12637. \begin{array}{l}
  12638. \gray{\LintASTRacket{}} \\ \hline
  12639. \gray{\LvarASTRacket{}} \\ \hline
  12640. \gray{\LifASTRacket{}} \\ \hline
  12641. \gray{\LwhileASTRacket} \\ \hline
  12642. \gray{\LtupASTRacket} \\ \hline
  12643. \LstructASTRacket \\
  12644. \begin{array}{lcl}
  12645. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12646. \end{array}
  12647. \end{array}
  12648. \]
  12649. \end{tcolorbox}
  12650. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12651. (figure~\ref{fig:Lvec-syntax}).}
  12652. \label{fig:Lstruct-syntax}
  12653. \end{figure}
  12654. An instance of a structure is created using function-call syntax, with
  12655. the name of the structure in the function position, as follows:
  12656. \begin{lstlisting}
  12657. (point 7 12)
  12658. \end{lstlisting}
  12659. Function-call syntax is also used to read a field of a structure. The
  12660. function name is formed by the structure name, a dash, and the field
  12661. name. The following example uses \code{point-x} and \code{point-y} to
  12662. access the \code{x} and \code{y} fields of two point instances:
  12663. \begin{center}
  12664. \begin{lstlisting}
  12665. (let ([pt1 (point 7 12)])
  12666. (let ([pt2 (point 4 3)])
  12667. (+ (- (point-x pt1) (point-x pt2))
  12668. (- (point-y pt1) (point-y pt2)))))
  12669. \end{lstlisting}
  12670. \end{center}
  12671. Similarly, to write to a field of a structure, use its set function,
  12672. whose name starts with \code{set-}, followed by the structure name,
  12673. then a dash, then the field name, and finally with an exclamation
  12674. mark. The following example uses \code{set-point-x!} to change the
  12675. \code{x} field from \code{7} to \code{42}:
  12676. \begin{center}
  12677. \begin{lstlisting}
  12678. (let ([pt (point 7 12)])
  12679. (let ([_ (set-point-x! pt 42)])
  12680. (point-x pt)))
  12681. \end{lstlisting}
  12682. \end{center}
  12683. \begin{exercise}\normalfont\normalsize
  12684. Create a type checker for \LangStruct{} by extending the type
  12685. checker for \LangVec{}. Extend your compiler with support for simple
  12686. structures, compiling \LangStruct{} to x86 assembly code. Create
  12687. five new test cases that use structures and, test your compiler.
  12688. \end{exercise}
  12689. % TODO: create an interpreter for L_struct
  12690. \clearpage
  12691. \fi}
  12692. \section{Challenge: Arrays}
  12693. \label{sec:arrays}
  12694. % TODO mention trapped-error
  12695. In this chapter we have studied tuples, that is, heterogeneous
  12696. sequences of elements whose length is determined at compile time. This
  12697. challenge is also about sequences, but this time the length is
  12698. determined at runtime and all the elements have the same type (they
  12699. are homogeneous). We use the term \emph{array} for this latter kind of
  12700. sequence.
  12701. %
  12702. \racket{
  12703. The Racket language does not distinguish between tuples and arrays;
  12704. they are both represented by vectors. However, Typed Racket
  12705. distinguishes between tuples and arrays: the \code{Vector} type is for
  12706. tuples, and the \code{Vectorof} type is for arrays.}
  12707. \python{
  12708. Arrays correspond to the \code{list} type in Python language.
  12709. }
  12710. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12711. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12712. presents the definition of the abstract syntax, extending \LangVec{}
  12713. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12714. %
  12715. \racket{\code{make-vector} primitive operator for creating an array,
  12716. whose arguments are the length of the array and an initial value for
  12717. all the elements in the array.}
  12718. \python{bracket notation for creating an array literal.}
  12719. \racket{
  12720. The \code{vector-length},
  12721. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12722. for tuples become overloaded for use with arrays.}
  12723. \python{
  12724. The subscript operator becomes overloaded for use with arrays and tuples
  12725. and now may appear on the left-hand side of an assignment.
  12726. Note that the index of the subscript, when applied to an array, may be an
  12727. arbitrary expression and not just a constant integer.
  12728. The \code{len} function is also applicable to arrays.
  12729. }
  12730. %
  12731. We include integer multiplication in \LangArray{}, because it is
  12732. useful in many examples involving arrays such as computing the
  12733. inner product of two arrays (figure~\ref{fig:inner_product}).
  12734. \newcommand{\LarrayGrammarRacket}{
  12735. \begin{array}{lcl}
  12736. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12737. \Exp &::=& \CMUL{\Exp}{\Exp}
  12738. \MID \CMAKEVEC{\Exp}{\Exp}
  12739. \end{array}
  12740. }
  12741. \newcommand{\LarrayASTRacket}{
  12742. \begin{array}{lcl}
  12743. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12744. \Exp &::=& \MUL{\Exp}{\Exp}
  12745. \MID \MAKEVEC{\Exp}{\Exp}
  12746. \end{array}
  12747. }
  12748. \newcommand{\LarrayGrammarPython}{
  12749. \begin{array}{lcl}
  12750. \Type &::=& \key{list}\LS\Type\RS \\
  12751. \Exp &::=& \CMUL{\Exp}{\Exp}
  12752. \MID \CGET{\Exp}{\Exp}
  12753. \MID \LS \Exp \code{,} \ldots \RS \\
  12754. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12755. \end{array}
  12756. }
  12757. \newcommand{\LarrayASTPython}{
  12758. \begin{array}{lcl}
  12759. \Type &::=& \key{ListType}\LP\Type\RP \\
  12760. \Exp &::=& \MUL{\Exp}{\Exp}
  12761. \MID \GET{\Exp}{\Exp} \\
  12762. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12763. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12764. \end{array}
  12765. }
  12766. \begin{figure}[tp]
  12767. \centering
  12768. \begin{tcolorbox}[colback=white]
  12769. \small
  12770. {\if\edition\racketEd
  12771. \[
  12772. \begin{array}{l}
  12773. \gray{\LintGrammarRacket{}} \\ \hline
  12774. \gray{\LvarGrammarRacket{}} \\ \hline
  12775. \gray{\LifGrammarRacket{}} \\ \hline
  12776. \gray{\LwhileGrammarRacket} \\ \hline
  12777. \gray{\LtupGrammarRacket} \\ \hline
  12778. \LarrayGrammarRacket \\
  12779. \begin{array}{lcl}
  12780. \LangArray{} &::=& \Exp
  12781. \end{array}
  12782. \end{array}
  12783. \]
  12784. \fi}
  12785. {\if\edition\pythonEd
  12786. \[
  12787. \begin{array}{l}
  12788. \gray{\LintGrammarPython{}} \\ \hline
  12789. \gray{\LvarGrammarPython{}} \\ \hline
  12790. \gray{\LifGrammarPython{}} \\ \hline
  12791. \gray{\LwhileGrammarPython} \\ \hline
  12792. \gray{\LtupGrammarPython} \\ \hline
  12793. \LarrayGrammarPython \\
  12794. \begin{array}{rcl}
  12795. \LangArrayM{} &::=& \Stmt^{*}
  12796. \end{array}
  12797. \end{array}
  12798. \]
  12799. \fi}
  12800. \end{tcolorbox}
  12801. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12802. \label{fig:Lvecof-concrete-syntax}
  12803. \end{figure}
  12804. \begin{figure}[tp]
  12805. \centering
  12806. \begin{tcolorbox}[colback=white]
  12807. \small
  12808. {\if\edition\racketEd
  12809. \[
  12810. \begin{array}{l}
  12811. \gray{\LintASTRacket{}} \\ \hline
  12812. \gray{\LvarASTRacket{}} \\ \hline
  12813. \gray{\LifASTRacket{}} \\ \hline
  12814. \gray{\LwhileASTRacket} \\ \hline
  12815. \gray{\LtupASTRacket} \\ \hline
  12816. \LarrayASTRacket \\
  12817. \begin{array}{lcl}
  12818. \LangArray{} &::=& \Exp
  12819. \end{array}
  12820. \end{array}
  12821. \]
  12822. \fi}
  12823. {\if\edition\pythonEd
  12824. \[
  12825. \begin{array}{l}
  12826. \gray{\LintASTPython{}} \\ \hline
  12827. \gray{\LvarASTPython{}} \\ \hline
  12828. \gray{\LifASTPython{}} \\ \hline
  12829. \gray{\LwhileASTPython} \\ \hline
  12830. \gray{\LtupASTPython} \\ \hline
  12831. \LarrayASTPython \\
  12832. \begin{array}{rcl}
  12833. \LangArrayM{} &::=& \Stmt^{*}
  12834. \end{array}
  12835. \end{array}
  12836. \]
  12837. \fi}
  12838. \end{tcolorbox}
  12839. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12840. \label{fig:Lvecof-syntax}
  12841. \end{figure}
  12842. \begin{figure}[tp]
  12843. \begin{tcolorbox}[colback=white]
  12844. {\if\edition\racketEd
  12845. % TODO: remove the function from the following example, like the python version -Jeremy
  12846. \begin{lstlisting}
  12847. (let ([A (make-vector 2 2)])
  12848. (let ([B (make-vector 2 3)])
  12849. (let ([i 0])
  12850. (let ([prod 0])
  12851. (begin
  12852. (while (< i n)
  12853. (begin
  12854. (set! prod (+ prod (* (vector-ref A i)
  12855. (vector-ref B i))))
  12856. (set! i (+ i 1))))
  12857. prod)))))
  12858. \end{lstlisting}
  12859. \fi}
  12860. {\if\edition\pythonEd
  12861. \begin{lstlisting}
  12862. A = [2, 2]
  12863. B = [3, 3]
  12864. i = 0
  12865. prod = 0
  12866. while i != len(A):
  12867. prod = prod + A[i] * B[i]
  12868. i = i + 1
  12869. print( prod )
  12870. \end{lstlisting}
  12871. \fi}
  12872. \end{tcolorbox}
  12873. \caption{Example program that computes the inner product.}
  12874. \label{fig:inner_product}
  12875. \end{figure}
  12876. {\if\edition\racketEd
  12877. %
  12878. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12879. checker for \LangArray{}. The result type of
  12880. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12881. of the initializing expression. The length expression is required to
  12882. have type \code{Integer}. The type checking of the operators
  12883. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12884. updated to handle the situation in which the vector has type
  12885. \code{Vectorof}. In these cases we translate the operators to their
  12886. \code{vectorof} form so that later passes can easily distinguish
  12887. between operations on tuples versus arrays. We override the
  12888. \code{operator-types} method to provide the type signature for
  12889. multiplication: it takes two integers and returns an integer. \fi}
  12890. {\if\edition\pythonEd
  12891. %
  12892. The type checker for \LangArray{} is defined in
  12893. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12894. is \code{list[T]} where \code{T} is the type of the initializing
  12895. expressions. The type checking of the \code{len} function and the
  12896. subscript operator is updated to handle lists. The type checker now
  12897. also handles a subscript on the left-hand side of an assignment.
  12898. Regarding multiplication, it takes two integers and returns an
  12899. integer.
  12900. %
  12901. \fi}
  12902. \begin{figure}[tbp]
  12903. \begin{tcolorbox}[colback=white]
  12904. {\if\edition\racketEd
  12905. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12906. (define type-check-Lvecof-class
  12907. (class type-check-Lvec-class
  12908. (super-new)
  12909. (inherit check-type-equal?)
  12910. (define/override (operator-types)
  12911. (append '((* . ((Integer Integer) . Integer)))
  12912. (super operator-types)))
  12913. (define/override (type-check-exp env)
  12914. (lambda (e)
  12915. (define recur (type-check-exp env))
  12916. (match e
  12917. [(Prim 'make-vector (list e1 e2))
  12918. (define-values (e1^ t1) (recur e1))
  12919. (define-values (e2^ elt-type) (recur e2))
  12920. (define vec-type `(Vectorof ,elt-type))
  12921. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12922. [(Prim 'vector-ref (list e1 e2))
  12923. (define-values (e1^ t1) (recur e1))
  12924. (define-values (e2^ t2) (recur e2))
  12925. (match* (t1 t2)
  12926. [(`(Vectorof ,elt-type) 'Integer)
  12927. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12928. [(other wise) ((super type-check-exp env) e)])]
  12929. [(Prim 'vector-set! (list e1 e2 e3) )
  12930. (define-values (e-vec t-vec) (recur e1))
  12931. (define-values (e2^ t2) (recur e2))
  12932. (define-values (e-arg^ t-arg) (recur e3))
  12933. (match t-vec
  12934. [`(Vectorof ,elt-type)
  12935. (check-type-equal? elt-type t-arg e)
  12936. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12937. [else ((super type-check-exp env) e)])]
  12938. [(Prim 'vector-length (list e1))
  12939. (define-values (e1^ t1) (recur e1))
  12940. (match t1
  12941. [`(Vectorof ,t)
  12942. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12943. [else ((super type-check-exp env) e)])]
  12944. [else ((super type-check-exp env) e)])))
  12945. ))
  12946. (define (type-check-Lvecof p)
  12947. (send (new type-check-Lvecof-class) type-check-program p))
  12948. \end{lstlisting}
  12949. \fi}
  12950. {\if\edition\pythonEd
  12951. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12952. class TypeCheckLarray(TypeCheckLtup):
  12953. def type_check_exp(self, e, env):
  12954. match e:
  12955. case ast.List(es, Load()):
  12956. ts = [self.type_check_exp(e, env) for e in es]
  12957. elt_ty = ts[0]
  12958. for (ty, elt) in zip(ts, es):
  12959. self.check_type_equal(elt_ty, ty, elt)
  12960. e.has_type = ListType(elt_ty)
  12961. return e.has_type
  12962. case Call(Name('len'), [tup]):
  12963. tup_t = self.type_check_exp(tup, env)
  12964. tup.has_type = tup_t
  12965. match tup_t:
  12966. case TupleType(ts):
  12967. return IntType()
  12968. case ListType(ty):
  12969. return IntType()
  12970. case _:
  12971. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12972. case Subscript(tup, index, Load()):
  12973. tup_ty = self.type_check_exp(tup, env)
  12974. index_ty = self.type_check_exp(index, env)
  12975. self.check_type_equal(index_ty, IntType(), index)
  12976. match tup_ty:
  12977. case TupleType(ts):
  12978. match index:
  12979. case Constant(i):
  12980. return ts[i]
  12981. case _:
  12982. raise Exception('subscript required constant integer index')
  12983. case ListType(ty):
  12984. return ty
  12985. case _:
  12986. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12987. case BinOp(left, Mult(), right):
  12988. l = self.type_check_exp(left, env)
  12989. self.check_type_equal(l, IntType(), left)
  12990. r = self.type_check_exp(right, env)
  12991. self.check_type_equal(r, IntType(), right)
  12992. return IntType()
  12993. case _:
  12994. return super().type_check_exp(e, env)
  12995. def type_check_stmts(self, ss, env):
  12996. if len(ss) == 0:
  12997. return VoidType()
  12998. match ss[0]:
  12999. case Assign([Subscript(tup, index, Store())], value):
  13000. tup_t = self.type_check_exp(tup, env)
  13001. value_t = self.type_check_exp(value, env)
  13002. index_ty = self.type_check_exp(index, env)
  13003. self.check_type_equal(index_ty, IntType(), index)
  13004. match tup_t:
  13005. case ListType(ty):
  13006. self.check_type_equal(ty, value_t, ss[0])
  13007. case TupleType(ts):
  13008. return self.type_check_stmts(ss, env)
  13009. case _:
  13010. raise Exception('type_check_stmts: '
  13011. 'expected tuple or list, not ' + repr(tup_t))
  13012. return self.type_check_stmts(ss[1:], env)
  13013. case _:
  13014. return super().type_check_stmts(ss, env)
  13015. \end{lstlisting}
  13016. \fi}
  13017. \end{tcolorbox}
  13018. \caption{Type checker for the \LangArray{} language.}
  13019. \label{fig:type-check-Lvecof}
  13020. \end{figure}
  13021. The definition of the interpreter for \LangArray{} is shown in
  13022. figure~\ref{fig:interp-Lvecof}.
  13023. \racket{The \code{make-vector} operator is
  13024. interpreted using Racket's \code{make-vector} function,
  13025. and multiplication is interpreted using \code{fx*},
  13026. which is multiplication for \code{fixnum} integers.
  13027. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  13028. we translate array access operations
  13029. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13030. which we interpret using \code{vector} operations with additional
  13031. bounds checks that signal a \code{trapped-error}.
  13032. }
  13033. %
  13034. \python{We implement list creation with a Python list comprehension
  13035. and multiplication is implemented with Python multiplication. We
  13036. add a case to handle a subscript on the left-hand side of
  13037. assignment. Other uses of subscript can be handled by the existing
  13038. code for tuples.}
  13039. \begin{figure}[tbp]
  13040. \begin{tcolorbox}[colback=white]
  13041. {\if\edition\racketEd
  13042. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13043. (define interp-Lvecof-class
  13044. (class interp-Lvec-class
  13045. (super-new)
  13046. (define/override (interp-op op)
  13047. (match op
  13048. ['make-vector make-vector]
  13049. ['vectorof-length vector-length]
  13050. ['vectorof-ref
  13051. (lambda (v i)
  13052. (if (< i (vector-length v))
  13053. (vector-ref v i)
  13054. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13055. ['vectorof-set!
  13056. (lambda (v i e)
  13057. (if (< i (vector-length v))
  13058. (vector-set! v i e)
  13059. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13060. [else (super interp-op op)]))
  13061. ))
  13062. (define (interp-Lvecof p)
  13063. (send (new interp-Lvecof-class) interp-program p))
  13064. \end{lstlisting}
  13065. \fi}
  13066. {\if\edition\pythonEd
  13067. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13068. class InterpLarray(InterpLtup):
  13069. def interp_exp(self, e, env):
  13070. match e:
  13071. case ast.List(es, Load()):
  13072. return [self.interp_exp(e, env) for e in es]
  13073. case BinOp(left, Mult(), right):
  13074. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  13075. return l * r
  13076. case _:
  13077. return super().interp_exp(e, env)
  13078. def interp_stmts(self, ss, env):
  13079. if len(ss) == 0:
  13080. return
  13081. match ss[0]:
  13082. case Assign([Subscript(lst, index)], value):
  13083. lst = self.interp_exp(lst, env)
  13084. index = self.interp_exp(index, env)
  13085. lst[index] = self.interp_exp(value, env)
  13086. return self.interp_stmts(ss[1:], env)
  13087. case _:
  13088. return super().interp_stmts(ss, env)
  13089. \end{lstlisting}
  13090. \fi}
  13091. \end{tcolorbox}
  13092. \caption{Interpreter for \LangArray{}.}
  13093. \label{fig:interp-Lvecof}
  13094. \end{figure}
  13095. \subsection{Data Representation}
  13096. \label{sec:array-rep}
  13097. Just as with tuples, we store arrays on the heap, which means that the
  13098. garbage collector will need to inspect arrays. An immediate thought is
  13099. to use the same representation for arrays that we use for tuples.
  13100. However, we limit tuples to a length of fifty so that their length and
  13101. pointer mask can fit into the 64-bit tag at the beginning of each
  13102. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13103. millions of elements, so we need more bits to store the length.
  13104. However, because arrays are homogeneous, we need only 1 bit for the
  13105. pointer mask instead of 1 bit per array element. Finally, the
  13106. garbage collector must be able to distinguish between tuples
  13107. and arrays, so we need to reserve one bit for that purpose. We
  13108. arrive at the following layout for the 64-bit tag at the beginning of
  13109. an array:
  13110. \begin{itemize}
  13111. \item The right-most bit is the forwarding bit, just as in a tuple.
  13112. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13113. that it is not.
  13114. \item The next bit to the left is the pointer mask. A $0$ indicates
  13115. that none of the elements are pointers to the heap, and a $1$
  13116. indicates that all the elements are pointers.
  13117. \item The next $60$ bits store the length of the array.
  13118. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13119. and an array ($1$).
  13120. \item The left-most bit is reserved as explained in
  13121. chapter~\ref{ch:Lgrad}.
  13122. \end{itemize}
  13123. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13124. %% differentiate the kinds of values that have been injected into the
  13125. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13126. %% to indicate that the value is an array.
  13127. In the following subsections we provide hints regarding how to update
  13128. the passes to handle arrays.
  13129. \subsection{Overload Resolution}
  13130. \label{sec:array-resolution}
  13131. As noted previously, with the addition of arrays, several operators
  13132. have become \emph{overloaded}; that is, they can be applied to values
  13133. of more than one type. In this case, the element access and length
  13134. operators can be applied to both tuples and arrays. This kind of
  13135. overloading is quite common in programming languages, so many
  13136. compilers perform \emph{overload resolution}\index{subject}{overload
  13137. resolution} to handle it. The idea is to translate each overloaded
  13138. operator into different operators for the different types.
  13139. Implement a new pass named \code{resolve}.
  13140. Translate the reading of an array element
  13141. into a call to
  13142. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13143. and the writing of an array element to
  13144. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13145. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13146. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13147. When these operators are applied to tuples, leave them as is.
  13148. %
  13149. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13150. field which can be inspected to determine whether the operator
  13151. is applied to a tuple or an array.}
  13152. \subsection{Bounds Checking}
  13153. Recall that the interpreter for \LangArray{} signals a
  13154. \code{trapped-error} when there is an array access that is out of
  13155. bounds. Therefore your compiler is obliged to also catch these errors
  13156. during execution and halt, signaling an error. We recommend inserting
  13157. a new pass named \code{check\_bounds} that inserts code around each
  13158. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13159. \python{subscript} operation to ensure that the index is greater than
  13160. or equal to zero and less than the array's length. If not, the program
  13161. should halt, for which we recommend using a new primitive operation
  13162. named \code{exit}.
  13163. %% \subsection{Reveal Casts}
  13164. %% The array-access operators \code{vectorof-ref} and
  13165. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13166. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13167. %% that the type checker cannot tell whether the index will be in bounds,
  13168. %% so the bounds check must be performed at run time. Recall that the
  13169. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13170. %% an \code{If} around a vector reference for update to check whether
  13171. %% the index is less than the length. You should do the same for
  13172. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13173. %% In addition, the handling of the \code{any-vector} operators in
  13174. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13175. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13176. %% generated code should test whether the tag is for tuples (\code{010})
  13177. %% or arrays (\code{110}) and then dispatch to either
  13178. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13179. %% we add a case in \code{select\_instructions} to generate the
  13180. %% appropriate instructions for accessing the array length from the
  13181. %% header of an array.
  13182. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13183. %% the generated code needs to check that the index is less than the
  13184. %% vector length, so like the code for \code{any-vector-length}, check
  13185. %% the tag to determine whether to use \code{any-vector-length} or
  13186. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13187. %% is complete, the generated code can use \code{any-vector-ref} and
  13188. %% \code{any-vector-set!} for both tuples and arrays because the
  13189. %% instructions used for those operators do not look at the tag at the
  13190. %% front of the tuple or array.
  13191. \subsection{Expose Allocation}
  13192. This pass should translate array creation into lower-level
  13193. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13194. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13195. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13196. array. The \code{AllocateArray} AST node allocates an array of the
  13197. length specified by the $\Exp$ (of type \INTTY), but does not
  13198. initialize the elements of the array. Generate code in this pass to
  13199. initialize the elements analogous to the case for tuples.
  13200. {\if\edition\racketEd
  13201. \section{Uncover \texttt{get!}}
  13202. \label{sec:uncover-get-bang-vecof}
  13203. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13204. \code{uncover-get!-exp}.
  13205. \fi}
  13206. \subsection{Remove Complex Operands}
  13207. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13208. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13209. complex, and its subexpression must be atomic.
  13210. \subsection{Explicate Control}
  13211. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13212. \code{explicate\_assign}.
  13213. \subsection{Select Instructions}
  13214. Generate instructions for \code{AllocateArray} similar to those for
  13215. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13216. except that the tag at the front of the array should instead use the
  13217. representation discussed in section~\ref{sec:array-rep}.
  13218. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13219. extract the length from the tag.
  13220. The instructions generated for accessing an element of an array differ
  13221. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13222. that the index is not a constant so you need to generate instructions
  13223. that compute the offset at runtime.
  13224. Compile the \code{exit} primitive into a call to the \code{exit}
  13225. function of the C standard library, with an argument of $255$.
  13226. %% Also, note that assignment to an array element may appear in
  13227. %% as a stand-alone statement, so make sure to handle that situation in
  13228. %% this pass.
  13229. %% Finally, the instructions for \code{any-vectorof-length} should be
  13230. %% similar to those for \code{vectorof-length}, except that one must
  13231. %% first project the array by writing zeroes into the $3$-bit tag
  13232. \begin{exercise}\normalfont\normalsize
  13233. Implement a compiler for the \LangArray{} language by extending your
  13234. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13235. programs, including the one shown in figure~\ref{fig:inner_product}
  13236. and also a program that multiplies two matrices. Note that although
  13237. matrices are two-dimensional arrays, they can be encoded into
  13238. one-dimensional arrays by laying out each row in the array, one after
  13239. the next.
  13240. \end{exercise}
  13241. {\if\edition\racketEd
  13242. \section{Challenge: Generational Collection}
  13243. The copying collector described in section~\ref{sec:GC} can incur
  13244. significant runtime overhead because the call to \code{collect} takes
  13245. time proportional to all the live data. One way to reduce this
  13246. overhead is to reduce how much data is inspected in each call to
  13247. \code{collect}. In particular, researchers have observed that recently
  13248. allocated data is more likely to become garbage then data that has
  13249. survived one or more previous calls to \code{collect}. This insight
  13250. motivated the creation of \emph{generational garbage collectors}
  13251. \index{subject}{generational garbage collector} that
  13252. (1) segregate data according to its age into two or more generations;
  13253. (2) allocate less space for younger generations, so collecting them is
  13254. faster, and more space for the older generations; and (3) perform
  13255. collection on the younger generations more frequently than on older
  13256. generations~\citep{Wilson:1992fk}.
  13257. For this challenge assignment, the goal is to adapt the copying
  13258. collector implemented in \code{runtime.c} to use two generations, one
  13259. for young data and one for old data. Each generation consists of a
  13260. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13261. \code{collect} function to use the two generations:
  13262. \begin{enumerate}
  13263. \item Copy the young generation's FromSpace to its ToSpace and then
  13264. switch the role of the ToSpace and FromSpace
  13265. \item If there is enough space for the requested number of bytes in
  13266. the young FromSpace, then return from \code{collect}.
  13267. \item If there is not enough space in the young FromSpace for the
  13268. requested bytes, then move the data from the young generation to the
  13269. old one with the following steps:
  13270. \begin{enumerate}
  13271. \item[a.] If there is enough room in the old FromSpace, copy the young
  13272. FromSpace to the old FromSpace and then return.
  13273. \item[b.] If there is not enough room in the old FromSpace, then collect
  13274. the old generation by copying the old FromSpace to the old ToSpace
  13275. and swap the roles of the old FromSpace and ToSpace.
  13276. \item[c.] If there is enough room now, copy the young FromSpace to the
  13277. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13278. and ToSpace for the old generation. Copy the young FromSpace and
  13279. the old FromSpace into the larger FromSpace for the old
  13280. generation and then return.
  13281. \end{enumerate}
  13282. \end{enumerate}
  13283. We recommend that you generalize the \code{cheney} function so that it
  13284. can be used for all the copies mentioned: between the young FromSpace
  13285. and ToSpace, between the old FromSpace and ToSpace, and between the
  13286. young FromSpace and old FromSpace. This can be accomplished by adding
  13287. parameters to \code{cheney} that replace its use of the global
  13288. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13289. \code{tospace\_begin}, and \code{tospace\_end}.
  13290. Note that the collection of the young generation does not traverse the
  13291. old generation. This introduces a potential problem: there may be
  13292. young data that is reachable only through pointers in the old
  13293. generation. If these pointers are not taken into account, the
  13294. collector could throw away young data that is live! One solution,
  13295. called \emph{pointer recording}, is to maintain a set of all the
  13296. pointers from the old generation into the new generation and consider
  13297. this set as part of the root set. To maintain this set, the compiler
  13298. must insert extra instructions around every \code{vector-set!}. If the
  13299. vector being modified is in the old generation, and if the value being
  13300. written is a pointer into the new generation, then that pointer must
  13301. be added to the set. Also, if the value being overwritten was a
  13302. pointer into the new generation, then that pointer should be removed
  13303. from the set.
  13304. \begin{exercise}\normalfont\normalsize
  13305. Adapt the \code{collect} function in \code{runtime.c} to implement
  13306. generational garbage collection, as outlined in this section.
  13307. Update the code generation for \code{vector-set!} to implement
  13308. pointer recording. Make sure that your new compiler and runtime
  13309. execute without error on your test suite.
  13310. \end{exercise}
  13311. \fi}
  13312. \section{Further Reading}
  13313. \citet{Appel90} describes many data representation approaches,
  13314. including the ones used in the compilation of Standard ML.
  13315. There are many alternatives to copying collectors (and their bigger
  13316. siblings, the generational collectors) with regard to garbage
  13317. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13318. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13319. collectors are that allocation is fast (just a comparison and pointer
  13320. increment), there is no fragmentation, cyclic garbage is collected,
  13321. and the time complexity of collection depends only on the amount of
  13322. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13323. main disadvantages of a two-space copying collector is that it uses a
  13324. lot of extra space and takes a long time to perform the copy, though
  13325. these problems are ameliorated in generational collectors.
  13326. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13327. small objects and generate a lot of garbage, so copying and
  13328. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13329. Garbage collection is an active research topic, especially concurrent
  13330. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13331. developing new techniques and revisiting old
  13332. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13333. meet every year at the International Symposium on Memory Management to
  13334. present these findings.
  13335. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13336. \chapter{Functions}
  13337. \label{ch:Lfun}
  13338. \index{subject}{function}
  13339. \setcounter{footnote}{0}
  13340. This chapter studies the compilation of a subset of \racket{Typed
  13341. Racket}\python{Python} in which only top-level function definitions
  13342. are allowed. This kind of function appears in the C programming
  13343. language, and it serves as an important stepping-stone to implementing
  13344. lexically scoped functions in the form of \key{lambda} abstractions,
  13345. which is the topic of chapter~\ref{ch:Llambda}.
  13346. \section{The \LangFun{} Language}
  13347. The concrete syntax and abstract syntax for function definitions and
  13348. function application are shown in
  13349. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13350. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13351. with zero or more function definitions. The function names from these
  13352. definitions are in scope for the entire program, including all the
  13353. function definitions, and therefore the ordering of function
  13354. definitions does not matter.
  13355. %
  13356. \python{The abstract syntax for function parameters in
  13357. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  13358. consists of a parameter name and its type. This design differs from
  13359. Python's \code{ast} module, which has a more complex structure for
  13360. function parameters to handle keyword parameters,
  13361. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13362. complex Python abstract syntax into the simpler syntax of
  13363. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13364. \code{FunctionDef} constructor are for decorators and a type
  13365. comment, neither of which are used by our compiler. We recommend
  13366. replacing them with \code{None} in the \code{shrink} pass.
  13367. }
  13368. %
  13369. The concrete syntax for function application
  13370. \index{subject}{function application}
  13371. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13372. where the first expression
  13373. must evaluate to a function and the remaining expressions are the arguments. The
  13374. abstract syntax for function application is
  13375. $\APPLY{\Exp}{\Exp^*}$.
  13376. %% The syntax for function application does not include an explicit
  13377. %% keyword, which is error prone when using \code{match}. To alleviate
  13378. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13379. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13380. Functions are first-class in the sense that a function pointer
  13381. \index{subject}{function pointer} is data and can be stored in memory or passed
  13382. as a parameter to another function. Thus, there is a function
  13383. type, written
  13384. {\if\edition\racketEd
  13385. \begin{lstlisting}
  13386. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13387. \end{lstlisting}
  13388. \fi}
  13389. {\if\edition\pythonEd
  13390. \begin{lstlisting}
  13391. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13392. \end{lstlisting}
  13393. \fi}
  13394. %
  13395. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13396. through $\Type_n$ and whose return type is $\Type_R$. The main
  13397. limitation of these functions (with respect to
  13398. \racket{Racket}\python{Python} functions) is that they are not
  13399. lexically scoped. That is, the only external entities that can be
  13400. referenced from inside a function body are other globally defined
  13401. functions. The syntax of \LangFun{} prevents function definitions from
  13402. being nested inside each other.
  13403. \newcommand{\LfunGrammarRacket}{
  13404. \begin{array}{lcl}
  13405. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13406. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13407. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13408. \end{array}
  13409. }
  13410. \newcommand{\LfunASTRacket}{
  13411. \begin{array}{lcl}
  13412. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13413. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13414. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13415. \end{array}
  13416. }
  13417. \newcommand{\LfunGrammarPython}{
  13418. \begin{array}{lcl}
  13419. \Type &::=& \key{int}
  13420. \MID \key{bool} \MID \key{void}
  13421. \MID \key{tuple}\LS \Type^+ \RS
  13422. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13423. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13424. \Stmt &::=& \CRETURN{\Exp} \\
  13425. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13426. \end{array}
  13427. }
  13428. \newcommand{\LfunASTPython}{
  13429. \begin{array}{lcl}
  13430. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13431. \MID \key{TupleType}\LS\Type^+\RS\\
  13432. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13433. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13434. \Stmt &::=& \RETURN{\Exp} \\
  13435. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13436. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13437. \end{array}
  13438. }
  13439. \begin{figure}[tp]
  13440. \centering
  13441. \begin{tcolorbox}[colback=white]
  13442. \small
  13443. {\if\edition\racketEd
  13444. \[
  13445. \begin{array}{l}
  13446. \gray{\LintGrammarRacket{}} \\ \hline
  13447. \gray{\LvarGrammarRacket{}} \\ \hline
  13448. \gray{\LifGrammarRacket{}} \\ \hline
  13449. \gray{\LwhileGrammarRacket} \\ \hline
  13450. \gray{\LtupGrammarRacket} \\ \hline
  13451. \LfunGrammarRacket \\
  13452. \begin{array}{lcl}
  13453. \LangFunM{} &::=& \Def \ldots \; \Exp
  13454. \end{array}
  13455. \end{array}
  13456. \]
  13457. \fi}
  13458. {\if\edition\pythonEd
  13459. \[
  13460. \begin{array}{l}
  13461. \gray{\LintGrammarPython{}} \\ \hline
  13462. \gray{\LvarGrammarPython{}} \\ \hline
  13463. \gray{\LifGrammarPython{}} \\ \hline
  13464. \gray{\LwhileGrammarPython} \\ \hline
  13465. \gray{\LtupGrammarPython} \\ \hline
  13466. \LfunGrammarPython \\
  13467. \begin{array}{rcl}
  13468. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13469. \end{array}
  13470. \end{array}
  13471. \]
  13472. \fi}
  13473. \end{tcolorbox}
  13474. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13475. \label{fig:Lfun-concrete-syntax}
  13476. \end{figure}
  13477. \begin{figure}[tp]
  13478. \centering
  13479. \begin{tcolorbox}[colback=white]
  13480. \small
  13481. {\if\edition\racketEd
  13482. \[
  13483. \begin{array}{l}
  13484. \gray{\LintOpAST} \\ \hline
  13485. \gray{\LvarASTRacket{}} \\ \hline
  13486. \gray{\LifASTRacket{}} \\ \hline
  13487. \gray{\LwhileASTRacket{}} \\ \hline
  13488. \gray{\LtupASTRacket{}} \\ \hline
  13489. \LfunASTRacket \\
  13490. \begin{array}{lcl}
  13491. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13492. \end{array}
  13493. \end{array}
  13494. \]
  13495. \fi}
  13496. {\if\edition\pythonEd
  13497. \[
  13498. \begin{array}{l}
  13499. \gray{\LintASTPython{}} \\ \hline
  13500. \gray{\LvarASTPython{}} \\ \hline
  13501. \gray{\LifASTPython{}} \\ \hline
  13502. \gray{\LwhileASTPython} \\ \hline
  13503. \gray{\LtupASTPython} \\ \hline
  13504. \LfunASTPython \\
  13505. \begin{array}{rcl}
  13506. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13507. \end{array}
  13508. \end{array}
  13509. \]
  13510. \fi}
  13511. \end{tcolorbox}
  13512. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13513. \label{fig:Lfun-syntax}
  13514. \end{figure}
  13515. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13516. representative example of defining and using functions in \LangFun{}.
  13517. We define a function \code{map} that applies some other function
  13518. \code{f} to both elements of a tuple and returns a new tuple
  13519. containing the results. We also define a function \code{inc}. The
  13520. program applies \code{map} to \code{inc} and
  13521. %
  13522. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13523. %
  13524. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13525. %
  13526. from which we return \code{42}.
  13527. \begin{figure}[tbp]
  13528. \begin{tcolorbox}[colback=white]
  13529. {\if\edition\racketEd
  13530. \begin{lstlisting}
  13531. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13532. : (Vector Integer Integer)
  13533. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13534. (define (inc [x : Integer]) : Integer
  13535. (+ x 1))
  13536. (vector-ref (map inc (vector 0 41)) 1)
  13537. \end{lstlisting}
  13538. \fi}
  13539. {\if\edition\pythonEd
  13540. \begin{lstlisting}
  13541. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13542. return f(v[0]), f(v[1])
  13543. def inc(x : int) -> int:
  13544. return x + 1
  13545. print( map(inc, (0, 41))[1] )
  13546. \end{lstlisting}
  13547. \fi}
  13548. \end{tcolorbox}
  13549. \caption{Example of using functions in \LangFun{}.}
  13550. \label{fig:Lfun-function-example}
  13551. \end{figure}
  13552. The definitional interpreter for \LangFun{} is shown in
  13553. figure~\ref{fig:interp-Lfun}. The case for the
  13554. %
  13555. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13556. %
  13557. AST is responsible for setting up the mutual recursion between the
  13558. top-level function definitions.
  13559. %
  13560. \racket{We use the classic back-patching
  13561. \index{subject}{back-patching} approach that uses mutable variables
  13562. and makes two passes over the function
  13563. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13564. top-level environment using a mutable cons cell for each function
  13565. definition. Note that the \code{lambda} value for each function is
  13566. incomplete; it does not yet include the environment. Once the
  13567. top-level environment has been constructed, we iterate over it and
  13568. update the \code{lambda} values to use the top-level environment.}
  13569. %
  13570. \python{We create a dictionary named \code{env} and fill it in
  13571. by mapping each function name to a new \code{Function} value,
  13572. each of which stores a reference to the \code{env}.
  13573. (We define the class \code{Function} for this purpose.)}
  13574. %
  13575. To interpret a function \racket{application}\python{call}, we match
  13576. the result of the function expression to obtain a function value. We
  13577. then extend the function's environment with the mapping of parameters to
  13578. argument values. Finally, we interpret the body of the function in
  13579. this extended environment.
  13580. \begin{figure}[tp]
  13581. \begin{tcolorbox}[colback=white]
  13582. {\if\edition\racketEd
  13583. \begin{lstlisting}
  13584. (define interp-Lfun-class
  13585. (class interp-Lvec-class
  13586. (super-new)
  13587. (define/override ((interp-exp env) e)
  13588. (define recur (interp-exp env))
  13589. (match e
  13590. [(Apply fun args)
  13591. (define fun-val (recur fun))
  13592. (define arg-vals (for/list ([e args]) (recur e)))
  13593. (match fun-val
  13594. [`(function (,xs ...) ,body ,fun-env)
  13595. (define params-args (for/list ([x xs] [arg arg-vals])
  13596. (cons x (box arg))))
  13597. (define new-env (append params-args fun-env))
  13598. ((interp-exp new-env) body)]
  13599. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  13600. [else ((super interp-exp env) e)]
  13601. ))
  13602. (define/public (interp-def d)
  13603. (match d
  13604. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13605. (cons f (box `(function ,xs ,body ())))]))
  13606. (define/override (interp-program p)
  13607. (match p
  13608. [(ProgramDefsExp info ds body)
  13609. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13610. (for/list ([f (in-dict-values top-level)])
  13611. (set-box! f (match (unbox f)
  13612. [`(function ,xs ,body ())
  13613. `(function ,xs ,body ,top-level)])))
  13614. ((interp-exp top-level) body))]))
  13615. ))
  13616. (define (interp-Lfun p)
  13617. (send (new interp-Lfun-class) interp-program p))
  13618. \end{lstlisting}
  13619. \fi}
  13620. {\if\edition\pythonEd
  13621. \begin{lstlisting}
  13622. class InterpLfun(InterpLtup):
  13623. def apply_fun(self, fun, args, e):
  13624. match fun:
  13625. case Function(name, xs, body, env):
  13626. new_env = env.copy().update(zip(xs, args))
  13627. return self.interp_stmts(body, new_env)
  13628. case _:
  13629. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13630. def interp_exp(self, e, env):
  13631. match e:
  13632. case Call(Name('input_int'), []):
  13633. return super().interp_exp(e, env)
  13634. case Call(func, args):
  13635. f = self.interp_exp(func, env)
  13636. vs = [self.interp_exp(arg, env) for arg in args]
  13637. return self.apply_fun(f, vs, e)
  13638. case _:
  13639. return super().interp_exp(e, env)
  13640. def interp_stmts(self, ss, env):
  13641. if len(ss) == 0:
  13642. return
  13643. match ss[0]:
  13644. case Return(value):
  13645. return self.interp_exp(value, env)
  13646. case FunctionDef(name, params, bod, dl, returns, comment):
  13647. ps = [x for (x,t) in params]
  13648. env[name] = Function(name, ps, bod, env)
  13649. return self.interp_stmts(ss[1:], env)
  13650. case _:
  13651. return super().interp_stmts(ss, env)
  13652. def interp(self, p):
  13653. match p:
  13654. case Module(ss):
  13655. env = {}
  13656. self.interp_stmts(ss, env)
  13657. if 'main' in env.keys():
  13658. self.apply_fun(env['main'], [], None)
  13659. case _:
  13660. raise Exception('interp: unexpected ' + repr(p))
  13661. \end{lstlisting}
  13662. \fi}
  13663. \end{tcolorbox}
  13664. \caption{Interpreter for the \LangFun{} language.}
  13665. \label{fig:interp-Lfun}
  13666. \end{figure}
  13667. %\margincomment{TODO: explain type checker}
  13668. The type checker for \LangFun{} is shown in
  13669. figure~\ref{fig:type-check-Lfun}.
  13670. %
  13671. \python{(We omit the code that parses function parameters into the
  13672. simpler abstract syntax.)}
  13673. %
  13674. Similarly to the interpreter, the case for the
  13675. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13676. %
  13677. AST is responsible for setting up the mutual recursion between the
  13678. top-level function definitions. We begin by create a mapping
  13679. \code{env} from every function name to its type. We then type check
  13680. the program using this mapping.
  13681. %
  13682. In the case for function \racket{application}\python{call}, we match
  13683. the type of the function expression to a function type and check that
  13684. the types of the argument expressions are equal to the function's
  13685. parameter types. The type of the \racket{application}\python{call} as
  13686. a whole is the return type from the function type.
  13687. \begin{figure}[tp]
  13688. \begin{tcolorbox}[colback=white]
  13689. {\if\edition\racketEd
  13690. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13691. (define type-check-Lfun-class
  13692. (class type-check-Lvec-class
  13693. (super-new)
  13694. (inherit check-type-equal?)
  13695. (define/public (type-check-apply env e es)
  13696. (define-values (e^ ty) ((type-check-exp env) e))
  13697. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13698. ((type-check-exp env) e)))
  13699. (match ty
  13700. [`(,ty^* ... -> ,rt)
  13701. (for ([arg-ty ty*] [param-ty ty^*])
  13702. (check-type-equal? arg-ty param-ty (Apply e es)))
  13703. (values e^ e* rt)]))
  13704. (define/override (type-check-exp env)
  13705. (lambda (e)
  13706. (match e
  13707. [(FunRef f n)
  13708. (values (FunRef f n) (dict-ref env f))]
  13709. [(Apply e es)
  13710. (define-values (e^ es^ rt) (type-check-apply env e es))
  13711. (values (Apply e^ es^) rt)]
  13712. [(Call e es)
  13713. (define-values (e^ es^ rt) (type-check-apply env e es))
  13714. (values (Call e^ es^) rt)]
  13715. [else ((super type-check-exp env) e)])))
  13716. (define/public (type-check-def env)
  13717. (lambda (e)
  13718. (match e
  13719. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13720. (define new-env (append (map cons xs ps) env))
  13721. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13722. (check-type-equal? ty^ rt body)
  13723. (Def f p:t* rt info body^)])))
  13724. (define/public (fun-def-type d)
  13725. (match d
  13726. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13727. (define/override (type-check-program e)
  13728. (match e
  13729. [(ProgramDefsExp info ds body)
  13730. (define env (for/list ([d ds])
  13731. (cons (Def-name d) (fun-def-type d))))
  13732. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13733. (define-values (body^ ty) ((type-check-exp env) body))
  13734. (check-type-equal? ty 'Integer body)
  13735. (ProgramDefsExp info ds^ body^)]))))
  13736. (define (type-check-Lfun p)
  13737. (send (new type-check-Lfun-class) type-check-program p))
  13738. \end{lstlisting}
  13739. \fi}
  13740. {\if\edition\pythonEd
  13741. \begin{lstlisting}
  13742. class TypeCheckLfun(TypeCheckLtup):
  13743. def type_check_exp(self, e, env):
  13744. match e:
  13745. case Call(Name('input_int'), []):
  13746. return super().type_check_exp(e, env)
  13747. case Call(func, args):
  13748. func_t = self.type_check_exp(func, env)
  13749. args_t = [self.type_check_exp(arg, env) for arg in args]
  13750. match func_t:
  13751. case FunctionType(params_t, return_t):
  13752. for (arg_t, param_t) in zip(args_t, params_t):
  13753. check_type_equal(param_t, arg_t, e)
  13754. return return_t
  13755. case _:
  13756. raise Exception('type_check_exp: in call, unexpected ' +
  13757. repr(func_t))
  13758. case _:
  13759. return super().type_check_exp(e, env)
  13760. def type_check_stmts(self, ss, env):
  13761. if len(ss) == 0:
  13762. return
  13763. match ss[0]:
  13764. case FunctionDef(name, params, body, dl, returns, comment):
  13765. new_env = env.copy().update(params)
  13766. rt = self.type_check_stmts(body, new_env)
  13767. check_type_equal(returns, rt, ss[0])
  13768. return self.type_check_stmts(ss[1:], env)
  13769. case Return(value):
  13770. return self.type_check_exp(value, env)
  13771. case _:
  13772. return super().type_check_stmts(ss, env)
  13773. def type_check(self, p):
  13774. match p:
  13775. case Module(body):
  13776. env = {}
  13777. for s in body:
  13778. match s:
  13779. case FunctionDef(name, params, bod, dl, returns, comment):
  13780. if name in env:
  13781. raise Exception('type_check: function ' +
  13782. repr(name) + ' defined twice')
  13783. params_t = [t for (x,t) in params]
  13784. env[name] = FunctionType(params_t, returns)
  13785. self.type_check_stmts(body, env)
  13786. case _:
  13787. raise Exception('type_check: unexpected ' + repr(p))
  13788. \end{lstlisting}
  13789. \fi}
  13790. \end{tcolorbox}
  13791. \caption{Type checker for the \LangFun{} language.}
  13792. \label{fig:type-check-Lfun}
  13793. \end{figure}
  13794. \clearpage
  13795. \section{Functions in x86}
  13796. \label{sec:fun-x86}
  13797. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13798. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13799. %% \margincomment{\tiny Talk about the return address on the
  13800. %% stack and what callq and retq does.\\ --Jeremy }
  13801. The x86 architecture provides a few features to support the
  13802. implementation of functions. We have already seen that there are
  13803. labels in x86 so that one can refer to the location of an instruction,
  13804. as is needed for jump instructions. Labels can also be used to mark
  13805. the beginning of the instructions for a function. Going further, we
  13806. can obtain the address of a label by using the \key{leaq}
  13807. instruction. For example, the following puts the address of the
  13808. \code{inc} label into the \code{rbx} register:
  13809. \begin{lstlisting}
  13810. leaq inc(%rip), %rbx
  13811. \end{lstlisting}
  13812. Recall from section~\ref{sec:select-instructions-gc} that
  13813. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13814. addressing.
  13815. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13816. to functions whose locations were given by a label, such as
  13817. \code{read\_int}. To support function calls in this chapter we instead
  13818. jump to functions whose location are given by an address in
  13819. a register; that is, we use \emph{indirect function calls}. The
  13820. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13821. before the register name.\index{subject}{indirect function call}
  13822. \begin{lstlisting}
  13823. callq *%rbx
  13824. \end{lstlisting}
  13825. \subsection{Calling Conventions}
  13826. \label{sec:calling-conventions-fun}
  13827. \index{subject}{calling conventions}
  13828. The \code{callq} instruction provides partial support for implementing
  13829. functions: it pushes the return address on the stack and it jumps to
  13830. the target. However, \code{callq} does not handle
  13831. \begin{enumerate}
  13832. \item parameter passing,
  13833. \item pushing frames on the procedure call stack and popping them off,
  13834. or
  13835. \item determining how registers are shared by different functions.
  13836. \end{enumerate}
  13837. Regarding parameter passing, recall that the x86-64 calling
  13838. convention for Unix-based system uses the following six registers to
  13839. pass arguments to a function, in the given order.
  13840. \begin{lstlisting}
  13841. rdi rsi rdx rcx r8 r9
  13842. \end{lstlisting}
  13843. If there are more than six arguments, then the calling convention
  13844. mandates using space on the frame of the caller for the rest of the
  13845. arguments. However, to ease the implementation of efficient tail calls
  13846. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13847. arguments.
  13848. %
  13849. The return value of the function is stored in register \code{rax}.
  13850. \index{subject}{prelude}\index{subject}{conclusion}
  13851. Regarding frames \index{subject}{frame} and the procedure call stack,
  13852. \index{subject}{procedure call stack} recall from
  13853. section~\ref{sec:x86} that the stack grows down and each function call
  13854. uses a chunk of space on the stack called a frame. The caller sets the
  13855. stack pointer, register \code{rsp}, to the last data item in its
  13856. frame. The callee must not change anything in the caller's frame, that
  13857. is, anything that is at or above the stack pointer. The callee is free
  13858. to use locations that are below the stack pointer.
  13859. Recall that we store variables of tuple type on the root stack. So,
  13860. the prelude of a function needs to move the root stack pointer
  13861. \code{r15} up according to the number of variables of tuple type and
  13862. the conclusion needs to move the root stack pointer back down. Also,
  13863. the prelude must initialize to \code{0} this frame's slots in the root
  13864. stack to signal to the garbage collector that those slots do not yet
  13865. contain a valid pointer. Otherwise the garbage collector will
  13866. interpret the garbage bits in those slots as memory addresses and try
  13867. to traverse them, causing serious mayhem!
  13868. Regarding the sharing of registers between different functions, recall
  13869. from section~\ref{sec:calling-conventions} that the registers are
  13870. divided into two groups, the caller-saved registers and the
  13871. callee-saved registers. The caller should assume that all the
  13872. caller-saved registers are overwritten with arbitrary values by the
  13873. callee. For that reason we recommend in
  13874. section~\ref{sec:calling-conventions} that variables that are live
  13875. during a function call should not be assigned to caller-saved
  13876. registers.
  13877. On the flip side, if the callee wants to use a callee-saved register,
  13878. the callee must save the contents of those registers on their stack
  13879. frame and then put them back prior to returning to the caller. For
  13880. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13881. the register allocator assigns a variable to a callee-saved register,
  13882. then the prelude of the \code{main} function must save that register
  13883. to the stack and the conclusion of \code{main} must restore it. This
  13884. recommendation now generalizes to all functions.
  13885. Recall that the base pointer, register \code{rbp}, is used as a
  13886. point of reference within a frame, so that each local variable can be
  13887. accessed at a fixed offset from the base pointer
  13888. (section~\ref{sec:x86}).
  13889. %
  13890. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13891. and callee frames.
  13892. \begin{figure}[tbp]
  13893. \centering
  13894. \begin{tcolorbox}[colback=white]
  13895. \begin{tabular}{r|r|l|l} \hline
  13896. Caller View & Callee View & Contents & Frame \\ \hline
  13897. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13898. 0(\key{\%rbp}) & & old \key{rbp} \\
  13899. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13900. \ldots & & \ldots \\
  13901. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13902. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13903. \ldots & & \ldots \\
  13904. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13905. %% & & \\
  13906. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13907. %% & \ldots & \ldots \\
  13908. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13909. \hline
  13910. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13911. & 0(\key{\%rbp}) & old \key{rbp} \\
  13912. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13913. & \ldots & \ldots \\
  13914. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13915. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13916. & \ldots & \ldots \\
  13917. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13918. \end{tabular}
  13919. \end{tcolorbox}
  13920. \caption{Memory layout of caller and callee frames.}
  13921. \label{fig:call-frames}
  13922. \end{figure}
  13923. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13924. %% local variables and for storing the values of callee-saved registers
  13925. %% (we shall refer to all of these collectively as ``locals''), and that
  13926. %% at the beginning of a function we move the stack pointer \code{rsp}
  13927. %% down to make room for them.
  13928. %% We recommend storing the local variables
  13929. %% first and then the callee-saved registers, so that the local variables
  13930. %% can be accessed using \code{rbp} the same as before the addition of
  13931. %% functions.
  13932. %% To make additional room for passing arguments, we shall
  13933. %% move the stack pointer even further down. We count how many stack
  13934. %% arguments are needed for each function call that occurs inside the
  13935. %% body of the function and find their maximum. Adding this number to the
  13936. %% number of locals gives us how much the \code{rsp} should be moved at
  13937. %% the beginning of the function. In preparation for a function call, we
  13938. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13939. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13940. %% so on.
  13941. %% Upon calling the function, the stack arguments are retrieved by the
  13942. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13943. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13944. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13945. %% the layout of the caller and callee frames. Notice how important it is
  13946. %% that we correctly compute the maximum number of arguments needed for
  13947. %% function calls; if that number is too small then the arguments and
  13948. %% local variables will smash into each other!
  13949. \subsection{Efficient Tail Calls}
  13950. \label{sec:tail-call}
  13951. In general, the amount of stack space used by a program is determined
  13952. by the longest chain of nested function calls. That is, if function
  13953. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13954. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13955. large if functions are recursive. However, in some cases we can
  13956. arrange to use only a constant amount of space for a long chain of
  13957. nested function calls.
  13958. A \emph{tail call}\index{subject}{tail call} is a function call that
  13959. happens as the last action in a function body. For example, in the
  13960. following program, the recursive call to \code{tail\_sum} is a tail
  13961. call:
  13962. \begin{center}
  13963. {\if\edition\racketEd
  13964. \begin{lstlisting}
  13965. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13966. (if (eq? n 0)
  13967. r
  13968. (tail_sum (- n 1) (+ n r))))
  13969. (+ (tail_sum 3 0) 36)
  13970. \end{lstlisting}
  13971. \fi}
  13972. {\if\edition\pythonEd
  13973. \begin{lstlisting}
  13974. def tail_sum(n : int, r : int) -> int:
  13975. if n == 0:
  13976. return r
  13977. else:
  13978. return tail_sum(n - 1, n + r)
  13979. print( tail_sum(3, 0) + 36)
  13980. \end{lstlisting}
  13981. \fi}
  13982. \end{center}
  13983. At a tail call, the frame of the caller is no longer needed, so we can
  13984. pop the caller's frame before making the tail call. With this
  13985. approach, a recursive function that makes only tail calls ends up
  13986. using a constant amount of stack space. Functional languages like
  13987. Racket rely heavily on recursive functions, so the definition of
  13988. Racket \emph{requires} that all tail calls be optimized in this way.
  13989. \index{subject}{frame}
  13990. Some care is needed with regard to argument passing in tail calls. As
  13991. mentioned, for arguments beyond the sixth, the convention is to use
  13992. space in the caller's frame for passing arguments. However, for a
  13993. tail call we pop the caller's frame and can no longer use it. An
  13994. alternative is to use space in the callee's frame for passing
  13995. arguments. However, this option is also problematic because the caller
  13996. and callee's frames overlap in memory. As we begin to copy the
  13997. arguments from their sources in the caller's frame, the target
  13998. locations in the callee's frame might collide with the sources for
  13999. later arguments! We solve this problem by using the heap instead of
  14000. the stack for passing more than six arguments
  14001. (section~\ref{sec:limit-functions-r4}).
  14002. As mentioned, for a tail call we pop the caller's frame prior to
  14003. making the tail call. The instructions for popping a frame are the
  14004. instructions that we usually place in the conclusion of a
  14005. function. Thus, we also need to place such code immediately before
  14006. each tail call. These instructions include restoring the callee-saved
  14007. registers, so it is fortunate that the argument passing registers are
  14008. all caller-saved registers.
  14009. One note remains regarding which instruction to use to make the tail
  14010. call. When the callee is finished, it should not return to the current
  14011. function but instead return to the function that called the current
  14012. one. Thus, the return address that is already on the stack is the
  14013. right one, and we should not use \key{callq} to make the tail call
  14014. because that would overwrite the return address. Instead we simply use
  14015. the \key{jmp} instruction. As with the indirect function call, we write
  14016. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14017. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14018. jump target because the conclusion can overwrite just about everything
  14019. else.
  14020. \begin{lstlisting}
  14021. jmp *%rax
  14022. \end{lstlisting}
  14023. \section{Shrink \LangFun{}}
  14024. \label{sec:shrink-r4}
  14025. The \code{shrink} pass performs a minor modification to ease the
  14026. later passes. This pass introduces an explicit \code{main} function
  14027. that gobbles up all the top-level statements of the module.
  14028. %
  14029. \racket{It also changes the top \code{ProgramDefsExp} form to
  14030. \code{ProgramDefs}.}
  14031. {\if\edition\racketEd
  14032. \begin{lstlisting}
  14033. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14034. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14035. \end{lstlisting}
  14036. where $\itm{mainDef}$ is
  14037. \begin{lstlisting}
  14038. (Def 'main '() 'Integer '() |$\Exp'$|)
  14039. \end{lstlisting}
  14040. \fi}
  14041. {\if\edition\pythonEd
  14042. \begin{lstlisting}
  14043. Module(|$\Def\ldots\Stmt\ldots$|)
  14044. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14045. \end{lstlisting}
  14046. where $\itm{mainDef}$ is
  14047. \begin{lstlisting}
  14048. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14049. \end{lstlisting}
  14050. \fi}
  14051. \section{Reveal Functions and the \LangFunRef{} language}
  14052. \label{sec:reveal-functions-r4}
  14053. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14054. in that it conflates the use of function names and local
  14055. variables. This is a problem because we need to compile the use of a
  14056. function name differently from the use of a local variable. In
  14057. particular, we use \code{leaq} to convert the function name (a label
  14058. in x86) to an address in a register. Thus, we create a new pass that
  14059. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14060. $n$ is the arity of the function.\python{\footnote{The arity is not
  14061. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14062. This pass is named \code{reveal\_functions} and the output language
  14063. is \LangFunRef{}.
  14064. %is defined in figure~\ref{fig:f1-syntax}.
  14065. %% The concrete syntax for a
  14066. %% function reference is $\CFUNREF{f}$.
  14067. %% \begin{figure}[tp]
  14068. %% \centering
  14069. %% \fbox{
  14070. %% \begin{minipage}{0.96\textwidth}
  14071. %% {\if\edition\racketEd
  14072. %% \[
  14073. %% \begin{array}{lcl}
  14074. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14075. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14076. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14077. %% \end{array}
  14078. %% \]
  14079. %% \fi}
  14080. %% {\if\edition\pythonEd
  14081. %% \[
  14082. %% \begin{array}{lcl}
  14083. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14084. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14085. %% \end{array}
  14086. %% \]
  14087. %% \fi}
  14088. %% \end{minipage}
  14089. %% }
  14090. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14091. %% (figure~\ref{fig:Lfun-syntax}).}
  14092. %% \label{fig:f1-syntax}
  14093. %% \end{figure}
  14094. %% Distinguishing between calls in tail position and non-tail position
  14095. %% requires the pass to have some notion of context. We recommend using
  14096. %% two mutually recursive functions, one for processing expressions in
  14097. %% tail position and another for the rest.
  14098. \racket{Placing this pass after \code{uniquify} will make sure that
  14099. there are no local variables and functions that share the same
  14100. name.}
  14101. %
  14102. The \code{reveal\_functions} pass should come before the
  14103. \code{remove\_complex\_operands} pass because function references
  14104. should be categorized as complex expressions.
  14105. \section{Limit Functions}
  14106. \label{sec:limit-functions-r4}
  14107. Recall that we wish to limit the number of function parameters to six
  14108. so that we do not need to use the stack for argument passing, which
  14109. makes it easier to implement efficient tail calls. However, because
  14110. the input language \LangFun{} supports arbitrary numbers of function
  14111. arguments, we have some work to do! The \code{limit\_functions} pass
  14112. transforms functions and function calls that involve more than six
  14113. arguments to pass the first five arguments as usual, but it packs the
  14114. rest of the arguments into a tuple and passes it as the sixth
  14115. argument.\footnote{The implementation this pass can be postponed to
  14116. last because you can test the rest of the passes on functions with
  14117. six or fewer parameters.}
  14118. Each function definition with seven or more parameters is transformed as
  14119. follows.
  14120. {\if\edition\racketEd
  14121. \begin{lstlisting}
  14122. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14123. |$\Rightarrow$|
  14124. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14125. \end{lstlisting}
  14126. \fi}
  14127. {\if\edition\pythonEd
  14128. \begin{lstlisting}
  14129. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14130. |$\Rightarrow$|
  14131. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14132. |$T_r$|, None, |$\itm{body}'$|, None)
  14133. \end{lstlisting}
  14134. \fi}
  14135. %
  14136. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14137. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14138. the $k$th element of the tuple, where $k = i - 6$.
  14139. %
  14140. {\if\edition\racketEd
  14141. \begin{lstlisting}
  14142. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14143. \end{lstlisting}
  14144. \fi}
  14145. {\if\edition\pythonEd
  14146. \begin{lstlisting}
  14147. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14148. \end{lstlisting}
  14149. \fi}
  14150. For function calls with too many arguments, the \code{limit\_functions}
  14151. pass transforms them in the following way:
  14152. \begin{tabular}{lll}
  14153. \begin{minipage}{0.3\textwidth}
  14154. {\if\edition\racketEd
  14155. \begin{lstlisting}
  14156. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14157. \end{lstlisting}
  14158. \fi}
  14159. {\if\edition\pythonEd
  14160. \begin{lstlisting}
  14161. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14162. \end{lstlisting}
  14163. \fi}
  14164. \end{minipage}
  14165. &
  14166. $\Rightarrow$
  14167. &
  14168. \begin{minipage}{0.5\textwidth}
  14169. {\if\edition\racketEd
  14170. \begin{lstlisting}
  14171. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14172. \end{lstlisting}
  14173. \fi}
  14174. {\if\edition\pythonEd
  14175. \begin{lstlisting}
  14176. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14177. \end{lstlisting}
  14178. \fi}
  14179. \end{minipage}
  14180. \end{tabular}
  14181. \section{Remove Complex Operands}
  14182. \label{sec:rco-r4}
  14183. The primary decisions to make for this pass are whether to classify
  14184. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14185. atomic or complex expressions. Recall that an atomic expression will
  14186. end up as an immediate argument of an x86 instruction. Function
  14187. application will be translated to a sequence of instructions, so
  14188. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14189. complex expression. On the other hand, the arguments of
  14190. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14191. expressions.
  14192. %
  14193. Regarding \code{FunRef}, as discussed previously, the function label
  14194. needs to be converted to an address using the \code{leaq}
  14195. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14196. needs to be classified as a complex expression so that we generate an
  14197. assignment statement with a left-hand side that can serve as the
  14198. target of the \code{leaq}.
  14199. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14200. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14201. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14202. and augments programs to include a list of function definitions.
  14203. %
  14204. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14205. \newcommand{\LfunMonadASTRacket}{
  14206. \begin{array}{lcl}
  14207. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14208. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14209. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14210. \end{array}
  14211. }
  14212. \newcommand{\LfunMonadASTPython}{
  14213. \begin{array}{lcl}
  14214. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  14215. \MID \key{TupleType}\LS\Type^+\RS\\
  14216. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14217. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14218. \Stmt &::=& \RETURN{\Exp} \\
  14219. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14220. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14221. \end{array}
  14222. }
  14223. \begin{figure}[tp]
  14224. \centering
  14225. \begin{tcolorbox}[colback=white]
  14226. \small
  14227. {\if\edition\racketEd
  14228. \[
  14229. \begin{array}{l}
  14230. \gray{\LvarMonadASTRacket} \\ \hline
  14231. \gray{\LifMonadASTRacket} \\ \hline
  14232. \gray{\LwhileMonadASTRacket} \\ \hline
  14233. \gray{\LtupMonadASTRacket} \\ \hline
  14234. \LfunMonadASTRacket \\
  14235. \begin{array}{rcl}
  14236. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14237. \end{array}
  14238. \end{array}
  14239. \]
  14240. \fi}
  14241. {\if\edition\pythonEd
  14242. \[
  14243. \begin{array}{l}
  14244. \gray{\LvarMonadASTPython} \\ \hline
  14245. \gray{\LifMonadASTPython} \\ \hline
  14246. \gray{\LwhileMonadASTPython} \\ \hline
  14247. \gray{\LtupMonadASTPython} \\ \hline
  14248. \LfunMonadASTPython \\
  14249. \begin{array}{rcl}
  14250. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14251. \end{array}
  14252. \end{array}
  14253. \]
  14254. \fi}
  14255. \end{tcolorbox}
  14256. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14257. \label{fig:Lfun-anf-syntax}
  14258. \end{figure}
  14259. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14260. %% \LangFunANF{} of this pass.
  14261. %% \begin{figure}[tp]
  14262. %% \centering
  14263. %% \fbox{
  14264. %% \begin{minipage}{0.96\textwidth}
  14265. %% \small
  14266. %% \[
  14267. %% \begin{array}{rcl}
  14268. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14269. %% \MID \VOID{} } \\
  14270. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14271. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14272. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14273. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14274. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14275. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14276. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14277. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14278. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14279. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14280. %% \end{array}
  14281. %% \]
  14282. %% \end{minipage}
  14283. %% }
  14284. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14285. %% \label{fig:Lfun-anf-syntax}
  14286. %% \end{figure}
  14287. \section{Explicate Control and the \LangCFun{} language}
  14288. \label{sec:explicate-control-r4}
  14289. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14290. output of \code{explicate\_control}.
  14291. %
  14292. %% \racket{(The concrete syntax is given in
  14293. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14294. %
  14295. The auxiliary functions for assignment\racket{ and tail contexts} should
  14296. be updated with cases for
  14297. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14298. function for predicate context should be updated for
  14299. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14300. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14301. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14302. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14303. auxiliary function for processing function definitions. This code is
  14304. similar to the case for \code{Program} in \LangVec{}. The top-level
  14305. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14306. form of \LangFun{} can then apply this new function to all the
  14307. function definitions.
  14308. {\if\edition\pythonEd
  14309. The translation of \code{Return} statements requires a new auxiliary
  14310. function to handle expressions in tail context, called
  14311. \code{explicate\_tail}. The function should take an expression and the
  14312. dictionary of basic blocks and produce a list of statements in the
  14313. \LangCFun{} language. The \code{explicate\_tail} function should
  14314. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  14315. and a default case for other kinds of expressions. The default case
  14316. should produce a \code{Return} statement. The case for \code{Call}
  14317. should change it into \code{TailCall}. The other cases should
  14318. recursively process their subexpressions and statements, choosing the
  14319. appropriate explicate functions for the various contexts.
  14320. \fi}
  14321. \newcommand{\CfunASTRacket}{
  14322. \begin{array}{lcl}
  14323. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14324. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14325. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14326. \end{array}
  14327. }
  14328. \newcommand{\CfunASTPython}{
  14329. \begin{array}{lcl}
  14330. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14331. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14332. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14333. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  14334. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  14335. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  14336. \end{array}
  14337. }
  14338. \begin{figure}[tp]
  14339. \begin{tcolorbox}[colback=white]
  14340. \small
  14341. {\if\edition\racketEd
  14342. \[
  14343. \begin{array}{l}
  14344. \gray{\CvarASTRacket} \\ \hline
  14345. \gray{\CifASTRacket} \\ \hline
  14346. \gray{\CloopASTRacket} \\ \hline
  14347. \gray{\CtupASTRacket} \\ \hline
  14348. \CfunASTRacket \\
  14349. \begin{array}{lcl}
  14350. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14351. \end{array}
  14352. \end{array}
  14353. \]
  14354. \fi}
  14355. {\if\edition\pythonEd
  14356. \[
  14357. \begin{array}{l}
  14358. \gray{\CifASTPython} \\ \hline
  14359. \gray{\CtupASTPython} \\ \hline
  14360. \CfunASTPython \\
  14361. \begin{array}{lcl}
  14362. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14363. \end{array}
  14364. \end{array}
  14365. \]
  14366. \fi}
  14367. \end{tcolorbox}
  14368. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14369. \label{fig:c3-syntax}
  14370. \end{figure}
  14371. \clearpage
  14372. \section{Select Instructions and the \LangXIndCall{} Language}
  14373. \label{sec:select-r4}
  14374. \index{subject}{instruction selection}
  14375. The output of select instructions is a program in the \LangXIndCall{}
  14376. language; the definition of its concrete syntax is shown in
  14377. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14378. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14379. directive on the labels of function definitions to make sure the
  14380. bottom three bits are zero, which we put to use in
  14381. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14382. this section. \index{subject}{x86}
  14383. \newcommand{\GrammarXIndCall}{
  14384. \begin{array}{lcl}
  14385. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14386. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14387. \Block &::= & \Instr^{+} \\
  14388. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14389. \end{array}
  14390. }
  14391. \newcommand{\ASTXIndCallRacket}{
  14392. \begin{array}{lcl}
  14393. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14394. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14395. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14396. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14397. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14398. \end{array}
  14399. }
  14400. \begin{figure}[tp]
  14401. \begin{tcolorbox}[colback=white]
  14402. \small
  14403. \[
  14404. \begin{array}{l}
  14405. \gray{\GrammarXInt} \\ \hline
  14406. \gray{\GrammarXIf} \\ \hline
  14407. \gray{\GrammarXGlobal} \\ \hline
  14408. \GrammarXIndCall \\
  14409. \begin{array}{lcl}
  14410. \LangXIndCallM{} &::= & \Def^{*}
  14411. \end{array}
  14412. \end{array}
  14413. \]
  14414. \end{tcolorbox}
  14415. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14416. \label{fig:x86-3-concrete}
  14417. \end{figure}
  14418. \begin{figure}[tp]
  14419. \begin{tcolorbox}[colback=white]
  14420. \small
  14421. {\if\edition\racketEd
  14422. \[\arraycolsep=3pt
  14423. \begin{array}{l}
  14424. \gray{\ASTXIntRacket} \\ \hline
  14425. \gray{\ASTXIfRacket} \\ \hline
  14426. \gray{\ASTXGlobalRacket} \\ \hline
  14427. \ASTXIndCallRacket \\
  14428. \begin{array}{lcl}
  14429. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14430. \end{array}
  14431. \end{array}
  14432. \]
  14433. \fi}
  14434. {\if\edition\pythonEd
  14435. \[
  14436. \begin{array}{lcl}
  14437. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14438. \MID \BYTEREG{\Reg} } \\
  14439. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14440. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14441. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14442. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14443. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14444. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  14445. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  14446. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14447. \end{array}
  14448. \]
  14449. \fi}
  14450. \end{tcolorbox}
  14451. \caption{The abstract syntax of \LangXIndCall{} (extends
  14452. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14453. \label{fig:x86-3}
  14454. \end{figure}
  14455. An assignment of a function reference to a variable becomes a
  14456. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14457. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14458. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14459. node, whose concrete syntax is instruction-pointer-relative
  14460. addressing.
  14461. \begin{center}
  14462. \begin{tabular}{lcl}
  14463. \begin{minipage}{0.35\textwidth}
  14464. {\if\edition\racketEd
  14465. \begin{lstlisting}
  14466. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14467. \end{lstlisting}
  14468. \fi}
  14469. {\if\edition\pythonEd
  14470. \begin{lstlisting}
  14471. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14472. \end{lstlisting}
  14473. \fi}
  14474. \end{minipage}
  14475. &
  14476. $\Rightarrow$\qquad\qquad
  14477. &
  14478. \begin{minipage}{0.3\textwidth}
  14479. \begin{lstlisting}
  14480. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14481. \end{lstlisting}
  14482. \end{minipage}
  14483. \end{tabular}
  14484. \end{center}
  14485. Regarding function definitions, we need to remove the parameters and
  14486. instead perform parameter passing using the conventions discussed in
  14487. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14488. registers. We recommend turning the parameters into local variables
  14489. and generating instructions at the beginning of the function to move
  14490. from the argument-passing registers
  14491. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14492. {\if\edition\racketEd
  14493. \begin{lstlisting}
  14494. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14495. |$\Rightarrow$|
  14496. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14497. \end{lstlisting}
  14498. \fi}
  14499. {\if\edition\pythonEd
  14500. \begin{lstlisting}
  14501. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14502. |$\Rightarrow$|
  14503. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14504. \end{lstlisting}
  14505. \fi}
  14506. The basic blocks $B'$ are the same as $B$ except that the
  14507. \code{start} block is modified to add the instructions for moving from
  14508. the argument registers to the parameter variables. So the \code{start}
  14509. block of $B$ shown on the left of the following is changed to the code
  14510. on the right:
  14511. \begin{center}
  14512. \begin{minipage}{0.3\textwidth}
  14513. \begin{lstlisting}
  14514. start:
  14515. |$\itm{instr}_1$|
  14516. |$\cdots$|
  14517. |$\itm{instr}_n$|
  14518. \end{lstlisting}
  14519. \end{minipage}
  14520. $\Rightarrow$
  14521. \begin{minipage}{0.3\textwidth}
  14522. \begin{lstlisting}
  14523. |$f$|start:
  14524. movq %rdi, |$x_1$|
  14525. movq %rsi, |$x_2$|
  14526. |$\cdots$|
  14527. |$\itm{instr}_1$|
  14528. |$\cdots$|
  14529. |$\itm{instr}_n$|
  14530. \end{lstlisting}
  14531. \end{minipage}
  14532. \end{center}
  14533. Recall that we use the label \code{start} for the initial block of a
  14534. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14535. the conclusion of the program with \code{conclusion}, so that
  14536. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14537. by a jump to \code{conclusion}. With the addition of function
  14538. definitions, there is a start block and conclusion for each function,
  14539. but their labels need to be unique. We recommend prepending the
  14540. function's name to \code{start} and \code{conclusion}, respectively,
  14541. to obtain unique labels.
  14542. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14543. number of parameters the function expects, but the parameters are no
  14544. longer in the syntax of function definitions. Instead, add an entry
  14545. to $\itm{info}$ that maps \code{num-params} to the number of
  14546. parameters to construct $\itm{info}'$.}
  14547. By changing the parameters to local variables, we are giving the
  14548. register allocator control over which registers or stack locations to
  14549. use for them. If you implement the move-biasing challenge
  14550. (section~\ref{sec:move-biasing}), the register allocator will try to
  14551. assign the parameter variables to the corresponding argument register,
  14552. in which case the \code{patch\_instructions} pass will remove the
  14553. \code{movq} instruction. This happens in the example translation given
  14554. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14555. the \code{add} function.
  14556. %
  14557. Also, note that the register allocator will perform liveness analysis
  14558. on this sequence of move instructions and build the interference
  14559. graph. So, for example, $x_1$ will be marked as interfering with
  14560. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14561. which is good because otherwise the first \code{movq} would overwrite
  14562. the argument in \code{rsi} that is needed for $x_2$.
  14563. Next, consider the compilation of function calls. In the mirror image
  14564. of the handling of parameters in function definitions, the arguments
  14565. are moved to the argument-passing registers. Note that the function
  14566. is not given as a label, but its address is produced by the argument
  14567. $\itm{arg}_0$. So, we translate the call into an indirect function
  14568. call. The return value from the function is stored in \code{rax}, so
  14569. it needs to be moved into the \itm{lhs}.
  14570. \begin{lstlisting}
  14571. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  14572. |$\Rightarrow$|
  14573. movq |$\itm{arg}_1$|, %rdi
  14574. movq |$\itm{arg}_2$|, %rsi
  14575. |$\vdots$|
  14576. callq *|$\itm{arg}_0$|
  14577. movq %rax, |$\itm{lhs}$|
  14578. \end{lstlisting}
  14579. The \code{IndirectCallq} AST node includes an integer for the arity of
  14580. the function, that is, the number of parameters. That information is
  14581. useful in the \code{uncover\_live} pass for determining which
  14582. argument-passing registers are potentially read during the call.
  14583. For tail calls, the parameter passing is the same as non-tail calls:
  14584. generate instructions to move the arguments into the argument-passing
  14585. registers. After that we need to pop the frame from the procedure
  14586. call stack. However, we do not yet know how big the frame is; that
  14587. gets determined during register allocation. So, instead of generating
  14588. those instructions here, we invent a new instruction that means ``pop
  14589. the frame and then do an indirect jump,'' which we name
  14590. \code{TailJmp}. The abstract syntax for this instruction includes an
  14591. argument that specifies where to jump and an integer that represents
  14592. the arity of the function being called.
  14593. \section{Register Allocation}
  14594. \label{sec:register-allocation-r4}
  14595. The addition of functions requires some changes to all three aspects
  14596. of register allocation, which we discuss in the following subsections.
  14597. \subsection{Liveness Analysis}
  14598. \label{sec:liveness-analysis-r4}
  14599. \index{subject}{liveness analysis}
  14600. %% The rest of the passes need only minor modifications to handle the new
  14601. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14602. %% \code{leaq}.
  14603. The \code{IndirectCallq} instruction should be treated like
  14604. \code{Callq} regarding its written locations $W$, in that they should
  14605. include all the caller-saved registers. Recall that the reason for
  14606. that is to force variables that are live across a function call to be assigned to callee-saved
  14607. registers or to be spilled to the stack.
  14608. Regarding the set of read locations $R$, the arity field of
  14609. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14610. argument-passing registers should be considered as read by those
  14611. instructions. Also, the target field of \code{TailJmp} and
  14612. \code{IndirectCallq} should be included in the set of read locations
  14613. $R$.
  14614. \subsection{Build Interference Graph}
  14615. \label{sec:build-interference-r4}
  14616. With the addition of function definitions, we compute a separate interference
  14617. graph for each function (not just one for the whole program).
  14618. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14619. spill tuple-typed variables that are live during a call to
  14620. \code{collect}, the garbage collector. With the addition of functions
  14621. to our language, we need to revisit this issue. Functions that perform
  14622. allocation contain calls to the collector. Thus, we should not only
  14623. spill a tuple-typed variable when it is live during a call to
  14624. \code{collect}, but we should spill the variable if it is live during
  14625. call to any user-defined function. Thus, in the
  14626. \code{build\_interference} pass, we recommend adding interference
  14627. edges between call-live tuple-typed variables and the callee-saved
  14628. registers (in addition to the usual addition of edges between
  14629. call-live variables and the caller-saved registers).
  14630. \subsection{Allocate Registers}
  14631. The primary change to the \code{allocate\_registers} pass is adding an
  14632. auxiliary function for handling definitions (the \Def{} nonterminal
  14633. shown in figure~\ref{fig:x86-3}) with one case for function
  14634. definitions. The logic is the same as described in
  14635. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14636. allocation is performed many times, once for each function definition,
  14637. instead of just once for the whole program.
  14638. \section{Patch Instructions}
  14639. In \code{patch\_instructions}, you should deal with the x86
  14640. idiosyncrasy that the destination argument of \code{leaq} must be a
  14641. register. Additionally, you should ensure that the argument of
  14642. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14643. trample many other registers before the tail call, as explained in the
  14644. next section.
  14645. \section{Prelude and Conclusion}
  14646. Now that register allocation is complete, we can translate the
  14647. \code{TailJmp} into a sequence of instructions. A naive translation of
  14648. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14649. before the jump we need to pop the current frame to achieve efficient
  14650. tail calls. This sequence of instructions is the same as the code for
  14651. the conclusion of a function, except that the \code{retq} is replaced with
  14652. \code{jmp *$\itm{arg}$}.
  14653. Regarding function definitions, we generate a prelude and conclusion
  14654. for each one. This code is similar to the prelude and conclusion
  14655. generated for the \code{main} function presented in
  14656. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14657. carry out the following steps:
  14658. % TODO: .align the functions!
  14659. \begin{enumerate}
  14660. %% \item Start with \code{.global} and \code{.align} directives followed
  14661. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14662. %% example.)
  14663. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14664. pointer.
  14665. \item Push to the stack all the callee-saved registers that were
  14666. used for register allocation.
  14667. \item Move the stack pointer \code{rsp} down to make room for the
  14668. regular spills (aligned to 16 bytes).
  14669. \item Move the root stack pointer \code{r15} up by the size of the
  14670. root-stack frame for this function, which depends on the number of
  14671. spilled tuple-typed variables. \label{root-stack-init}
  14672. \item Initialize to zero all new entries in the root-stack frame.
  14673. \item Jump to the start block.
  14674. \end{enumerate}
  14675. The prelude of the \code{main} function has an additional task: call
  14676. the \code{initialize} function to set up the garbage collector, and
  14677. then move the value of the global \code{rootstack\_begin} in
  14678. \code{r15}. This initialization should happen before step
  14679. \ref{root-stack-init}, which depends on \code{r15}.
  14680. The conclusion of every function should do the following:
  14681. \begin{enumerate}
  14682. \item Move the stack pointer back up past the regular spills.
  14683. \item Restore the callee-saved registers by popping them from the
  14684. stack.
  14685. \item Move the root stack pointer back down by the size of the
  14686. root-stack frame for this function.
  14687. \item Restore \code{rbp} by popping it from the stack.
  14688. \item Return to the caller with the \code{retq} instruction.
  14689. \end{enumerate}
  14690. The output of this pass is \LangXIndCallFlat{}, which differs from
  14691. \LangXIndCall{} in that there is no longer an AST node for function
  14692. definitions. Instead, a program is just an association list of basic
  14693. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14694. \[
  14695. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14696. \]
  14697. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14698. compiling \LangFun{} to x86.
  14699. \begin{exercise}\normalfont\normalsize
  14700. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14701. Create eight new programs that use functions, including examples that
  14702. pass functions and return functions from other functions, recursive
  14703. functions, functions that create vectors, and functions that make tail
  14704. calls. Test your compiler on these new programs and all your
  14705. previously created test programs.
  14706. \end{exercise}
  14707. \begin{figure}[tbp]
  14708. \begin{tcolorbox}[colback=white]
  14709. {\if\edition\racketEd
  14710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14711. \node (Lfun) at (0,2) {\large \LangFun{}};
  14712. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14713. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14714. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14715. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14716. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14717. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14718. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14719. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14720. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14721. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14722. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14723. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14724. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14725. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14726. \path[->,bend left=15] (Lfun) edge [above] node
  14727. {\ttfamily\footnotesize shrink} (Lfun-1);
  14728. \path[->,bend left=15] (Lfun-1) edge [above] node
  14729. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14730. \path[->,bend left=15] (Lfun-2) edge [above] node
  14731. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14732. \path[->,bend left=15] (F1-1) edge [left] node
  14733. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14734. \path[->,bend left=15] (F1-2) edge [below] node
  14735. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14736. \path[->,bend left=15] (F1-3) edge [below] node
  14737. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14738. \path[->,bend right=15] (F1-4) edge [above] node
  14739. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14740. \path[->,bend right=15] (F1-5) edge [right] node
  14741. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14742. \path[->,bend right=15] (C3-2) edge [right] node
  14743. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14744. \path[->,bend left=15] (x86-2) edge [right] node
  14745. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14746. \path[->,bend right=15] (x86-2-1) edge [below] node
  14747. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14748. \path[->,bend right=15] (x86-2-2) edge [right] node
  14749. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14750. \path[->,bend left=15] (x86-3) edge [above] node
  14751. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14752. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14753. \end{tikzpicture}
  14754. \fi}
  14755. {\if\edition\pythonEd
  14756. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14757. \node (Lfun) at (0,2) {\large \LangFun{}};
  14758. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14759. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14760. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14761. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14762. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14763. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14764. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14765. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14766. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14767. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14768. \path[->,bend left=15] (Lfun) edge [above] node
  14769. {\ttfamily\footnotesize shrink} (Lfun-2);
  14770. \path[->,bend left=15] (Lfun-2) edge [above] node
  14771. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14772. \path[->,bend left=15] (F1-1) edge [above] node
  14773. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14774. \path[->,bend left=15] (F1-2) edge [right] node
  14775. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  14776. \path[->,bend right=15] (F1-4) edge [above] node
  14777. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14778. \path[->,bend right=15] (F1-5) edge [right] node
  14779. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14780. \path[->,bend left=15] (C3-2) edge [right] node
  14781. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14782. \path[->,bend right=15] (x86-2) edge [below] node
  14783. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14784. \path[->,bend left=15] (x86-3) edge [above] node
  14785. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14786. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14787. \end{tikzpicture}
  14788. \fi}
  14789. \end{tcolorbox}
  14790. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14791. \label{fig:Lfun-passes}
  14792. \end{figure}
  14793. \section{An Example Translation}
  14794. \label{sec:functions-example}
  14795. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14796. function in \LangFun{} to x86. The figure also includes the results of the
  14797. \code{explicate\_control} and \code{select\_instructions} passes.
  14798. \begin{figure}[htbp]
  14799. \begin{tcolorbox}[colback=white]
  14800. \begin{tabular}{ll}
  14801. \begin{minipage}{0.4\textwidth}
  14802. % s3_2.rkt
  14803. {\if\edition\racketEd
  14804. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14805. (define (add [x : Integer]
  14806. [y : Integer])
  14807. : Integer
  14808. (+ x y))
  14809. (add 40 2)
  14810. \end{lstlisting}
  14811. \fi}
  14812. {\if\edition\pythonEd
  14813. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14814. def add(x:int, y:int) -> int:
  14815. return x + y
  14816. print(add(40, 2))
  14817. \end{lstlisting}
  14818. \fi}
  14819. $\Downarrow$
  14820. {\if\edition\racketEd
  14821. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14822. (define (add86 [x87 : Integer]
  14823. [y88 : Integer])
  14824. : Integer
  14825. add86start:
  14826. return (+ x87 y88);
  14827. )
  14828. (define (main) : Integer ()
  14829. mainstart:
  14830. tmp89 = (fun-ref add86 2);
  14831. (tail-call tmp89 40 2)
  14832. )
  14833. \end{lstlisting}
  14834. \fi}
  14835. {\if\edition\pythonEd
  14836. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14837. def add(x:int, y:int) -> int:
  14838. addstart:
  14839. return x + y
  14840. def main() -> int:
  14841. mainstart:
  14842. fun.0 = add
  14843. tmp.1 = fun.0(40, 2)
  14844. print(tmp.1)
  14845. return 0
  14846. \end{lstlisting}
  14847. \fi}
  14848. \end{minipage}
  14849. &
  14850. $\Rightarrow$
  14851. \begin{minipage}{0.5\textwidth}
  14852. {\if\edition\racketEd
  14853. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14854. (define (add86) : Integer
  14855. add86start:
  14856. movq %rdi, x87
  14857. movq %rsi, y88
  14858. movq x87, %rax
  14859. addq y88, %rax
  14860. jmp inc1389conclusion
  14861. )
  14862. (define (main) : Integer
  14863. mainstart:
  14864. leaq (fun-ref add86 2), tmp89
  14865. movq $40, %rdi
  14866. movq $2, %rsi
  14867. tail-jmp tmp89
  14868. )
  14869. \end{lstlisting}
  14870. \fi}
  14871. {\if\edition\pythonEd
  14872. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14873. def add() -> int:
  14874. addstart:
  14875. movq %rdi, x
  14876. movq %rsi, y
  14877. movq x, %rax
  14878. addq y, %rax
  14879. jmp addconclusion
  14880. def main() -> int:
  14881. mainstart:
  14882. leaq add, fun.0
  14883. movq $40, %rdi
  14884. movq $2, %rsi
  14885. callq *fun.0
  14886. movq %rax, tmp.1
  14887. movq tmp.1, %rdi
  14888. callq print_int
  14889. movq $0, %rax
  14890. jmp mainconclusion
  14891. \end{lstlisting}
  14892. \fi}
  14893. $\Downarrow$
  14894. \end{minipage}
  14895. \end{tabular}
  14896. \begin{tabular}{ll}
  14897. \begin{minipage}{0.3\textwidth}
  14898. {\if\edition\racketEd
  14899. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14900. .globl add86
  14901. .align 8
  14902. add86:
  14903. pushq %rbp
  14904. movq %rsp, %rbp
  14905. jmp add86start
  14906. add86start:
  14907. movq %rdi, %rax
  14908. addq %rsi, %rax
  14909. jmp add86conclusion
  14910. add86conclusion:
  14911. popq %rbp
  14912. retq
  14913. \end{lstlisting}
  14914. \fi}
  14915. {\if\edition\pythonEd
  14916. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14917. .align 8
  14918. add:
  14919. pushq %rbp
  14920. movq %rsp, %rbp
  14921. subq $0, %rsp
  14922. jmp addstart
  14923. addstart:
  14924. movq %rdi, %rdx
  14925. movq %rsi, %rcx
  14926. movq %rdx, %rax
  14927. addq %rcx, %rax
  14928. jmp addconclusion
  14929. addconclusion:
  14930. subq $0, %r15
  14931. addq $0, %rsp
  14932. popq %rbp
  14933. retq
  14934. \end{lstlisting}
  14935. \fi}
  14936. \end{minipage}
  14937. &
  14938. \begin{minipage}{0.5\textwidth}
  14939. {\if\edition\racketEd
  14940. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14941. .globl main
  14942. .align 8
  14943. main:
  14944. pushq %rbp
  14945. movq %rsp, %rbp
  14946. movq $16384, %rdi
  14947. movq $16384, %rsi
  14948. callq initialize
  14949. movq rootstack_begin(%rip), %r15
  14950. jmp mainstart
  14951. mainstart:
  14952. leaq add86(%rip), %rcx
  14953. movq $40, %rdi
  14954. movq $2, %rsi
  14955. movq %rcx, %rax
  14956. popq %rbp
  14957. jmp *%rax
  14958. mainconclusion:
  14959. popq %rbp
  14960. retq
  14961. \end{lstlisting}
  14962. \fi}
  14963. {\if\edition\pythonEd
  14964. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14965. .globl main
  14966. .align 8
  14967. main:
  14968. pushq %rbp
  14969. movq %rsp, %rbp
  14970. subq $0, %rsp
  14971. movq $65536, %rdi
  14972. movq $65536, %rsi
  14973. callq initialize
  14974. movq rootstack_begin(%rip), %r15
  14975. jmp mainstart
  14976. mainstart:
  14977. leaq add(%rip), %rcx
  14978. movq $40, %rdi
  14979. movq $2, %rsi
  14980. callq *%rcx
  14981. movq %rax, %rcx
  14982. movq %rcx, %rdi
  14983. callq print_int
  14984. movq $0, %rax
  14985. jmp mainconclusion
  14986. mainconclusion:
  14987. subq $0, %r15
  14988. addq $0, %rsp
  14989. popq %rbp
  14990. retq
  14991. \end{lstlisting}
  14992. \fi}
  14993. \end{minipage}
  14994. \end{tabular}
  14995. \end{tcolorbox}
  14996. \caption{Example compilation of a simple function to x86.}
  14997. \label{fig:add-fun}
  14998. \end{figure}
  14999. % Challenge idea: inlining! (simple version)
  15000. % Further Reading
  15001. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15002. \chapter{Lexically Scoped Functions}
  15003. \label{ch:Llambda}
  15004. \index{subject}{lambda}
  15005. \index{subject}{lexical scoping}
  15006. \setcounter{footnote}{0}
  15007. This chapter studies lexically scoped functions. Lexical scoping means
  15008. that a function's body may refer to variables whose binding site is
  15009. outside of the function, in an enclosing scope.
  15010. %
  15011. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15012. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  15013. creating lexically scoped functions. The body of the \key{lambda}
  15014. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  15015. binding sites for \code{x} and \code{y} are outside of the
  15016. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  15017. \key{let}}\python{a local variable of function \code{f}}, and
  15018. \code{x} is a parameter of function \code{f}. Note that function
  15019. \code{f} returns the \key{lambda} as its result value. The main
  15020. expression of the program includes two calls to \code{f} with
  15021. different arguments for \code{x}: first \code{5} and then \code{3}. The
  15022. functions returned from \code{f} are bound to variables \code{g} and
  15023. \code{h}. Even though these two functions were created by the same
  15024. \code{lambda}, they are really different functions because they use
  15025. different values for \code{x}. Applying \code{g} to \code{11} produces
  15026. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  15027. so the result of the program is \code{42}.
  15028. \begin{figure}[btp]
  15029. \begin{tcolorbox}[colback=white]
  15030. {\if\edition\racketEd
  15031. % lambda_test_21.rkt
  15032. \begin{lstlisting}
  15033. (define (f [x : Integer]) : (Integer -> Integer)
  15034. (let ([y 4])
  15035. (lambda: ([z : Integer]) : Integer
  15036. (+ x (+ y z)))))
  15037. (let ([g (f 5)])
  15038. (let ([h (f 3)])
  15039. (+ (g 11) (h 15))))
  15040. \end{lstlisting}
  15041. \fi}
  15042. {\if\edition\pythonEd
  15043. \begin{lstlisting}
  15044. def f(x : int) -> Callable[[int], int]:
  15045. y = 4
  15046. return lambda z: x + y + z
  15047. g = f(5)
  15048. h = f(3)
  15049. print( g(11) + h(15) )
  15050. \end{lstlisting}
  15051. \fi}
  15052. \end{tcolorbox}
  15053. \caption{Example of a lexically scoped function.}
  15054. \label{fig:lexical-scoping}
  15055. \end{figure}
  15056. The approach that we take for implementing lexically scoped functions
  15057. is to compile them into top-level function definitions, translating
  15058. from \LangLam{} into \LangFun{}. However, the compiler must give
  15059. special treatment to variable occurrences such as \code{x} and
  15060. \code{y} in the body of the \code{lambda} shown in
  15061. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15062. may not refer to variables defined outside of it. To identify such
  15063. variable occurrences, we review the standard notion of free variable.
  15064. \begin{definition}\normalfont
  15065. A variable is \emph{free in expression} $e$ if the variable occurs
  15066. inside $e$ but does not have an enclosing definition that is also in
  15067. $e$.\index{subject}{free variable}
  15068. \end{definition}
  15069. For example, in the expression
  15070. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15071. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15072. only \code{x} and \code{y} are free in the following expression,
  15073. because \code{z} is defined by the \code{lambda}
  15074. {\if\edition\racketEd
  15075. \begin{lstlisting}
  15076. (lambda: ([z : Integer]) : Integer
  15077. (+ x (+ y z)))
  15078. \end{lstlisting}
  15079. \fi}
  15080. {\if\edition\pythonEd
  15081. \begin{lstlisting}
  15082. lambda z: x + y + z
  15083. \end{lstlisting}
  15084. \fi}
  15085. %
  15086. \noindent Thus the free variables of a \code{lambda} are the ones that
  15087. need special treatment. We need to transport at runtime the values
  15088. of those variables from the point where the \code{lambda} was created
  15089. to the point where the \code{lambda} is applied. An efficient solution
  15090. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15091. values of the free variables together with a function pointer into a
  15092. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15093. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15094. closure}
  15095. %
  15096. By design, we have all the ingredients to make closures:
  15097. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15098. function pointers. The function pointer resides at index $0$, and the
  15099. values for the free variables fill in the rest of the tuple.
  15100. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15101. to see how closures work. It is a three-step dance. The program calls
  15102. function \code{f}, which creates a closure for the \code{lambda}. The
  15103. closure is a tuple whose first element is a pointer to the top-level
  15104. function that we will generate for the \code{lambda}; the second
  15105. element is the value of \code{x}, which is \code{5}; and the third
  15106. element is \code{4}, the value of \code{y}. The closure does not
  15107. contain an element for \code{z} because \code{z} is not a free
  15108. variable of the \code{lambda}. Creating the closure is step 1 of the
  15109. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15110. shown in figure~\ref{fig:closures}.
  15111. %
  15112. The second call to \code{f} creates another closure, this time with
  15113. \code{3} in the second slot (for \code{x}). This closure is also
  15114. returned from \code{f} but bound to \code{h}, which is also shown in
  15115. figure~\ref{fig:closures}.
  15116. \begin{figure}[tbp]
  15117. \centering
  15118. \begin{minipage}{0.65\textwidth}
  15119. \begin{tcolorbox}[colback=white]
  15120. \includegraphics[width=\textwidth]{figs/closures}
  15121. \end{tcolorbox}
  15122. \end{minipage}
  15123. \caption{Flat closure representations for the two functions
  15124. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15125. \label{fig:closures}
  15126. \end{figure}
  15127. Continuing with the example, consider the application of \code{g} to
  15128. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15129. closure, we obtain the function pointer from the first element of the
  15130. closure and call it, passing in the closure itself and then the
  15131. regular arguments, in this case \code{11}. This technique for applying
  15132. a closure is step 2 of the dance.
  15133. %
  15134. But doesn't this \code{lambda} take only one argument, for parameter
  15135. \code{z}? The third and final step of the dance is generating a
  15136. top-level function for a \code{lambda}. We add an additional
  15137. parameter for the closure and insert an initialization at the beginning
  15138. of the function for each free variable, to bind those variables to the
  15139. appropriate elements from the closure parameter.
  15140. %
  15141. This three-step dance is known as \emph{closure conversion}. We
  15142. discuss the details of closure conversion in
  15143. section~\ref{sec:closure-conversion} and show the code generated from
  15144. the example in section~\ref{sec:example-lambda}. First, we define
  15145. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  15146. \section{The \LangLam{} Language}
  15147. \label{sec:r5}
  15148. The definitions of the concrete syntax and abstract syntax for
  15149. \LangLam{}, a language with anonymous functions and lexical scoping,
  15150. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15151. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15152. for \LangFun{}, which already has syntax for function application.
  15153. %
  15154. \python{The syntax also includes an assignment statement that includes
  15155. a type annotation for the variable on the left-hand side, which
  15156. facilitates the type checking of \code{lambda} expressions that we
  15157. discuss later in this section.}
  15158. %
  15159. \racket{The \code{procedure-arity} operation returns the number of parameters
  15160. of a given function, an operation that we need for the translation
  15161. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  15162. %
  15163. \python{The \code{arity} operation returns the number of parameters of
  15164. a given function, an operation that we need for the translation
  15165. of dynamic typing in chapter~\ref{ch:Ldyn}.
  15166. The \code{arity} operation is not in Python, but the same functionality
  15167. is available in a more complex form. We include \code{arity} in the
  15168. \LangLam{} source language to enable testing.}
  15169. \newcommand{\LlambdaGrammarRacket}{
  15170. \begin{array}{lcl}
  15171. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15172. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15173. \end{array}
  15174. }
  15175. \newcommand{\LlambdaASTRacket}{
  15176. \begin{array}{lcl}
  15177. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15178. \itm{op} &::=& \code{procedure-arity}
  15179. \end{array}
  15180. }
  15181. \newcommand{\LlambdaGrammarPython}{
  15182. \begin{array}{lcl}
  15183. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15184. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15185. \end{array}
  15186. }
  15187. \newcommand{\LlambdaASTPython}{
  15188. \begin{array}{lcl}
  15189. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15190. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15191. \end{array}
  15192. }
  15193. % include AnnAssign in ASTPython
  15194. \begin{figure}[tp]
  15195. \centering
  15196. \begin{tcolorbox}[colback=white]
  15197. \small
  15198. {\if\edition\racketEd
  15199. \[
  15200. \begin{array}{l}
  15201. \gray{\LintGrammarRacket{}} \\ \hline
  15202. \gray{\LvarGrammarRacket{}} \\ \hline
  15203. \gray{\LifGrammarRacket{}} \\ \hline
  15204. \gray{\LwhileGrammarRacket} \\ \hline
  15205. \gray{\LtupGrammarRacket} \\ \hline
  15206. \gray{\LfunGrammarRacket} \\ \hline
  15207. \LlambdaGrammarRacket \\
  15208. \begin{array}{lcl}
  15209. \LangLamM{} &::=& \Def\ldots \; \Exp
  15210. \end{array}
  15211. \end{array}
  15212. \]
  15213. \fi}
  15214. {\if\edition\pythonEd
  15215. \[
  15216. \begin{array}{l}
  15217. \gray{\LintGrammarPython{}} \\ \hline
  15218. \gray{\LvarGrammarPython{}} \\ \hline
  15219. \gray{\LifGrammarPython{}} \\ \hline
  15220. \gray{\LwhileGrammarPython} \\ \hline
  15221. \gray{\LtupGrammarPython} \\ \hline
  15222. \gray{\LfunGrammarPython} \\ \hline
  15223. \LlambdaGrammarPython \\
  15224. \begin{array}{lcl}
  15225. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15226. \end{array}
  15227. \end{array}
  15228. \]
  15229. \fi}
  15230. \end{tcolorbox}
  15231. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15232. with \key{lambda}.}
  15233. \label{fig:Llam-concrete-syntax}
  15234. \end{figure}
  15235. \begin{figure}[tp]
  15236. \centering
  15237. \begin{tcolorbox}[colback=white]
  15238. \small
  15239. {\if\edition\racketEd
  15240. \[\arraycolsep=3pt
  15241. \begin{array}{l}
  15242. \gray{\LintOpAST} \\ \hline
  15243. \gray{\LvarASTRacket{}} \\ \hline
  15244. \gray{\LifASTRacket{}} \\ \hline
  15245. \gray{\LwhileASTRacket{}} \\ \hline
  15246. \gray{\LtupASTRacket{}} \\ \hline
  15247. \gray{\LfunASTRacket} \\ \hline
  15248. \LlambdaASTRacket \\
  15249. \begin{array}{lcl}
  15250. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15251. \end{array}
  15252. \end{array}
  15253. \]
  15254. \fi}
  15255. {\if\edition\pythonEd
  15256. \[
  15257. \begin{array}{l}
  15258. \gray{\LintASTPython} \\ \hline
  15259. \gray{\LvarASTPython{}} \\ \hline
  15260. \gray{\LifASTPython{}} \\ \hline
  15261. \gray{\LwhileASTPython{}} \\ \hline
  15262. \gray{\LtupASTPython{}} \\ \hline
  15263. \gray{\LfunASTPython} \\ \hline
  15264. \LlambdaASTPython \\
  15265. \begin{array}{lcl}
  15266. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15267. \end{array}
  15268. \end{array}
  15269. \]
  15270. \fi}
  15271. \end{tcolorbox}
  15272. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15273. \label{fig:Llam-syntax}
  15274. \end{figure}
  15275. \index{subject}{interpreter}
  15276. \label{sec:interp-Llambda}
  15277. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  15278. \LangLam{}. The case for \key{Lambda} saves the current environment
  15279. inside the returned function value. Recall that during function
  15280. application, the environment stored in the function value, extended
  15281. with the mapping of parameters to argument values, is used to
  15282. interpret the body of the function.
  15283. \begin{figure}[tbp]
  15284. \begin{tcolorbox}[colback=white]
  15285. {\if\edition\racketEd
  15286. \begin{lstlisting}
  15287. (define interp-Llambda-class
  15288. (class interp-Lfun-class
  15289. (super-new)
  15290. (define/override (interp-op op)
  15291. (match op
  15292. ['procedure-arity
  15293. (lambda (v)
  15294. (match v
  15295. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15296. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15297. [else (super interp-op op)]))
  15298. (define/override ((interp-exp env) e)
  15299. (define recur (interp-exp env))
  15300. (match e
  15301. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15302. `(function ,xs ,body ,env)]
  15303. [else ((super interp-exp env) e)]))
  15304. ))
  15305. (define (interp-Llambda p)
  15306. (send (new interp-Llambda-class) interp-program p))
  15307. \end{lstlisting}
  15308. \fi}
  15309. {\if\edition\pythonEd
  15310. \begin{lstlisting}
  15311. class InterpLlambda(InterpLfun):
  15312. def arity(self, v):
  15313. match v:
  15314. case Function(name, params, body, env):
  15315. return len(params)
  15316. case _:
  15317. raise Exception('Llambda arity unexpected ' + repr(v))
  15318. def interp_exp(self, e, env):
  15319. match e:
  15320. case Call(Name('arity'), [fun]):
  15321. f = self.interp_exp(fun, env)
  15322. return self.arity(f)
  15323. case Lambda(params, body):
  15324. return Function('lambda', params, [Return(body)], env)
  15325. case _:
  15326. return super().interp_exp(e, env)
  15327. def interp_stmts(self, ss, env):
  15328. if len(ss) == 0:
  15329. return
  15330. match ss[0]:
  15331. case AnnAssign(lhs, typ, value, simple):
  15332. env[lhs.id] = self.interp_exp(value, env)
  15333. return self.interp_stmts(ss[1:], env)
  15334. case _:
  15335. return super().interp_stmts(ss, env)
  15336. \end{lstlisting}
  15337. \fi}
  15338. \end{tcolorbox}
  15339. \caption{Interpreter for \LangLam{}.}
  15340. \label{fig:interp-Llambda}
  15341. \end{figure}
  15342. \label{sec:type-check-r5}
  15343. \index{subject}{type checking}
  15344. {\if\edition\racketEd
  15345. %
  15346. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15347. \key{lambda} form. The body of the \key{lambda} is checked in an
  15348. environment that includes the current environment (because it is
  15349. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15350. require the body's type to match the declared return type.
  15351. %
  15352. \fi}
  15353. {\if\edition\pythonEd
  15354. %
  15355. Figures~\ref{fig:type-check-Llambda} and
  15356. \ref{fig:type-check-Llambda-part2} define the type checker for
  15357. \LangLam{}, which is more complex than one might expect. The reason
  15358. for the added complexity is that the syntax of \key{lambda} does not
  15359. include type annotations for the parameters or return type. Instead
  15360. they must be inferred. There are many approaches of type inference to
  15361. choose from of varying degrees of complexity. We choose one of the
  15362. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  15363. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  15364. this book is compilation, not type inference.
  15365. The main idea of bidirectional type inference is to add an auxiliary
  15366. function, here named \code{check\_exp}, that takes an expected type
  15367. and checks whether the given expression is of that type. Thus, in
  15368. \code{check\_exp}, type information flows in a top-down manner with
  15369. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15370. function, where type information flows in a primarily bottom-up
  15371. manner.
  15372. %
  15373. The idea then is to use \code{check\_exp} in all the places where we
  15374. already know what the type of an expression should be, such as in the
  15375. \code{return} statement of a top-level function definition, or on the
  15376. right-hand side of an annotated assignment statement.
  15377. Getting back to \code{lambda}, it is straightforward to check a
  15378. \code{lambda} inside \code{check\_exp} because the expected type
  15379. provides the parameter types and the return type. On the other hand,
  15380. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15381. that we do not allow \code{lambda} in contexts where we don't already
  15382. know its type. This restriction does not incur a loss of
  15383. expressiveness for \LangLam{} because it is straightforward to modify
  15384. a program to sidestep the restriction, for example, by using an
  15385. annotated assignment statement to assign the \code{lambda} to a
  15386. temporary variable.
  15387. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15388. checker records their type in a \code{has\_type} field. This type
  15389. information is used later in this chapter.
  15390. %
  15391. \fi}
  15392. \begin{figure}[tbp]
  15393. \begin{tcolorbox}[colback=white]
  15394. {\if\edition\racketEd
  15395. \begin{lstlisting}
  15396. (define (type-check-Llambda env)
  15397. (lambda (e)
  15398. (match e
  15399. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15400. (define-values (new-body bodyT)
  15401. ((type-check-exp (append (map cons xs Ts) env)) body))
  15402. (define ty `(,@Ts -> ,rT))
  15403. (cond
  15404. [(equal? rT bodyT)
  15405. (values (HasType (Lambda params rT new-body) ty) ty)]
  15406. [else
  15407. (error "mismatch in return type" bodyT rT)])]
  15408. ...
  15409. )))
  15410. \end{lstlisting}
  15411. \fi}
  15412. {\if\edition\pythonEd
  15413. \begin{lstlisting}
  15414. class TypeCheckLlambda(TypeCheckLfun):
  15415. def type_check_exp(self, e, env):
  15416. match e:
  15417. case Name(id):
  15418. e.has_type = env[id]
  15419. return env[id]
  15420. case Lambda(params, body):
  15421. raise Exception('cannot synthesize a type for a lambda')
  15422. case Call(Name('arity'), [func]):
  15423. func_t = self.type_check_exp(func, env)
  15424. match func_t:
  15425. case FunctionType(params_t, return_t):
  15426. return IntType()
  15427. case _:
  15428. raise Exception('in arity, unexpected ' + repr(func_t))
  15429. case _:
  15430. return super().type_check_exp(e, env)
  15431. def check_exp(self, e, ty, env):
  15432. match e:
  15433. case Lambda(params, body):
  15434. e.has_type = ty
  15435. match ty:
  15436. case FunctionType(params_t, return_t):
  15437. new_env = env.copy().update(zip(params, params_t))
  15438. self.check_exp(body, return_t, new_env)
  15439. case _:
  15440. raise Exception('lambda does not have type ' + str(ty))
  15441. case Call(func, args):
  15442. func_t = self.type_check_exp(func, env)
  15443. match func_t:
  15444. case FunctionType(params_t, return_t):
  15445. for (arg, param_t) in zip(args, params_t):
  15446. self.check_exp(arg, param_t, env)
  15447. self.check_type_equal(return_t, ty, e)
  15448. case _:
  15449. raise Exception('type_check_exp: in call, unexpected ' + \
  15450. repr(func_t))
  15451. case _:
  15452. t = self.type_check_exp(e, env)
  15453. self.check_type_equal(t, ty, e)
  15454. \end{lstlisting}
  15455. \fi}
  15456. \end{tcolorbox}
  15457. \caption{Type checking \LangLam{}\python{, part 1}.}
  15458. \label{fig:type-check-Llambda}
  15459. \end{figure}
  15460. {\if\edition\pythonEd
  15461. \begin{figure}[tbp]
  15462. \begin{tcolorbox}[colback=white]
  15463. \begin{lstlisting}
  15464. def check_stmts(self, ss, return_ty, env):
  15465. if len(ss) == 0:
  15466. return
  15467. match ss[0]:
  15468. case FunctionDef(name, params, body, dl, returns, comment):
  15469. new_env = env.copy().update(params)
  15470. rt = self.check_stmts(body, returns, new_env)
  15471. self.check_stmts(ss[1:], return_ty, env)
  15472. case Return(value):
  15473. self.check_exp(value, return_ty, env)
  15474. case Assign([Name(id)], value):
  15475. if id in env:
  15476. self.check_exp(value, env[id], env)
  15477. else:
  15478. env[id] = self.type_check_exp(value, env)
  15479. self.check_stmts(ss[1:], return_ty, env)
  15480. case Assign([Subscript(tup, Constant(index), Store())], value):
  15481. tup_t = self.type_check_exp(tup, env)
  15482. match tup_t:
  15483. case TupleType(ts):
  15484. self.check_exp(value, ts[index], env)
  15485. case _:
  15486. raise Exception('expected a tuple, not ' + repr(tup_t))
  15487. self.check_stmts(ss[1:], return_ty, env)
  15488. case AnnAssign(Name(id), ty_annot, value, simple):
  15489. ss[0].annotation = ty_annot
  15490. if id in env:
  15491. self.check_type_equal(env[id], ty_annot)
  15492. else:
  15493. env[id] = ty_annot
  15494. self.check_exp(value, ty_annot, env)
  15495. self.check_stmts(ss[1:], return_ty, env)
  15496. case _:
  15497. self.type_check_stmts(ss, env)
  15498. def type_check(self, p):
  15499. match p:
  15500. case Module(body):
  15501. env = {}
  15502. for s in body:
  15503. match s:
  15504. case FunctionDef(name, params, bod, dl, returns, comment):
  15505. params_t = [t for (x,t) in params]
  15506. env[name] = FunctionType(params_t, returns)
  15507. self.check_stmts(body, int, env)
  15508. \end{lstlisting}
  15509. \end{tcolorbox}
  15510. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15511. \label{fig:type-check-Llambda-part2}
  15512. \end{figure}
  15513. \fi}
  15514. \clearpage
  15515. \section{Assignment and Lexically Scoped Functions}
  15516. \label{sec:assignment-scoping}
  15517. The combination of lexically scoped functions and assignment to
  15518. variables raises a challenge with the flat-closure approach to
  15519. implementing lexically scoped functions. Consider the following
  15520. example in which function \code{f} has a free variable \code{x} that
  15521. is changed after \code{f} is created but before the call to \code{f}.
  15522. % loop_test_11.rkt
  15523. {\if\edition\racketEd
  15524. \begin{lstlisting}
  15525. (let ([x 0])
  15526. (let ([y 0])
  15527. (let ([z 20])
  15528. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15529. (begin
  15530. (set! x 10)
  15531. (set! y 12)
  15532. (f y))))))
  15533. \end{lstlisting}
  15534. \fi}
  15535. {\if\edition\pythonEd
  15536. % box_free_assign.py
  15537. \begin{lstlisting}
  15538. def g(z : int) -> int:
  15539. x = 0
  15540. y = 0
  15541. f : Callable[[int],int] = lambda a: a + x + z
  15542. x = 10
  15543. y = 12
  15544. return f(y)
  15545. print( g(20) )
  15546. \end{lstlisting}
  15547. \fi} The correct output for this example is \code{42} because the call
  15548. to \code{f} is required to use the current value of \code{x} (which is
  15549. \code{10}). Unfortunately, the closure conversion pass
  15550. (section~\ref{sec:closure-conversion}) generates code for the
  15551. \code{lambda} that copies the old value of \code{x} into a
  15552. closure. Thus, if we naively applied closure conversion, the output of
  15553. this program would be \code{32}.
  15554. A first attempt at solving this problem would be to save a pointer to
  15555. \code{x} in the closure and change the occurrences of \code{x} inside
  15556. the lambda to dereference the pointer. Of course, this would require
  15557. assigning \code{x} to the stack and not to a register. However, the
  15558. problem goes a bit deeper.
  15559. Consider the following example that returns a function that refers to
  15560. a local variable of the enclosing function:
  15561. \begin{center}
  15562. \begin{minipage}{\textwidth}
  15563. {\if\edition\racketEd
  15564. \begin{lstlisting}
  15565. (define (f []) : Integer
  15566. (let ([x 0])
  15567. (let ([g (lambda: () : Integer x)])
  15568. (begin
  15569. (set! x 42)
  15570. g))))
  15571. ((f))
  15572. \end{lstlisting}
  15573. \fi}
  15574. {\if\edition\pythonEd
  15575. % counter.py
  15576. \begin{lstlisting}
  15577. def f():
  15578. x = 0
  15579. g = lambda: x
  15580. x = 42
  15581. return g
  15582. print( f()() )
  15583. \end{lstlisting}
  15584. \fi}
  15585. \end{minipage}
  15586. \end{center}
  15587. In this example, the lifetime of \code{x} extends beyond the lifetime
  15588. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15589. stack frame for the call to \code{f}, it would be gone by the time we
  15590. called \code{g}, leaving us with dangling pointers for
  15591. \code{x}. This example demonstrates that when a variable occurs free
  15592. inside a function, its lifetime becomes indefinite. Thus, the value of
  15593. the variable needs to live on the heap. The verb
  15594. \emph{box}\index{subject}{box} is often used for allocating a single
  15595. value on the heap, producing a pointer, and
  15596. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15597. %
  15598. We introduce a new pass named \code{convert\_assignments} to address
  15599. this challenge.
  15600. %
  15601. \python{But before diving into that, we have one more
  15602. problem to discuss.}
  15603. \if\edition\pythonEd
  15604. \section{Uniquify Variables}
  15605. \label{sec:uniquify-lambda}
  15606. With the addition of \code{lambda} we have a complication to deal
  15607. with: name shadowing. Consider the following program with a function
  15608. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15609. \code{lambda} expressions. The first \code{lambda} has a parameter
  15610. that is also named \code{x}.
  15611. \begin{lstlisting}
  15612. def f(x:int, y:int) -> Callable[[int], int]:
  15613. g : Callable[[int],int] = (lambda x: x + y)
  15614. h : Callable[[int],int] = (lambda y: x + y)
  15615. x = input_int()
  15616. return g
  15617. print(f(0, 10)(32))
  15618. \end{lstlisting}
  15619. Many of our compiler passes rely on being able to connect variable
  15620. uses with their definitions using just the name of the variable,
  15621. including new passes in this chapter. However, in the above example
  15622. the name of the variable does not uniquely determine its
  15623. definition. To solve this problem we recommend implementing a pass
  15624. named \code{uniquify} that renames every variable in the program to
  15625. make sure they are all unique.
  15626. The following shows the result of \code{uniquify} for the above
  15627. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  15628. and the \code{x} parameter of the \code{lambda} is renamed to
  15629. \code{x\_4}.
  15630. \begin{lstlisting}
  15631. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15632. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15633. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15634. x_0 = input_int()
  15635. return g_2
  15636. def main() -> int :
  15637. print(f(0, 10)(32))
  15638. return 0
  15639. \end{lstlisting}
  15640. \fi
  15641. %% \section{Reveal Functions}
  15642. %% \label{sec:reveal-functions-r5}
  15643. %% \racket{To support the \code{procedure-arity} operator we need to
  15644. %% communicate the arity of a function to the point of closure
  15645. %% creation.}
  15646. %% %
  15647. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15648. %% function at runtime. Thus, we need to communicate the arity of a
  15649. %% function to the point of closure creation.}
  15650. %% %
  15651. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15652. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15653. %% \[
  15654. %% \begin{array}{lcl}
  15655. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15656. %% \end{array}
  15657. %% \]
  15658. \section{Assignment Conversion}
  15659. \label{sec:convert-assignments}
  15660. The purpose of the \code{convert\_assignments} pass is to address the
  15661. challenge regarding the interaction between variable assignments and
  15662. closure conversion. First we identify which variables need to be
  15663. boxed, and then we transform the program to box those variables. In
  15664. general, boxing introduces runtime overhead that we would like to
  15665. avoid, so we should box as few variables as possible. We recommend
  15666. boxing the variables in the intersection of the following two sets of
  15667. variables:
  15668. \begin{enumerate}
  15669. \item The variables that are free in a \code{lambda}.
  15670. \item The variables that appear on the left-hand side of an
  15671. assignment.
  15672. \end{enumerate}
  15673. The first condition is a must but the second condition is
  15674. conservative. It is possible to develop a more liberal condition using
  15675. static program analysis.
  15676. Consider again the first example from
  15677. section~\ref{sec:assignment-scoping}:
  15678. %
  15679. {\if\edition\racketEd
  15680. \begin{lstlisting}
  15681. (let ([x 0])
  15682. (let ([y 0])
  15683. (let ([z 20])
  15684. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15685. (begin
  15686. (set! x 10)
  15687. (set! y 12)
  15688. (f y))))))
  15689. \end{lstlisting}
  15690. \fi}
  15691. {\if\edition\pythonEd
  15692. \begin{lstlisting}
  15693. def g(z : int) -> int:
  15694. x = 0
  15695. y = 0
  15696. f : Callable[[int],int] = lambda a: a + x + z
  15697. x = 10
  15698. y = 12
  15699. return f(y)
  15700. print( g(20) )
  15701. \end{lstlisting}
  15702. \fi}
  15703. %
  15704. \noindent The variables \code{x} and \code{y} are assigned to. The
  15705. variables \code{x} and \code{z} occur free inside the
  15706. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  15707. \code{y} or \code{z}. The boxing of \code{x} consists of three
  15708. transformations: initialize \code{x} with a tuple whose elements are
  15709. uninitialized, replace reads from \code{x} with tuple reads, and
  15710. replace each assignment to \code{x} with a tuple write. The output of
  15711. \code{convert\_assignments} for this example is as follows:
  15712. %
  15713. {\if\edition\racketEd
  15714. \begin{lstlisting}
  15715. (define (main) : Integer
  15716. (let ([x0 (vector 0)])
  15717. (let ([y1 0])
  15718. (let ([z2 20])
  15719. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15720. (+ a3 (+ (vector-ref x0 0) z2)))])
  15721. (begin
  15722. (vector-set! x0 0 10)
  15723. (set! y1 12)
  15724. (f4 y1)))))))
  15725. \end{lstlisting}
  15726. \fi}
  15727. %
  15728. {\if\edition\pythonEd
  15729. \begin{lstlisting}
  15730. def g(z : int)-> int:
  15731. x = (uninitialized(int),)
  15732. x[0] = 0
  15733. y = 0
  15734. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15735. x[0] = 10
  15736. y = 12
  15737. return f(y)
  15738. def main() -> int:
  15739. print(g(20))
  15740. return 0
  15741. \end{lstlisting}
  15742. \fi}
  15743. To compute the free variables of all the \code{lambda} expressions, we
  15744. recommend defining the following two auxiliary functions:
  15745. \begin{enumerate}
  15746. \item \code{free\_variables} computes the free variables of an expression, and
  15747. \item \code{free\_in\_lambda} collects all the variables that are
  15748. free in any of the \code{lambda} expressions, using
  15749. \code{free\_variables} in the case for each \code{lambda}.
  15750. \end{enumerate}
  15751. {\if\edition\racketEd
  15752. %
  15753. To compute the variables that are assigned to, we recommend updating
  15754. the \code{collect-set!} function that we introduced in
  15755. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15756. as \code{Lambda}.
  15757. %
  15758. \fi}
  15759. {\if\edition\pythonEd
  15760. %
  15761. To compute the variables that are assigned to, we recommend defining
  15762. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15763. the set of variables that occur in the left-hand side of an assignment
  15764. statement, and otherwise returns the empty set.
  15765. %
  15766. \fi}
  15767. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15768. free in a \code{lambda} and that are assigned to in the enclosing
  15769. function definition.
  15770. Next we discuss the \code{convert\_assignments} pass. In the case for
  15771. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15772. $\VAR{x}$ to a tuple read.
  15773. %
  15774. {\if\edition\racketEd
  15775. \begin{lstlisting}
  15776. (Var |$x$|)
  15777. |$\Rightarrow$|
  15778. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15779. \end{lstlisting}
  15780. \fi}
  15781. %
  15782. {\if\edition\pythonEd
  15783. \begin{lstlisting}
  15784. Name(|$x$|)
  15785. |$\Rightarrow$|
  15786. Subscript(Name(|$x$|), Constant(0), Load())
  15787. \end{lstlisting}
  15788. \fi}
  15789. %
  15790. \noindent In the case for assignment, recursively process the
  15791. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15792. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15793. as follows:
  15794. %
  15795. {\if\edition\racketEd
  15796. \begin{lstlisting}
  15797. (SetBang |$x$| |$\itm{rhs}$|)
  15798. |$\Rightarrow$|
  15799. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15800. \end{lstlisting}
  15801. \fi}
  15802. {\if\edition\pythonEd
  15803. \begin{lstlisting}
  15804. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15805. |$\Rightarrow$|
  15806. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15807. \end{lstlisting}
  15808. \fi}
  15809. %
  15810. {\if\edition\racketEd
  15811. The case for \code{Lambda} is nontrivial, but it is similar to the
  15812. case for function definitions, which we discuss next.
  15813. \fi}
  15814. %
  15815. To translate a function definition, we first compute $\mathit{AF}$,
  15816. the intersection of the variables that are free in a \code{lambda} and
  15817. that are assigned to. We then apply assignment conversion to the body
  15818. of the function definition. Finally, we box the parameters of this
  15819. function definition that are in $\mathit{AF}$. For example,
  15820. the parameter \code{x} of the following function \code{g}
  15821. needs to be boxed:
  15822. {\if\edition\racketEd
  15823. \begin{lstlisting}
  15824. (define (g [x : Integer]) : Integer
  15825. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15826. (begin
  15827. (set! x 10)
  15828. (f 32))))
  15829. \end{lstlisting}
  15830. \fi}
  15831. %
  15832. {\if\edition\pythonEd
  15833. \begin{lstlisting}
  15834. def g(x : int) -> int:
  15835. f : Callable[[int],int] = lambda a: a + x
  15836. x = 10
  15837. return f(32)
  15838. \end{lstlisting}
  15839. \fi}
  15840. %
  15841. \noindent We box parameter \code{x} by creating a local variable named
  15842. \code{x} that is initialized to a tuple whose contents is the value of
  15843. the parameter, which has been renamed to \code{x\_0}.
  15844. %
  15845. {\if\edition\racketEd
  15846. \begin{lstlisting}
  15847. (define (g [x_0 : Integer]) : Integer
  15848. (let ([x (vector x_0)])
  15849. (let ([f (lambda: ([a : Integer]) : Integer
  15850. (+ a (vector-ref x 0)))])
  15851. (begin
  15852. (vector-set! x 0 10)
  15853. (f 32)))))
  15854. \end{lstlisting}
  15855. \fi}
  15856. %
  15857. {\if\edition\pythonEd
  15858. \begin{lstlisting}
  15859. def g(x_0 : int)-> int:
  15860. x = (x_0,)
  15861. f : Callable[[int], int] = (lambda a: a + x[0])
  15862. x[0] = 10
  15863. return f(32)
  15864. \end{lstlisting}
  15865. \fi}
  15866. \section{Closure Conversion}
  15867. \label{sec:closure-conversion}
  15868. \index{subject}{closure conversion}
  15869. The compiling of lexically scoped functions into top-level function
  15870. definitions and flat closures is accomplished in the pass
  15871. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15872. and before \code{limit\_functions}.
  15873. As usual, we implement the pass as a recursive function over the
  15874. AST. The interesting cases are for \key{lambda} and function
  15875. application. We transform a \key{lambda} expression into an expression
  15876. that creates a closure, that is, a tuple for which the first element
  15877. is a function pointer and the rest of the elements are the values of
  15878. the free variables of the \key{lambda}.
  15879. %
  15880. However, we use the \code{Closure} AST node instead of using a tuple
  15881. so that we can record the arity.
  15882. %
  15883. In the generated code that follows, \itm{fvs} is the free variables of
  15884. the lambda and \itm{name} is a unique symbol generated to identify the
  15885. lambda.
  15886. %
  15887. \racket{The \itm{arity} is the number of parameters (the length of
  15888. \itm{ps}).}
  15889. %
  15890. {\if\edition\racketEd
  15891. \begin{lstlisting}
  15892. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15893. |$\Rightarrow$|
  15894. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15895. \end{lstlisting}
  15896. \fi}
  15897. %
  15898. {\if\edition\pythonEd
  15899. \begin{lstlisting}
  15900. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15901. |$\Rightarrow$|
  15902. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15903. \end{lstlisting}
  15904. \fi}
  15905. %
  15906. In addition to transforming each \key{Lambda} AST node into a
  15907. tuple, we create a top-level function definition for each
  15908. \key{Lambda}, as shown next.\\
  15909. \begin{minipage}{0.8\textwidth}
  15910. {\if\edition\racketEd
  15911. \begin{lstlisting}
  15912. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15913. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15914. ...
  15915. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15916. |\itm{body'}|)...))
  15917. \end{lstlisting}
  15918. \fi}
  15919. {\if\edition\pythonEd
  15920. \begin{lstlisting}
  15921. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15922. |$\itm{fvs}_1$| = clos[1]
  15923. |$\ldots$|
  15924. |$\itm{fvs}_n$| = clos[|$n$|]
  15925. |\itm{body'}|
  15926. \end{lstlisting}
  15927. \fi}
  15928. \end{minipage}\\
  15929. The \code{clos} parameter refers to the closure. Translate the type
  15930. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15931. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15932. \itm{closTy} is a tuple type for which the first element type is
  15933. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15934. the element types are the types of the free variables in the
  15935. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15936. is nontrivial to give a type to the function in the closure's type.%
  15937. %
  15938. \footnote{To give an accurate type to a closure, we would need to add
  15939. existential types to the type checker~\citep{Minamide:1996ys}.}
  15940. %
  15941. %% The dummy type is considered to be equal to any other type during type
  15942. %% checking.
  15943. The free variables become local variables that are initialized with
  15944. their values in the closure.
  15945. Closure conversion turns every function into a tuple, so the type
  15946. annotations in the program must also be translated. We recommend
  15947. defining an auxiliary recursive function for this purpose. Function
  15948. types should be translated as follows:
  15949. %
  15950. {\if\edition\racketEd
  15951. \begin{lstlisting}
  15952. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15953. |$\Rightarrow$|
  15954. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15955. \end{lstlisting}
  15956. \fi}
  15957. {\if\edition\pythonEd
  15958. \begin{lstlisting}
  15959. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15960. |$\Rightarrow$|
  15961. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15962. \end{lstlisting}
  15963. \fi}
  15964. %
  15965. This type indicates that the first thing in the tuple is a
  15966. function. The first parameter of the function is a tuple (a closure)
  15967. and the rest of the parameters are the ones from the original
  15968. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15969. omits the types of the free variables because (1) those types are not
  15970. available in this context, and (2) we do not need them in the code that
  15971. is generated for function application. So this type describes only the
  15972. first component of the closure tuple. At runtime the tuple may have
  15973. more components, but we ignore them at this point.
  15974. We transform function application into code that retrieves the
  15975. function from the closure and then calls the function, passing the
  15976. closure as the first argument. We place $e'$ in a temporary variable
  15977. to avoid code duplication.
  15978. \begin{center}
  15979. \begin{minipage}{\textwidth}
  15980. {\if\edition\racketEd
  15981. \begin{lstlisting}
  15982. (Apply |$e$| |$\itm{es}$|)
  15983. |$\Rightarrow$|
  15984. (Let |$\itm{tmp}$| |$e'$|
  15985. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15986. \end{lstlisting}
  15987. \fi}
  15988. %
  15989. {\if\edition\pythonEd
  15990. \begin{lstlisting}
  15991. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15992. |$\Rightarrow$|
  15993. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15994. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15995. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15996. \end{lstlisting}
  15997. \fi}
  15998. \end{minipage}
  15999. \end{center}
  16000. There is also the question of what to do with references to top-level
  16001. function definitions. To maintain a uniform translation of function
  16002. application, we turn function references into closures.
  16003. \begin{tabular}{lll}
  16004. \begin{minipage}{0.3\textwidth}
  16005. {\if\edition\racketEd
  16006. \begin{lstlisting}
  16007. (FunRef |$f$| |$n$|)
  16008. \end{lstlisting}
  16009. \fi}
  16010. {\if\edition\pythonEd
  16011. \begin{lstlisting}
  16012. FunRef(|$f$|, |$n$|)
  16013. \end{lstlisting}
  16014. \fi}
  16015. \end{minipage}
  16016. &
  16017. $\Rightarrow$
  16018. &
  16019. \begin{minipage}{0.5\textwidth}
  16020. {\if\edition\racketEd
  16021. \begin{lstlisting}
  16022. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16023. \end{lstlisting}
  16024. \fi}
  16025. {\if\edition\pythonEd
  16026. \begin{lstlisting}
  16027. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16028. \end{lstlisting}
  16029. \fi}
  16030. \end{minipage}
  16031. \end{tabular} \\
  16032. We no longer need the annotated assignment statement \code{AnnAssign}
  16033. to support the type checking of \code{lambda} expressions, so we
  16034. translate it to a regular \code{Assign} statement.
  16035. The top-level function definitions need to be updated to take an extra
  16036. closure parameter, but that parameter is ignored in the body of those
  16037. functions.
  16038. \section{An Example Translation}
  16039. \label{sec:example-lambda}
  16040. Figure~\ref{fig:lexical-functions-example} shows the result of
  16041. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16042. program demonstrating lexical scoping that we discussed at the
  16043. beginning of this chapter.
  16044. \begin{figure}[tbp]
  16045. \begin{tcolorbox}[colback=white]
  16046. \begin{minipage}{0.8\textwidth}
  16047. {\if\edition\racketEd
  16048. % tests/lambda_test_6.rkt
  16049. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16050. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16051. (let ([y8 4])
  16052. (lambda: ([z9 : Integer]) : Integer
  16053. (+ x7 (+ y8 z9)))))
  16054. (define (main) : Integer
  16055. (let ([g0 ((fun-ref f6 1) 5)])
  16056. (let ([h1 ((fun-ref f6 1) 3)])
  16057. (+ (g0 11) (h1 15)))))
  16058. \end{lstlisting}
  16059. $\Rightarrow$
  16060. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16061. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16062. (let ([y8 4])
  16063. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16064. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16065. (let ([x7 (vector-ref fvs3 1)])
  16066. (let ([y8 (vector-ref fvs3 2)])
  16067. (+ x7 (+ y8 z9)))))
  16068. (define (main) : Integer
  16069. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16070. ((vector-ref clos5 0) clos5 5))])
  16071. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16072. ((vector-ref clos6 0) clos6 3))])
  16073. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16074. \end{lstlisting}
  16075. \fi}
  16076. %
  16077. {\if\edition\pythonEd
  16078. % free_var.py
  16079. \begin{lstlisting}
  16080. def f(x : int) -> Callable[[int], int]:
  16081. y = 4
  16082. return lambda z: x + y + z
  16083. g = f(5)
  16084. h = f(3)
  16085. print( g(11) + h(15) )
  16086. \end{lstlisting}
  16087. $\Rightarrow$
  16088. \begin{lstlisting}
  16089. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  16090. x = fvs_1[1]
  16091. y = fvs_1[2]
  16092. return x + y[0] + z
  16093. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  16094. y = (777,)
  16095. y[0] = 4
  16096. return (lambda_0, x, y)
  16097. def main() -> int:
  16098. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  16099. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  16100. print((let clos_5 = g in clos_5[0](clos_5, 11))
  16101. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  16102. return 0
  16103. \end{lstlisting}
  16104. \fi}
  16105. \end{minipage}
  16106. \end{tcolorbox}
  16107. \caption{Example of closure conversion.}
  16108. \label{fig:lexical-functions-example}
  16109. \end{figure}
  16110. \begin{exercise}\normalfont\normalsize
  16111. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16112. Create five new programs that use \key{lambda} functions and make use of
  16113. lexical scoping. Test your compiler on these new programs and all
  16114. your previously created test programs.
  16115. \end{exercise}
  16116. \section{Expose Allocation}
  16117. \label{sec:expose-allocation-r5}
  16118. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16119. that allocates and initializes a tuple, similar to the translation of
  16120. the tuple creation in section~\ref{sec:expose-allocation}.
  16121. The only difference is replacing the use of
  16122. \ALLOC{\itm{len}}{\itm{type}} with
  16123. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16124. \section{Explicate Control and \LangCLam{}}
  16125. \label{sec:explicate-r5}
  16126. The output language of \code{explicate\_control} is \LangCLam{}; the
  16127. definition of its abstract syntax is shown in
  16128. figure~\ref{fig:Clam-syntax}.
  16129. %
  16130. \racket{The only differences with respect to \LangCFun{} are the
  16131. addition of the \code{AllocateClosure} form to the grammar for
  16132. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16133. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16134. similar to the handling of other expressions such as primitive
  16135. operators.}
  16136. %
  16137. \python{The differences with respect to \LangCFun{} are the
  16138. additions of \code{Uninitialized}, \code{AllocateClosure},
  16139. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16140. \code{explicate\_control} pass is similar to the handling of other
  16141. expressions such as primitive operators.}
  16142. \newcommand{\ClambdaASTRacket}{
  16143. \begin{array}{lcl}
  16144. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16145. \itm{op} &::= & \code{procedure-arity}
  16146. \end{array}
  16147. }
  16148. \newcommand{\ClambdaASTPython}{
  16149. \begin{array}{lcl}
  16150. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16151. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16152. &\MID& \ARITY{\Atm}
  16153. \end{array}
  16154. }
  16155. \begin{figure}[tp]
  16156. \begin{tcolorbox}[colback=white]
  16157. \small
  16158. {\if\edition\racketEd
  16159. \[
  16160. \begin{array}{l}
  16161. \gray{\CvarASTRacket} \\ \hline
  16162. \gray{\CifASTRacket} \\ \hline
  16163. \gray{\CloopASTRacket} \\ \hline
  16164. \gray{\CtupASTRacket} \\ \hline
  16165. \gray{\CfunASTRacket} \\ \hline
  16166. \ClambdaASTRacket \\
  16167. \begin{array}{lcl}
  16168. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16169. \end{array}
  16170. \end{array}
  16171. \]
  16172. \fi}
  16173. {\if\edition\pythonEd
  16174. \[
  16175. \begin{array}{l}
  16176. \gray{\CifASTPython} \\ \hline
  16177. \gray{\CtupASTPython} \\ \hline
  16178. \gray{\CfunASTPython} \\ \hline
  16179. \ClambdaASTPython \\
  16180. \begin{array}{lcl}
  16181. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16182. \end{array}
  16183. \end{array}
  16184. \]
  16185. \fi}
  16186. \end{tcolorbox}
  16187. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16188. \label{fig:Clam-syntax}
  16189. \end{figure}
  16190. \section{Select Instructions}
  16191. \label{sec:select-instructions-Llambda}
  16192. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16193. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16194. (section~\ref{sec:select-instructions-gc}). The only difference is
  16195. that you should place the \itm{arity} in the tag that is stored at
  16196. position $0$ of the vector. Recall that in
  16197. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16198. was not used. We store the arity in the $5$ bits starting at position
  16199. $58$.
  16200. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16201. instructions that access the tag from position $0$ of the vector and
  16202. extract the $5$ bits starting at position $58$ from the tag.}
  16203. %
  16204. \python{Compile a call to the \code{arity} operator to a sequence of
  16205. instructions that access the tag from position $0$ of the tuple
  16206. (representing a closure) and extract the $5$-bits starting at position
  16207. $58$ from the tag.}
  16208. \begin{figure}[p]
  16209. \begin{tcolorbox}[colback=white]
  16210. {\if\edition\racketEd
  16211. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16212. \node (Lfun) at (0,2) {\large \LangLam{}};
  16213. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16214. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16215. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16216. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16217. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16218. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16219. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16220. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16221. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16222. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16223. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16224. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16225. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16226. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16227. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16228. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16229. \path[->,bend left=15] (Lfun) edge [above] node
  16230. {\ttfamily\footnotesize shrink} (Lfun-2);
  16231. \path[->,bend left=15] (Lfun-2) edge [above] node
  16232. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16233. \path[->,bend left=15] (Lfun-3) edge [above] node
  16234. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16235. \path[->,bend left=15] (F1-0) edge [left] node
  16236. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16237. \path[->,bend left=15] (F1-1) edge [below] node
  16238. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16239. \path[->,bend right=15] (F1-2) edge [above] node
  16240. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16241. \path[->,bend right=15] (F1-3) edge [above] node
  16242. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16243. \path[->,bend left=15] (F1-4) edge [right] node
  16244. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16245. \path[->,bend right=15] (F1-5) edge [below] node
  16246. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16247. \path[->,bend left=15] (F1-6) edge [above] node
  16248. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16249. \path[->] (C3-2) edge [right] node
  16250. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16251. \path[->,bend right=15] (x86-2) edge [right] node
  16252. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16253. \path[->,bend right=15] (x86-2-1) edge [below] node
  16254. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16255. \path[->,bend right=15] (x86-2-2) edge [right] node
  16256. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16257. \path[->,bend left=15] (x86-3) edge [above] node
  16258. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16259. \path[->,bend left=15] (x86-4) edge [right] node
  16260. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16261. \end{tikzpicture}
  16262. \fi}
  16263. {\if\edition\pythonEd
  16264. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16265. \node (Lfun) at (0,2) {\large \LangLam{}};
  16266. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16267. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16268. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16269. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16270. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16271. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16272. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16273. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16274. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16275. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16276. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16277. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16278. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16279. \path[->,bend left=15] (Lfun) edge [above] node
  16280. {\ttfamily\footnotesize shrink} (Lfun-2);
  16281. \path[->,bend left=15] (Lfun-2) edge [above] node
  16282. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16283. \path[->,bend left=15] (Lfun-3) edge [above] node
  16284. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16285. \path[->,bend left=15] (F1-0) edge [left] node
  16286. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16287. \path[->,bend left=15] (F1-1) edge [below] node
  16288. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16289. \path[->,bend left=15] (F1-2) edge [below] node
  16290. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16291. \path[->,bend right=15] (F1-3) edge [above] node
  16292. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16293. \path[->,bend right=15] (F1-5) edge [right] node
  16294. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16295. \path[->,bend left=15] (F1-6) edge [right] node
  16296. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16297. \path[->,bend right=15] (C3-2) edge [right] node
  16298. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16299. \path[->,bend right=15] (x86-2) edge [below] node
  16300. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16301. \path[->,bend right=15] (x86-3) edge [below] node
  16302. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16303. \path[->,bend left=15] (x86-4) edge [above] node
  16304. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16305. \end{tikzpicture}
  16306. \fi}
  16307. \end{tcolorbox}
  16308. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16309. functions.}
  16310. \label{fig:Llambda-passes}
  16311. \end{figure}
  16312. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16313. needed for the compilation of \LangLam{}.
  16314. \clearpage
  16315. \section{Challenge: Optimize Closures}
  16316. \label{sec:optimize-closures}
  16317. In this chapter we compile lexically scoped functions into a
  16318. relatively efficient representation: flat closures. However, even this
  16319. representation comes with some overhead. For example, consider the
  16320. following program with a function \code{tail\_sum} that does not have
  16321. any free variables and where all the uses of \code{tail\_sum} are in
  16322. applications in which we know that only \code{tail\_sum} is being applied
  16323. (and not any other functions):
  16324. \begin{center}
  16325. \begin{minipage}{0.95\textwidth}
  16326. {\if\edition\racketEd
  16327. \begin{lstlisting}
  16328. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16329. (if (eq? n 0)
  16330. s
  16331. (tail_sum (- n 1) (+ n s))))
  16332. (+ (tail_sum 3 0) 36)
  16333. \end{lstlisting}
  16334. \fi}
  16335. {\if\edition\pythonEd
  16336. \begin{lstlisting}
  16337. def tail_sum(n : int, s : int) -> int:
  16338. if n == 0:
  16339. return s
  16340. else:
  16341. return tail_sum(n - 1, n + s)
  16342. print( tail_sum(3, 0) + 36)
  16343. \end{lstlisting}
  16344. \fi}
  16345. \end{minipage}
  16346. \end{center}
  16347. As described in this chapter, we uniformly apply closure conversion to
  16348. all functions, obtaining the following output for this program:
  16349. \begin{center}
  16350. \begin{minipage}{0.95\textwidth}
  16351. {\if\edition\racketEd
  16352. \begin{lstlisting}
  16353. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16354. (if (eq? n2 0)
  16355. s3
  16356. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16357. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16358. (define (main) : Integer
  16359. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16360. ((vector-ref clos6 0) clos6 3 0)) 27))
  16361. \end{lstlisting}
  16362. \fi}
  16363. {\if\edition\pythonEd
  16364. \begin{lstlisting}
  16365. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16366. if n_0 == 0:
  16367. return s_1
  16368. else:
  16369. return (let clos_2 = (tail_sum,)
  16370. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16371. def main() -> int :
  16372. print((let clos_4 = (tail_sum,)
  16373. in clos_4[0](clos_4, 3, 0)) + 36)
  16374. return 0
  16375. \end{lstlisting}
  16376. \fi}
  16377. \end{minipage}
  16378. \end{center}
  16379. If this program were compiled according to the previous chapter, there
  16380. would be no allocation and the calls to \code{tail\_sum} would be
  16381. direct calls. In contrast, the program presented here allocates memory
  16382. for each closure and the calls to \code{tail\_sum} are indirect. These
  16383. two differences incur considerable overhead in a program such as this,
  16384. in which the allocations and indirect calls occur inside a tight loop.
  16385. One might think that this problem is trivial to solve: can't we just
  16386. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16387. and compile them to direct calls instead of treating it like a call to
  16388. a closure? We would also drop the new \code{fvs} parameter of
  16389. \code{tail\_sum}.
  16390. %
  16391. However, this problem is not so trivial, because a global function may
  16392. \emph{escape} and become involved in applications that also involve
  16393. closures. Consider the following example in which the application
  16394. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16395. application because the \code{lambda} may flow into \code{f}, but the
  16396. \code{inc} function might also flow into \code{f}:
  16397. \begin{center}
  16398. \begin{minipage}{\textwidth}
  16399. % lambda_test_30.rkt
  16400. {\if\edition\racketEd
  16401. \begin{lstlisting}
  16402. (define (inc [x : Integer]) : Integer
  16403. (+ x 1))
  16404. (let ([y (read)])
  16405. (let ([f (if (eq? (read) 0)
  16406. inc
  16407. (lambda: ([x : Integer]) : Integer (- x y)))])
  16408. (f 41)))
  16409. \end{lstlisting}
  16410. \fi}
  16411. {\if\edition\pythonEd
  16412. \begin{lstlisting}
  16413. def add1(x : int) -> int:
  16414. return x + 1
  16415. y = input_int()
  16416. g : Callable[[int], int] = lambda x: x - y
  16417. f = add1 if input_int() == 0 else g
  16418. print( f(41) )
  16419. \end{lstlisting}
  16420. \fi}
  16421. \end{minipage}
  16422. \end{center}
  16423. If a global function name is used in any way other than as the
  16424. operator in a direct call, then we say that the function
  16425. \emph{escapes}. If a global function does not escape, then we do not
  16426. need to perform closure conversion on the function.
  16427. \begin{exercise}\normalfont\normalsize
  16428. Implement an auxiliary function for detecting which global
  16429. functions escape. Using that function, implement an improved version
  16430. of closure conversion that does not apply closure conversion to
  16431. global functions that do not escape but instead compiles them as
  16432. regular functions. Create several new test cases that check whether
  16433. your compiler properly detect whether global functions escape or not.
  16434. \end{exercise}
  16435. So far we have reduced the overhead of calling global functions, but
  16436. it would also be nice to reduce the overhead of calling a
  16437. \code{lambda} when we can determine at compile time which
  16438. \code{lambda} will be called. We refer to such calls as \emph{known
  16439. calls}. Consider the following example in which a \code{lambda} is
  16440. bound to \code{f} and then applied.
  16441. {\if\edition\racketEd
  16442. % lambda_test_9.rkt
  16443. \begin{lstlisting}
  16444. (let ([y (read)])
  16445. (let ([f (lambda: ([x : Integer]) : Integer
  16446. (+ x y))])
  16447. (f 21)))
  16448. \end{lstlisting}
  16449. \fi}
  16450. {\if\edition\pythonEd
  16451. \begin{lstlisting}
  16452. y = input_int()
  16453. f : Callable[[int],int] = lambda x: x + y
  16454. print( f(21) )
  16455. \end{lstlisting}
  16456. \fi}
  16457. %
  16458. \noindent Closure conversion compiles the application
  16459. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16460. %
  16461. {\if\edition\racketEd
  16462. \begin{lstlisting}
  16463. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16464. (let ([y2 (vector-ref fvs6 1)])
  16465. (+ x3 y2)))
  16466. (define (main) : Integer
  16467. (let ([y2 (read)])
  16468. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16469. ((vector-ref f4 0) f4 21))))
  16470. \end{lstlisting}
  16471. \fi}
  16472. {\if\edition\pythonEd
  16473. \begin{lstlisting}
  16474. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16475. y_1 = fvs_4[1]
  16476. return x_2 + y_1[0]
  16477. def main() -> int:
  16478. y_1 = (777,)
  16479. y_1[0] = input_int()
  16480. f_0 = (lambda_3, y_1)
  16481. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16482. return 0
  16483. \end{lstlisting}
  16484. \fi}
  16485. %
  16486. \noindent However, we can instead compile the application
  16487. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16488. %
  16489. {\if\edition\racketEd
  16490. \begin{lstlisting}
  16491. (define (main) : Integer
  16492. (let ([y2 (read)])
  16493. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16494. ((fun-ref lambda5 1) f4 21))))
  16495. \end{lstlisting}
  16496. \fi}
  16497. {\if\edition\pythonEd
  16498. \begin{lstlisting}
  16499. def main() -> int:
  16500. y_1 = (777,)
  16501. y_1[0] = input_int()
  16502. f_0 = (lambda_3, y_1)
  16503. print(lambda_3(f_0, 21))
  16504. return 0
  16505. \end{lstlisting}
  16506. \fi}
  16507. The problem of determining which \code{lambda} will be called from a
  16508. particular application is quite challenging in general and the topic
  16509. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16510. following exercise we recommend that you compile an application to a
  16511. direct call when the operator is a variable and \racket{the variable
  16512. is \code{let}-bound to a closure}\python{the previous assignment to
  16513. the variable is a closure}. This can be accomplished by maintaining
  16514. an environment that maps variables to function names. Extend the
  16515. environment whenever you encounter a closure on the right-hand side of
  16516. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  16517. name of the global function for the closure. This pass should come
  16518. after closure conversion.
  16519. \begin{exercise}\normalfont\normalsize
  16520. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16521. compiles known calls into direct calls. Verify that your compiler is
  16522. successful in this regard on several example programs.
  16523. \end{exercise}
  16524. These exercises only scratch the surface of closure optimization. A
  16525. good next step for the interested reader is to look at the work of
  16526. \citet{Keep:2012ab}.
  16527. \section{Further Reading}
  16528. The notion of lexically scoped functions predates modern computers by
  16529. about a decade. They were invented by \citet{Church:1932aa}, who
  16530. proposed the lambda calculus as a foundation for logic. Anonymous
  16531. functions were included in the LISP~\citep{McCarthy:1960dz}
  16532. programming language but were initially dynamically scoped. The Scheme
  16533. dialect of LISP adopted lexical scoping, and
  16534. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16535. Scheme programs. However, environments were represented as linked
  16536. lists, so variable look-up was linear in the size of the
  16537. environment. \citet{Appel91} gives a detailed description of several
  16538. closure representations. In this chapter we represent environments
  16539. using flat closures, which were invented by
  16540. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  16541. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16542. closures, variable look-up is constant time but the time to create a
  16543. closure is proportional to the number of its free variables. Flat
  16544. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16545. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16546. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16547. % compilers)
  16548. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16549. \chapter{Dynamic Typing}
  16550. \label{ch:Ldyn}
  16551. \index{subject}{dynamic typing}
  16552. \setcounter{footnote}{0}
  16553. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16554. typed language that is a subset of \racket{Racket}\python{Python}. The
  16555. focus on dynamic typing is in contrast to the previous chapters, which
  16556. have studied the compilation of statically typed languages. In
  16557. dynamically typed languages such as \LangDyn{}, a particular
  16558. expression may produce a value of a different type each time it is
  16559. executed. Consider the following example with a conditional \code{if}
  16560. expression that may return a Boolean or an integer depending on the
  16561. input to the program:
  16562. % part of dynamic_test_25.rkt
  16563. {\if\edition\racketEd
  16564. \begin{lstlisting}
  16565. (not (if (eq? (read) 1) #f 0))
  16566. \end{lstlisting}
  16567. \fi}
  16568. {\if\edition\pythonEd
  16569. \begin{lstlisting}
  16570. not (False if input_int() == 1 else 0)
  16571. \end{lstlisting}
  16572. \fi}
  16573. Languages that allow expressions to produce different kinds of values
  16574. are called \emph{polymorphic}, a word composed of the Greek roots
  16575. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16576. There are several kinds of polymorphism in programming languages, such as
  16577. subtype polymorphism and parametric polymorphism
  16578. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16579. study in this chapter does not have a special name; it is the kind
  16580. that arises in dynamically typed languages.
  16581. Another characteristic of dynamically typed languages is that
  16582. their primitive operations, such as \code{not}, are often defined to operate
  16583. on many different types of values. In fact, in
  16584. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16585. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16586. given anything else it returns \FALSE{}.
  16587. Furthermore, even when primitive operations restrict their inputs to
  16588. values of a certain type, this restriction is enforced at runtime
  16589. instead of during compilation. For example, the tuple read
  16590. operation
  16591. \racket{\code{(vector-ref \#t 0)}}
  16592. \python{\code{True[0]}}
  16593. results in a runtime error because the first argument must
  16594. be a tuple, not a Boolean.
  16595. \section{The \LangDyn{} Language}
  16596. \newcommand{\LdynGrammarRacket}{
  16597. \begin{array}{rcl}
  16598. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16599. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16600. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16601. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16602. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16603. \end{array}
  16604. }
  16605. \newcommand{\LdynASTRacket}{
  16606. \begin{array}{lcl}
  16607. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16608. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16609. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16610. \end{array}
  16611. }
  16612. \begin{figure}[tp]
  16613. \centering
  16614. \begin{tcolorbox}[colback=white]
  16615. \small
  16616. {\if\edition\racketEd
  16617. \[
  16618. \begin{array}{l}
  16619. \gray{\LintGrammarRacket{}} \\ \hline
  16620. \gray{\LvarGrammarRacket{}} \\ \hline
  16621. \gray{\LifGrammarRacket{}} \\ \hline
  16622. \gray{\LwhileGrammarRacket} \\ \hline
  16623. \gray{\LtupGrammarRacket} \\ \hline
  16624. \LdynGrammarRacket \\
  16625. \begin{array}{rcl}
  16626. \LangDynM{} &::=& \Def\ldots\; \Exp
  16627. \end{array}
  16628. \end{array}
  16629. \]
  16630. \fi}
  16631. {\if\edition\pythonEd
  16632. \[
  16633. \begin{array}{rcl}
  16634. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16635. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16636. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16637. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16638. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16639. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16640. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16641. \MID \CLEN{\Exp} \\
  16642. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16643. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16644. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16645. \MID \Var\mathop{\key{=}}\Exp \\
  16646. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16647. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16648. &\MID& \CRETURN{\Exp} \\
  16649. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16650. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16651. \end{array}
  16652. \]
  16653. \fi}
  16654. \end{tcolorbox}
  16655. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16656. \label{fig:r7-concrete-syntax}
  16657. \end{figure}
  16658. \begin{figure}[tp]
  16659. \centering
  16660. \begin{tcolorbox}[colback=white]
  16661. \small
  16662. {\if\edition\racketEd
  16663. \[
  16664. \begin{array}{l}
  16665. \gray{\LintASTRacket{}} \\ \hline
  16666. \gray{\LvarASTRacket{}} \\ \hline
  16667. \gray{\LifASTRacket{}} \\ \hline
  16668. \gray{\LwhileASTRacket} \\ \hline
  16669. \gray{\LtupASTRacket} \\ \hline
  16670. \LdynASTRacket \\
  16671. \begin{array}{lcl}
  16672. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16673. \end{array}
  16674. \end{array}
  16675. \]
  16676. \fi}
  16677. {\if\edition\pythonEd
  16678. \[
  16679. \begin{array}{rcl}
  16680. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16681. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16682. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16683. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16684. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16685. &\MID & \code{Is()} \\
  16686. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16687. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16688. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16689. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16690. \MID \VAR{\Var{}} \\
  16691. &\MID& \BOOL{\itm{bool}}
  16692. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16693. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16694. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16695. &\MID& \LEN{\Exp} \\
  16696. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16697. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16698. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16699. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16700. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16701. &\MID& \RETURN{\Exp} \\
  16702. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16703. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16704. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16705. \end{array}
  16706. \]
  16707. \fi}
  16708. \end{tcolorbox}
  16709. \caption{The abstract syntax of \LangDyn{}.}
  16710. \label{fig:r7-syntax}
  16711. \end{figure}
  16712. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16713. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16714. %
  16715. There is no type checker for \LangDyn{} because it checks types only
  16716. at runtime.
  16717. The definitional interpreter for \LangDyn{} is presented in
  16718. \racket{figure~\ref{fig:interp-Ldyn}}
  16719. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  16720. and definitions of its auxiliary functions are shown in
  16721. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16722. \INT{n}. Instead of simply returning the integer \code{n} (as
  16723. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16724. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16725. value} that combines an underlying value with a tag that identifies
  16726. what kind of value it is. We define the following \racket{struct}\python{class}
  16727. to represent tagged values:
  16728. %
  16729. {\if\edition\racketEd
  16730. \begin{lstlisting}
  16731. (struct Tagged (value tag) #:transparent)
  16732. \end{lstlisting}
  16733. \fi}
  16734. {\if\edition\pythonEd
  16735. \begin{minipage}{\textwidth}
  16736. \begin{lstlisting}
  16737. @dataclass(eq=True)
  16738. class Tagged(Value):
  16739. value : Value
  16740. tag : str
  16741. def __str__(self):
  16742. return str(self.value)
  16743. \end{lstlisting}
  16744. \end{minipage}
  16745. \fi}
  16746. %
  16747. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16748. \code{Vector}, and \code{Procedure}.}
  16749. %
  16750. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16751. \code{'tuple'}, and \code{'function'}.}
  16752. %
  16753. Tags are closely related to types but do not always capture all the
  16754. information that a type does.
  16755. %
  16756. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16757. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16758. Any)} is tagged with \code{Procedure}.}
  16759. %
  16760. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16761. is tagged with \code{'tuple'} and a function of type
  16762. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16763. is tagged with \code{'function'}.}
  16764. Next consider the match case for accessing the element of a tuple.
  16765. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16766. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16767. argument is a tuple and the second is an integer.
  16768. \racket{
  16769. If they are not, a \code{trapped-error} is raised. Recall from
  16770. section~\ref{sec:interp_Lint} that when a definition interpreter
  16771. raises a \code{trapped-error} error, the compiled code must also
  16772. signal an error by exiting with return code \code{255}. A
  16773. \code{trapped-error} is also raised if the index is not less than the
  16774. length of the vector.
  16775. }
  16776. %
  16777. \python{If they are not, an exception is raised. The compiled code
  16778. must also signal an error by exiting with return code \code{255}. A
  16779. exception is also raised if the index is not less than the length of the
  16780. tuple or if it is negative.}
  16781. \begin{figure}[tbp]
  16782. \begin{tcolorbox}[colback=white]
  16783. {\if\edition\racketEd
  16784. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16785. (define ((interp-Ldyn-exp env) ast)
  16786. (define recur (interp-Ldyn-exp env))
  16787. (match ast
  16788. [(Var x) (dict-ref env x)]
  16789. [(Int n) (Tagged n 'Integer)]
  16790. [(Bool b) (Tagged b 'Boolean)]
  16791. [(Lambda xs rt body)
  16792. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16793. [(Prim 'vector es)
  16794. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16795. [(Prim 'vector-ref (list e1 e2))
  16796. (define vec (recur e1)) (define i (recur e2))
  16797. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16798. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16799. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16800. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16801. [(Prim 'vector-set! (list e1 e2 e3))
  16802. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16803. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16804. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16805. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16806. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16807. (Tagged (void) 'Void)]
  16808. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16809. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16810. [(Prim 'or (list e1 e2))
  16811. (define v1 (recur e1))
  16812. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16813. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16814. [(Prim op (list e1))
  16815. #:when (set-member? type-predicates op)
  16816. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16817. [(Prim op es)
  16818. (define args (map recur es))
  16819. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16820. (unless (for/or ([expected-tags (op-tags op)])
  16821. (equal? expected-tags tags))
  16822. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16823. (tag-value
  16824. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16825. [(If q t f)
  16826. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16827. [(Apply f es)
  16828. (define new-f (recur f)) (define args (map recur es))
  16829. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16830. (match f-val
  16831. [`(function ,xs ,body ,lam-env)
  16832. (unless (eq? (length xs) (length args))
  16833. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16834. (define new-env (append (map cons xs args) lam-env))
  16835. ((interp-Ldyn-exp new-env) body)]
  16836. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16837. \end{lstlisting}
  16838. \fi}
  16839. {\if\edition\pythonEd
  16840. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16841. class InterpLdyn(InterpLlambda):
  16842. def interp_exp(self, e, env):
  16843. match e:
  16844. case Constant(n):
  16845. return self.tag(super().interp_exp(e, env))
  16846. case Tuple(es, Load()):
  16847. return self.tag(super().interp_exp(e, env))
  16848. case Lambda(params, body):
  16849. return self.tag(super().interp_exp(e, env))
  16850. case Call(Name('input_int'), []):
  16851. return self.tag(super().interp_exp(e, env))
  16852. case BinOp(left, Add(), right):
  16853. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16854. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16855. case BinOp(left, Sub(), right):
  16856. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16857. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16858. case UnaryOp(USub(), e1):
  16859. v = self.interp_exp(e1, env)
  16860. return self.tag(- self.untag(v, 'int', e))
  16861. case IfExp(test, body, orelse):
  16862. v = self.interp_exp(test, env)
  16863. if self.untag(v, 'bool', e):
  16864. return self.interp_exp(body, env)
  16865. else:
  16866. return self.interp_exp(orelse, env)
  16867. case UnaryOp(Not(), e1):
  16868. v = self.interp_exp(e1, env)
  16869. return self.tag(not self.untag(v, 'bool', e))
  16870. case BoolOp(And(), values):
  16871. left = values[0]; right = values[1]
  16872. l = self.interp_exp(left, env)
  16873. if self.untag(l, 'bool', e):
  16874. return self.interp_exp(right, env)
  16875. else:
  16876. return self.tag(False)
  16877. case BoolOp(Or(), values):
  16878. left = values[0]; right = values[1]
  16879. l = self.interp_exp(left, env)
  16880. if self.untag(l, 'bool', e):
  16881. return self.tag(True)
  16882. else:
  16883. return self.interp_exp(right, env)
  16884. case Compare(left, [cmp], [right]):
  16885. l = self.interp_exp(left, env)
  16886. r = self.interp_exp(right, env)
  16887. if l.tag == r.tag:
  16888. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16889. else:
  16890. raise Exception('interp Compare unexpected '
  16891. + repr(l) + ' ' + repr(r))
  16892. case Subscript(tup, index, Load()):
  16893. t = self.interp_exp(tup, env)
  16894. n = self.interp_exp(index, env)
  16895. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16896. case Call(Name('len'), [tup]):
  16897. t = self.interp_exp(tup, env)
  16898. return self.tag(len(self.untag(t, 'tuple', e)))
  16899. case _:
  16900. return self.tag(super().interp_exp(e, env))
  16901. \end{lstlisting}
  16902. \fi}
  16903. \end{tcolorbox}
  16904. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16905. \label{fig:interp-Ldyn}
  16906. \end{figure}
  16907. {\if\edition\pythonEd
  16908. \begin{figure}[tbp]
  16909. \begin{tcolorbox}[colback=white]
  16910. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16911. class InterpLdyn(InterpLlambda):
  16912. def interp_stmts(self, ss, env):
  16913. if len(ss) == 0:
  16914. return
  16915. match ss[0]:
  16916. case If(test, body, orelse):
  16917. v = self.interp_exp(test, env)
  16918. if self.untag(v, 'bool', ss[0]):
  16919. return self.interp_stmts(body + ss[1:], env)
  16920. else:
  16921. return self.interp_stmts(orelse + ss[1:], env)
  16922. case While(test, body, []):
  16923. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16924. self.interp_stmts(body, env)
  16925. return self.interp_stmts(ss[1:], env)
  16926. case Assign([Subscript(tup, index)], value):
  16927. tup = self.interp_exp(tup, env)
  16928. index = self.interp_exp(index, env)
  16929. tup_v = self.untag(tup, 'tuple', ss[0])
  16930. index_v = self.untag(index, 'int', ss[0])
  16931. tup_v[index_v] = self.interp_exp(value, env)
  16932. return self.interp_stmts(ss[1:], env)
  16933. case FunctionDef(name, params, bod, dl, returns, comment):
  16934. ps = [x for (x,t) in params]
  16935. env[name] = self.tag(Function(name, ps, bod, env))
  16936. return self.interp_stmts(ss[1:], env)
  16937. case _:
  16938. return super().interp_stmts(ss, env)
  16939. \end{lstlisting}
  16940. \end{tcolorbox}
  16941. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16942. \label{fig:interp-Ldyn-2}
  16943. \end{figure}
  16944. \fi}
  16945. \begin{figure}[tbp]
  16946. \begin{tcolorbox}[colback=white]
  16947. {\if\edition\racketEd
  16948. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16949. (define (interp-op op)
  16950. (match op
  16951. ['+ fx+]
  16952. ['- fx-]
  16953. ['read read-fixnum]
  16954. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16955. ['< (lambda (v1 v2)
  16956. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16957. ['<= (lambda (v1 v2)
  16958. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16959. ['> (lambda (v1 v2)
  16960. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16961. ['>= (lambda (v1 v2)
  16962. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16963. ['boolean? boolean?]
  16964. ['integer? fixnum?]
  16965. ['void? void?]
  16966. ['vector? vector?]
  16967. ['vector-length vector-length]
  16968. ['procedure? (match-lambda
  16969. [`(functions ,xs ,body ,env) #t] [else #f])]
  16970. [else (error 'interp-op "unknown operator" op)]))
  16971. (define (op-tags op)
  16972. (match op
  16973. ['+ '((Integer Integer))]
  16974. ['- '((Integer Integer) (Integer))]
  16975. ['read '(())]
  16976. ['not '((Boolean))]
  16977. ['< '((Integer Integer))]
  16978. ['<= '((Integer Integer))]
  16979. ['> '((Integer Integer))]
  16980. ['>= '((Integer Integer))]
  16981. ['vector-length '((Vector))]))
  16982. (define type-predicates
  16983. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16984. (define (tag-value v)
  16985. (cond [(boolean? v) (Tagged v 'Boolean)]
  16986. [(fixnum? v) (Tagged v 'Integer)]
  16987. [(procedure? v) (Tagged v 'Procedure)]
  16988. [(vector? v) (Tagged v 'Vector)]
  16989. [(void? v) (Tagged v 'Void)]
  16990. [else (error 'tag-value "unidentified value ~a" v)]))
  16991. (define (check-tag val expected ast)
  16992. (define tag (Tagged-tag val))
  16993. (unless (eq? tag expected)
  16994. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16995. \end{lstlisting}
  16996. \fi}
  16997. {\if\edition\pythonEd
  16998. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16999. class InterpLdyn(InterpLlambda):
  17000. def tag(self, v):
  17001. if v is True or v is False:
  17002. return Tagged(v, 'bool')
  17003. elif isinstance(v, int):
  17004. return Tagged(v, 'int')
  17005. elif isinstance(v, Function):
  17006. return Tagged(v, 'function')
  17007. elif isinstance(v, tuple):
  17008. return Tagged(v, 'tuple')
  17009. elif isinstance(v, type(None)):
  17010. return Tagged(v, 'none')
  17011. else:
  17012. raise Exception('tag: unexpected ' + repr(v))
  17013. def untag(self, v, expected_tag, ast):
  17014. match v:
  17015. case Tagged(val, tag) if tag == expected_tag:
  17016. return val
  17017. case _:
  17018. raise Exception('expected Tagged value with '
  17019. + expected_tag + ', not ' + ' ' + repr(v))
  17020. def apply_fun(self, fun, args, e):
  17021. f = self.untag(fun, 'function', e)
  17022. return super().apply_fun(f, args, e)
  17023. \end{lstlisting}
  17024. \fi}
  17025. \end{tcolorbox}
  17026. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17027. \label{fig:interp-Ldyn-aux}
  17028. \end{figure}
  17029. \clearpage
  17030. \section{Representation of Tagged Values}
  17031. The interpreter for \LangDyn{} introduced a new kind of value: the
  17032. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17033. represent tagged values at the bit level. Because almost every
  17034. operation in \LangDyn{} involves manipulating tagged values, the
  17035. representation must be efficient. Recall that all our values are 64
  17036. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17037. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17038. $011$ for procedures, and $101$ for the void value\python{,
  17039. \key{None}}. We define the following auxiliary function for mapping
  17040. types to tag codes:
  17041. %
  17042. {\if\edition\racketEd
  17043. \begin{align*}
  17044. \itm{tagof}(\key{Integer}) &= 001 \\
  17045. \itm{tagof}(\key{Boolean}) &= 100 \\
  17046. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17047. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17048. \itm{tagof}(\key{Void}) &= 101
  17049. \end{align*}
  17050. \fi}
  17051. {\if\edition\pythonEd
  17052. \begin{align*}
  17053. \itm{tagof}(\key{IntType()}) &= 001 \\
  17054. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17055. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17056. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17057. \itm{tagof}(\key{type(None)}) &= 101
  17058. \end{align*}
  17059. \fi}
  17060. %
  17061. This stealing of 3 bits comes at some price: integers are now restricted
  17062. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17063. affect tuples and procedures because those values are addresses, and
  17064. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17065. they are always $000$. Thus, we do not lose information by overwriting
  17066. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17067. to recover the original address.
  17068. To make tagged values into first-class entities, we can give them a
  17069. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  17070. operations such as \code{Inject} and \code{Project} for creating and
  17071. using them, yielding the statically typed \LangAny{} intermediate
  17072. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17073. section~\ref{sec:compile-r7}; in th next section we describe the
  17074. \LangAny{} language in greater detail.
  17075. \section{The \LangAny{} Language}
  17076. \label{sec:Rany-lang}
  17077. \newcommand{\LanyASTRacket}{
  17078. \begin{array}{lcl}
  17079. \Type &::= & \ANYTY \\
  17080. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17081. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17082. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17083. \itm{op} &::= & \code{any-vector-length}
  17084. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17085. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17086. \MID \code{procedure?} \MID \code{void?} \\
  17087. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17088. \end{array}
  17089. }
  17090. \newcommand{\LanyASTPython}{
  17091. \begin{array}{lcl}
  17092. \Type &::= & \key{AnyType()} \\
  17093. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17094. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17095. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17096. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17097. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  17098. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  17099. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  17100. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17101. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  17102. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  17103. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  17104. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  17105. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  17106. \end{array}
  17107. }
  17108. \begin{figure}[tp]
  17109. \centering
  17110. \begin{tcolorbox}[colback=white]
  17111. \small
  17112. {\if\edition\racketEd
  17113. \[
  17114. \begin{array}{l}
  17115. \gray{\LintOpAST} \\ \hline
  17116. \gray{\LvarASTRacket{}} \\ \hline
  17117. \gray{\LifASTRacket{}} \\ \hline
  17118. \gray{\LwhileASTRacket{}} \\ \hline
  17119. \gray{\LtupASTRacket{}} \\ \hline
  17120. \gray{\LfunASTRacket} \\ \hline
  17121. \gray{\LlambdaASTRacket} \\ \hline
  17122. \LanyASTRacket \\
  17123. \begin{array}{lcl}
  17124. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17125. \end{array}
  17126. \end{array}
  17127. \]
  17128. \fi}
  17129. {\if\edition\pythonEd
  17130. \[
  17131. \begin{array}{l}
  17132. \gray{\LintASTPython} \\ \hline
  17133. \gray{\LvarASTPython{}} \\ \hline
  17134. \gray{\LifASTPython{}} \\ \hline
  17135. \gray{\LwhileASTPython{}} \\ \hline
  17136. \gray{\LtupASTPython{}} \\ \hline
  17137. \gray{\LfunASTPython} \\ \hline
  17138. \gray{\LlambdaASTPython} \\ \hline
  17139. \LanyASTPython \\
  17140. \begin{array}{lcl}
  17141. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17142. \end{array}
  17143. \end{array}
  17144. \]
  17145. \fi}
  17146. \end{tcolorbox}
  17147. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17148. \label{fig:Lany-syntax}
  17149. \end{figure}
  17150. The definition of the abstract syntax of \LangAny{} is given in
  17151. figure~\ref{fig:Lany-syntax}.
  17152. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17153. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17154. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17155. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17156. converts the tagged value produced by expression $e$ into a value of
  17157. type $T$ or halts the program if the type tag does not match $T$.
  17158. %
  17159. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17160. restricted to be a flat type (the nonterminal $\FType$) which
  17161. simplifies the implementation and complies with the needs for
  17162. compiling \LangDyn{}.
  17163. The \racket{\code{any-vector}} operators
  17164. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17165. operations so that they can be applied to a value of type
  17166. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17167. tuple operations in that the index is not restricted to a literal
  17168. integer in the grammar but is allowed to be any expression.
  17169. \racket{The type predicates such as
  17170. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17171. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17172. the predicate and return {\FALSE} otherwise.}
  17173. The type checker for \LangAny{} is shown in
  17174. figure~\ref{fig:type-check-Lany}
  17175. %
  17176. \racket{ and uses the auxiliary functions presented in
  17177. figure~\ref{fig:type-check-Lany-aux}}.
  17178. %
  17179. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17180. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17181. \begin{figure}[btp]
  17182. \begin{tcolorbox}[colback=white]
  17183. {\if\edition\racketEd
  17184. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17185. (define type-check-Lany-class
  17186. (class type-check-Llambda-class
  17187. (super-new)
  17188. (inherit check-type-equal?)
  17189. (define/override (type-check-exp env)
  17190. (lambda (e)
  17191. (define recur (type-check-exp env))
  17192. (match e
  17193. [(Inject e1 ty)
  17194. (unless (flat-ty? ty)
  17195. (error 'type-check "may only inject from flat type, not ~a" ty))
  17196. (define-values (new-e1 e-ty) (recur e1))
  17197. (check-type-equal? e-ty ty e)
  17198. (values (Inject new-e1 ty) 'Any)]
  17199. [(Project e1 ty)
  17200. (unless (flat-ty? ty)
  17201. (error 'type-check "may only project to flat type, not ~a" ty))
  17202. (define-values (new-e1 e-ty) (recur e1))
  17203. (check-type-equal? e-ty 'Any e)
  17204. (values (Project new-e1 ty) ty)]
  17205. [(Prim 'any-vector-length (list e1))
  17206. (define-values (e1^ t1) (recur e1))
  17207. (check-type-equal? t1 'Any e)
  17208. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17209. [(Prim 'any-vector-ref (list e1 e2))
  17210. (define-values (e1^ t1) (recur e1))
  17211. (define-values (e2^ t2) (recur e2))
  17212. (check-type-equal? t1 'Any e)
  17213. (check-type-equal? t2 'Integer e)
  17214. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17215. [(Prim 'any-vector-set! (list e1 e2 e3))
  17216. (define-values (e1^ t1) (recur e1))
  17217. (define-values (e2^ t2) (recur e2))
  17218. (define-values (e3^ t3) (recur e3))
  17219. (check-type-equal? t1 'Any e)
  17220. (check-type-equal? t2 'Integer e)
  17221. (check-type-equal? t3 'Any e)
  17222. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17223. [(Prim pred (list e1))
  17224. #:when (set-member? (type-predicates) pred)
  17225. (define-values (new-e1 e-ty) (recur e1))
  17226. (check-type-equal? e-ty 'Any e)
  17227. (values (Prim pred (list new-e1)) 'Boolean)]
  17228. [(Prim 'eq? (list arg1 arg2))
  17229. (define-values (e1 t1) (recur arg1))
  17230. (define-values (e2 t2) (recur arg2))
  17231. (match* (t1 t2)
  17232. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17233. [(other wise) (check-type-equal? t1 t2 e)])
  17234. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17235. [else ((super type-check-exp env) e)])))
  17236. ))
  17237. \end{lstlisting}
  17238. \fi}
  17239. {\if\edition\pythonEd
  17240. \begin{lstlisting}
  17241. class TypeCheckLany(TypeCheckLlambda):
  17242. def type_check_exp(self, e, env):
  17243. match e:
  17244. case Inject(value, typ):
  17245. self.check_exp(value, typ, env)
  17246. return AnyType()
  17247. case Project(value, typ):
  17248. self.check_exp(value, AnyType(), env)
  17249. return typ
  17250. case Call(Name('any_tuple_load'), [tup, index]):
  17251. self.check_exp(tup, AnyType(), env)
  17252. self.check_exp(index, IntType(), env)
  17253. return AnyType()
  17254. case Call(Name('any_len'), [tup]):
  17255. self.check_exp(tup, AnyType(), env)
  17256. return IntType()
  17257. case Call(Name('arity'), [fun]):
  17258. ty = self.type_check_exp(fun, env)
  17259. match ty:
  17260. case FunctionType(ps, rt):
  17261. return IntType()
  17262. case TupleType([FunctionType(ps,rs)]):
  17263. return IntType()
  17264. case _:
  17265. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  17266. case Call(Name('make_any'), [value, tag]):
  17267. self.type_check_exp(value, env)
  17268. self.check_exp(tag, IntType(), env)
  17269. return AnyType()
  17270. case AnnLambda(params, returns, body):
  17271. new_env = {x:t for (x,t) in env.items()}
  17272. for (x,t) in params:
  17273. new_env[x] = t
  17274. return_t = self.type_check_exp(body, new_env)
  17275. self.check_type_equal(returns, return_t, e)
  17276. return FunctionType([t for (x,t) in params], return_t)
  17277. case _:
  17278. return super().type_check_exp(e, env)
  17279. \end{lstlisting}
  17280. \fi}
  17281. \end{tcolorbox}
  17282. \caption{Type checker for the \LangAny{} language.}
  17283. \label{fig:type-check-Lany}
  17284. \end{figure}
  17285. {\if\edition\racketEd
  17286. \begin{figure}[tbp]
  17287. \begin{tcolorbox}[colback=white]
  17288. \begin{lstlisting}
  17289. (define/override (operator-types)
  17290. (append
  17291. '((integer? . ((Any) . Boolean))
  17292. (vector? . ((Any) . Boolean))
  17293. (procedure? . ((Any) . Boolean))
  17294. (void? . ((Any) . Boolean)))
  17295. (super operator-types)))
  17296. (define/public (type-predicates)
  17297. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17298. (define/public (flat-ty? ty)
  17299. (match ty
  17300. [(or `Integer `Boolean `Void) #t]
  17301. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17302. [`(,ts ... -> ,rt)
  17303. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17304. [else #f]))
  17305. \end{lstlisting}
  17306. \end{tcolorbox}
  17307. \caption{Auxiliary methods for type checking \LangAny{}.}
  17308. \label{fig:type-check-Lany-aux}
  17309. \end{figure}
  17310. \fi}
  17311. \begin{figure}[btp]
  17312. \begin{tcolorbox}[colback=white]
  17313. {\if\edition\racketEd
  17314. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17315. (define interp-Lany-class
  17316. (class interp-Llambda-class
  17317. (super-new)
  17318. (define/override (interp-op op)
  17319. (match op
  17320. ['boolean? (match-lambda
  17321. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17322. [else #f])]
  17323. ['integer? (match-lambda
  17324. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17325. [else #f])]
  17326. ['vector? (match-lambda
  17327. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17328. [else #f])]
  17329. ['procedure? (match-lambda
  17330. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17331. [else #f])]
  17332. ['eq? (match-lambda*
  17333. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17334. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17335. [ls (apply (super interp-op op) ls)])]
  17336. ['any-vector-ref (lambda (v i)
  17337. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17338. ['any-vector-set! (lambda (v i a)
  17339. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17340. ['any-vector-length (lambda (v)
  17341. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17342. [else (super interp-op op)]))
  17343. (define/override ((interp-exp env) e)
  17344. (define recur (interp-exp env))
  17345. (match e
  17346. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17347. [(Project e ty2) (apply-project (recur e) ty2)]
  17348. [else ((super interp-exp env) e)]))
  17349. ))
  17350. (define (interp-Lany p)
  17351. (send (new interp-Lany-class) interp-program p))
  17352. \end{lstlisting}
  17353. \fi}
  17354. {\if\edition\pythonEd
  17355. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17356. class InterpLany(InterpLlambda):
  17357. def interp_exp(self, e, env):
  17358. match e:
  17359. case Inject(value, typ):
  17360. v = self.interp_exp(value, env)
  17361. return Tagged(v, self.type_to_tag(typ))
  17362. case Project(value, typ):
  17363. v = self.interp_exp(value, env)
  17364. match v:
  17365. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17366. return val
  17367. case _:
  17368. raise Exception('interp project to ' + repr(typ)
  17369. + ' unexpected ' + repr(v))
  17370. case Call(Name('any_tuple_load'), [tup, index]):
  17371. tv = self.interp_exp(tup, env)
  17372. n = self.interp_exp(index, env)
  17373. match tv:
  17374. case Tagged(v, tag):
  17375. return v[n]
  17376. case _:
  17377. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  17378. case Call(Name('any_len'), [value]):
  17379. v = self.interp_exp(value, env)
  17380. match v:
  17381. case Tagged(value, tag):
  17382. return len(value)
  17383. case _:
  17384. raise Exception('interp any_len unexpected ' + repr(v))
  17385. case Call(Name('arity'), [fun]):
  17386. f = self.interp_exp(fun, env)
  17387. return self.arity(f)
  17388. case _:
  17389. return super().interp_exp(e, env)
  17390. \end{lstlisting}
  17391. \fi}
  17392. \end{tcolorbox}
  17393. \caption{Interpreter for \LangAny{}.}
  17394. \label{fig:interp-Lany}
  17395. \end{figure}
  17396. \begin{figure}[tbp]
  17397. \begin{tcolorbox}[colback=white]
  17398. {\if\edition\racketEd
  17399. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17400. (define/public (apply-inject v tg) (Tagged v tg))
  17401. (define/public (apply-project v ty2)
  17402. (define tag2 (any-tag ty2))
  17403. (match v
  17404. [(Tagged v1 tag1)
  17405. (cond
  17406. [(eq? tag1 tag2)
  17407. (match ty2
  17408. [`(Vector ,ts ...)
  17409. (define l1 ((interp-op 'vector-length) v1))
  17410. (cond
  17411. [(eq? l1 (length ts)) v1]
  17412. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17413. l1 (length ts))])]
  17414. [`(,ts ... -> ,rt)
  17415. (match v1
  17416. [`(function ,xs ,body ,env)
  17417. (cond [(eq? (length xs) (length ts)) v1]
  17418. [else
  17419. (error 'apply-project "arity mismatch ~a != ~a"
  17420. (length xs) (length ts))])]
  17421. [else (error 'apply-project "expected function not ~a" v1)])]
  17422. [else v1])]
  17423. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17424. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17425. \end{lstlisting}
  17426. \fi}
  17427. {\if\edition\pythonEd
  17428. \begin{lstlisting}
  17429. class InterpLany(InterpLlambda):
  17430. def type_to_tag(self, typ):
  17431. match typ:
  17432. case FunctionType(params, rt):
  17433. return 'function'
  17434. case TupleType(fields):
  17435. return 'tuple'
  17436. case t if t == int:
  17437. return 'int'
  17438. case t if t == bool:
  17439. return 'bool'
  17440. case IntType():
  17441. return 'int'
  17442. case BoolType():
  17443. return 'int'
  17444. case _:
  17445. raise Exception('type_to_tag unexpected ' + repr(typ))
  17446. def arity(self, v):
  17447. match v:
  17448. case Function(name, params, body, env):
  17449. return len(params)
  17450. case ClosureTuple(args, arity):
  17451. return arity
  17452. case _:
  17453. raise Exception('Lany arity unexpected ' + repr(v))
  17454. \end{lstlisting}
  17455. \fi}
  17456. \end{tcolorbox}
  17457. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17458. \label{fig:interp-Lany-aux}
  17459. \end{figure}
  17460. \clearpage
  17461. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17462. \label{sec:compile-r7}
  17463. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17464. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17465. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17466. is that given any subexpression $e$ in the \LangDyn{} program, the
  17467. pass will produce an expression $e'$ in \LangAny{} that has type
  17468. \ANYTY{}. For example, the first row in
  17469. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17470. \TRUE{}, which must be injected to produce an expression of type
  17471. \ANYTY{}.
  17472. %
  17473. The compilation of addition is shown in the second row of
  17474. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17475. representative of many primitive operations: the arguments have type
  17476. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17477. be performed.
  17478. The compilation of \key{lambda} (third row of
  17479. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17480. produce type annotations: we simply use \ANYTY{}.
  17481. %
  17482. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17483. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17484. this pass has to account for some differences in behavior between
  17485. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17486. permissive than \LangAny{} regarding what kind of values can be used
  17487. in various places. For example, the condition of an \key{if} does
  17488. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17489. of the same type (in that case the result is \code{\#f}).}
  17490. \begin{figure}[btp]
  17491. \centering
  17492. \begin{tcolorbox}[colback=white]
  17493. {\if\edition\racketEd
  17494. \begin{tabular}{lll}
  17495. \begin{minipage}{0.27\textwidth}
  17496. \begin{lstlisting}
  17497. #t
  17498. \end{lstlisting}
  17499. \end{minipage}
  17500. &
  17501. $\Rightarrow$
  17502. &
  17503. \begin{minipage}{0.65\textwidth}
  17504. \begin{lstlisting}
  17505. (inject #t Boolean)
  17506. \end{lstlisting}
  17507. \end{minipage}
  17508. \\[2ex]\hline
  17509. \begin{minipage}{0.27\textwidth}
  17510. \begin{lstlisting}
  17511. (+ |$e_1$| |$e_2$|)
  17512. \end{lstlisting}
  17513. \end{minipage}
  17514. &
  17515. $\Rightarrow$
  17516. &
  17517. \begin{minipage}{0.65\textwidth}
  17518. \begin{lstlisting}
  17519. (inject
  17520. (+ (project |$e'_1$| Integer)
  17521. (project |$e'_2$| Integer))
  17522. Integer)
  17523. \end{lstlisting}
  17524. \end{minipage}
  17525. \\[2ex]\hline
  17526. \begin{minipage}{0.27\textwidth}
  17527. \begin{lstlisting}
  17528. (lambda (|$x_1 \ldots$|) |$e$|)
  17529. \end{lstlisting}
  17530. \end{minipage}
  17531. &
  17532. $\Rightarrow$
  17533. &
  17534. \begin{minipage}{0.65\textwidth}
  17535. \begin{lstlisting}
  17536. (inject
  17537. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17538. (Any|$\ldots$|Any -> Any))
  17539. \end{lstlisting}
  17540. \end{minipage}
  17541. \\[2ex]\hline
  17542. \begin{minipage}{0.27\textwidth}
  17543. \begin{lstlisting}
  17544. (|$e_0$| |$e_1 \ldots e_n$|)
  17545. \end{lstlisting}
  17546. \end{minipage}
  17547. &
  17548. $\Rightarrow$
  17549. &
  17550. \begin{minipage}{0.65\textwidth}
  17551. \begin{lstlisting}
  17552. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17553. \end{lstlisting}
  17554. \end{minipage}
  17555. \\[2ex]\hline
  17556. \begin{minipage}{0.27\textwidth}
  17557. \begin{lstlisting}
  17558. (vector-ref |$e_1$| |$e_2$|)
  17559. \end{lstlisting}
  17560. \end{minipage}
  17561. &
  17562. $\Rightarrow$
  17563. &
  17564. \begin{minipage}{0.65\textwidth}
  17565. \begin{lstlisting}
  17566. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17567. \end{lstlisting}
  17568. \end{minipage}
  17569. \\[2ex]\hline
  17570. \begin{minipage}{0.27\textwidth}
  17571. \begin{lstlisting}
  17572. (if |$e_1$| |$e_2$| |$e_3$|)
  17573. \end{lstlisting}
  17574. \end{minipage}
  17575. &
  17576. $\Rightarrow$
  17577. &
  17578. \begin{minipage}{0.65\textwidth}
  17579. \begin{lstlisting}
  17580. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17581. \end{lstlisting}
  17582. \end{minipage}
  17583. \\[2ex]\hline
  17584. \begin{minipage}{0.27\textwidth}
  17585. \begin{lstlisting}
  17586. (eq? |$e_1$| |$e_2$|)
  17587. \end{lstlisting}
  17588. \end{minipage}
  17589. &
  17590. $\Rightarrow$
  17591. &
  17592. \begin{minipage}{0.65\textwidth}
  17593. \begin{lstlisting}
  17594. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17595. \end{lstlisting}
  17596. \end{minipage}
  17597. \\[2ex]\hline
  17598. \begin{minipage}{0.27\textwidth}
  17599. \begin{lstlisting}
  17600. (not |$e_1$|)
  17601. \end{lstlisting}
  17602. \end{minipage}
  17603. &
  17604. $\Rightarrow$
  17605. &
  17606. \begin{minipage}{0.65\textwidth}
  17607. \begin{lstlisting}
  17608. (if (eq? |$e'_1$| (inject #f Boolean))
  17609. (inject #t Boolean) (inject #f Boolean))
  17610. \end{lstlisting}
  17611. \end{minipage}
  17612. \end{tabular}
  17613. \fi}
  17614. {\if\edition\pythonEd
  17615. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17616. \begin{minipage}{0.23\textwidth}
  17617. \begin{lstlisting}
  17618. True
  17619. \end{lstlisting}
  17620. \end{minipage}
  17621. &
  17622. $\Rightarrow$
  17623. &
  17624. \begin{minipage}{0.7\textwidth}
  17625. \begin{lstlisting}
  17626. Inject(True, BoolType())
  17627. \end{lstlisting}
  17628. \end{minipage}
  17629. \\[2ex]\hline
  17630. \begin{minipage}{0.23\textwidth}
  17631. \begin{lstlisting}
  17632. |$e_1$| + |$e_2$|
  17633. \end{lstlisting}
  17634. \end{minipage}
  17635. &
  17636. $\Rightarrow$
  17637. &
  17638. \begin{minipage}{0.7\textwidth}
  17639. \begin{lstlisting}
  17640. Inject(Project(|$e'_1$|, IntType())
  17641. + Project(|$e'_2$|, IntType()),
  17642. IntType())
  17643. \end{lstlisting}
  17644. \end{minipage}
  17645. \\[2ex]\hline
  17646. \begin{minipage}{0.23\textwidth}
  17647. \begin{lstlisting}
  17648. lambda |$x_1 \ldots$|: |$e$|
  17649. \end{lstlisting}
  17650. \end{minipage}
  17651. &
  17652. $\Rightarrow$
  17653. &
  17654. \begin{minipage}{0.7\textwidth}
  17655. \begin{lstlisting}
  17656. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17657. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17658. \end{lstlisting}
  17659. \end{minipage}
  17660. \\[2ex]\hline
  17661. \begin{minipage}{0.23\textwidth}
  17662. \begin{lstlisting}
  17663. |$e_0$|(|$e_1 \ldots e_n$|)
  17664. \end{lstlisting}
  17665. \end{minipage}
  17666. &
  17667. $\Rightarrow$
  17668. &
  17669. \begin{minipage}{0.7\textwidth}
  17670. \begin{lstlisting}
  17671. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17672. AnyType())), |$e'_1, \ldots, e'_n$|)
  17673. \end{lstlisting}
  17674. \end{minipage}
  17675. \\[2ex]\hline
  17676. \begin{minipage}{0.23\textwidth}
  17677. \begin{lstlisting}
  17678. |$e_1$|[|$e_2$|]
  17679. \end{lstlisting}
  17680. \end{minipage}
  17681. &
  17682. $\Rightarrow$
  17683. &
  17684. \begin{minipage}{0.7\textwidth}
  17685. \begin{lstlisting}
  17686. Call(Name('any_tuple_load'),
  17687. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17688. \end{lstlisting}
  17689. \end{minipage}
  17690. %% \begin{minipage}{0.23\textwidth}
  17691. %% \begin{lstlisting}
  17692. %% |$e_2$| if |$e_1$| else |$e_3$|
  17693. %% \end{lstlisting}
  17694. %% \end{minipage}
  17695. %% &
  17696. %% $\Rightarrow$
  17697. %% &
  17698. %% \begin{minipage}{0.7\textwidth}
  17699. %% \begin{lstlisting}
  17700. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17701. %% \end{lstlisting}
  17702. %% \end{minipage}
  17703. %% \\[2ex]\hline
  17704. %% \begin{minipage}{0.23\textwidth}
  17705. %% \begin{lstlisting}
  17706. %% (eq? |$e_1$| |$e_2$|)
  17707. %% \end{lstlisting}
  17708. %% \end{minipage}
  17709. %% &
  17710. %% $\Rightarrow$
  17711. %% &
  17712. %% \begin{minipage}{0.7\textwidth}
  17713. %% \begin{lstlisting}
  17714. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17715. %% \end{lstlisting}
  17716. %% \end{minipage}
  17717. %% \\[2ex]\hline
  17718. %% \begin{minipage}{0.23\textwidth}
  17719. %% \begin{lstlisting}
  17720. %% (not |$e_1$|)
  17721. %% \end{lstlisting}
  17722. %% \end{minipage}
  17723. %% &
  17724. %% $\Rightarrow$
  17725. %% &
  17726. %% \begin{minipage}{0.7\textwidth}
  17727. %% \begin{lstlisting}
  17728. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17729. %% (inject #t Boolean) (inject #f Boolean))
  17730. %% \end{lstlisting}
  17731. %% \end{minipage}
  17732. %% \\[2ex]\hline
  17733. \\\hline
  17734. \end{tabular}
  17735. \fi}
  17736. \end{tcolorbox}
  17737. \caption{Cast insertion}
  17738. \label{fig:compile-r7-Lany}
  17739. \end{figure}
  17740. \section{Reveal Casts}
  17741. \label{sec:reveal-casts-Lany}
  17742. % TODO: define R'_6
  17743. In the \code{reveal\_casts} pass, we recommend compiling
  17744. \code{Project} into a conditional expression that checks whether the
  17745. value's tag matches the target type; if it does, the value is
  17746. converted to a value of the target type by removing the tag; if it
  17747. does not, the program exits.
  17748. %
  17749. {\if\edition\racketEd
  17750. %
  17751. To perform these actions we need a new primitive operation,
  17752. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17753. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17754. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17755. underlying value from a tagged value. The \code{ValueOf} form
  17756. includes the type for the underlying value that is used by the type
  17757. checker.
  17758. %
  17759. \fi}
  17760. %
  17761. {\if\edition\pythonEd
  17762. %
  17763. To perform these actions we need two new AST classes: \code{TagOf} and
  17764. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17765. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17766. the underlying value from a tagged value. The \code{ValueOf}
  17767. operation includes the type for the underlying value which is used by
  17768. the type checker.
  17769. %
  17770. \fi}
  17771. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17772. \code{Project} can be translated as follows.
  17773. \begin{center}
  17774. \begin{minipage}{1.0\textwidth}
  17775. {\if\edition\racketEd
  17776. \begin{lstlisting}
  17777. (Project |$e$| |$\FType$|)
  17778. |$\Rightarrow$|
  17779. (Let |$\itm{tmp}$| |$e'$|
  17780. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17781. (Int |$\itm{tagof}(\FType)$|)))
  17782. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17783. (Exit)))
  17784. \end{lstlisting}
  17785. \fi}
  17786. {\if\edition\pythonEd
  17787. \begin{lstlisting}
  17788. Project(|$e$|, |$\FType$|)
  17789. |$\Rightarrow$|
  17790. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17791. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17792. [Constant(|$\itm{tagof}(\FType)$|)]),
  17793. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17794. Call(Name('exit'), [])))
  17795. \end{lstlisting}
  17796. \fi}
  17797. \end{minipage}
  17798. \end{center}
  17799. If the target type of the projection is a tuple or function type, then
  17800. there is a bit more work to do. For tuples, check that the length of
  17801. the tuple type matches the length of the tuple. For functions, check
  17802. that the number of parameters in the function type matches the
  17803. function's arity.
  17804. Regarding \code{Inject}, we recommend compiling it to a slightly
  17805. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17806. takes a tag instead of a type.
  17807. \begin{center}
  17808. \begin{minipage}{1.0\textwidth}
  17809. {\if\edition\racketEd
  17810. \begin{lstlisting}
  17811. (Inject |$e$| |$\FType$|)
  17812. |$\Rightarrow$|
  17813. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17814. \end{lstlisting}
  17815. \fi}
  17816. {\if\edition\pythonEd
  17817. \begin{lstlisting}
  17818. Inject(|$e$|, |$\FType$|)
  17819. |$\Rightarrow$|
  17820. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17821. \end{lstlisting}
  17822. \fi}
  17823. \end{minipage}
  17824. \end{center}
  17825. {\if\edition\pythonEd
  17826. %
  17827. The introduction of \code{make\_any} makes it difficult to use
  17828. bidirectional type checking because we no longer have an expected type
  17829. to use for type checking the expression $e'$. Thus, we run into
  17830. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17831. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17832. annotated lambda) whose parameters have type annotations and that
  17833. records the return type.
  17834. %
  17835. \fi}
  17836. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17837. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17838. translation of \code{Project}.}
  17839. {\if\edition\racketEd
  17840. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17841. combine the projection action with the vector operation. Also, the
  17842. read and write operations allow arbitrary expressions for the index, so
  17843. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17844. cannot guarantee that the index is within bounds. Thus, we insert code
  17845. to perform bounds checking at runtime. The translation for
  17846. \code{any-vector-ref} is as follows, and the other two operations are
  17847. translated in a similar way:
  17848. \begin{center}
  17849. \begin{minipage}{0.95\textwidth}
  17850. \begin{lstlisting}
  17851. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17852. |$\Rightarrow$|
  17853. (Let |$v$| |$e'_1$|
  17854. (Let |$i$| |$e'_2$|
  17855. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17856. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17857. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17858. (Exit))
  17859. (Exit))))
  17860. \end{lstlisting}
  17861. \end{minipage}
  17862. \end{center}
  17863. \fi}
  17864. %
  17865. {\if\edition\pythonEd
  17866. %
  17867. The \code{any\_tuple\_load} operation combines the projection action
  17868. with the load operation. Also, the load operation allows arbitrary
  17869. expressions for the index so the type checker for \LangAny{}
  17870. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17871. within bounds. Thus, we insert code to perform bounds checking at
  17872. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17873. \begin{lstlisting}
  17874. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17875. |$\Rightarrow$|
  17876. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17877. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17878. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17879. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17880. Call(Name('exit'), [])),
  17881. Call(Name('exit'), [])))
  17882. \end{lstlisting}
  17883. \fi}
  17884. {\if\edition\pythonEd
  17885. \section{Assignment Conversion}
  17886. \label{sec:convert-assignments-Lany}
  17887. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17888. \code{AnnLambda} AST classes.
  17889. \section{Closure Conversion}
  17890. \label{sec:closure-conversion-Lany}
  17891. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17892. \code{AnnLambda} AST classes.
  17893. \fi}
  17894. \section{Remove Complex Operands}
  17895. \label{sec:rco-Lany}
  17896. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17897. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17898. %
  17899. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17900. complex expressions. Their subexpressions must be atomic.}
  17901. \section{Explicate Control and \LangCAny{}}
  17902. \label{sec:explicate-Lany}
  17903. The output of \code{explicate\_control} is the \LangCAny{} language,
  17904. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17905. %
  17906. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17907. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17908. note that the index argument of \code{vector-ref} and
  17909. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17910. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17911. %
  17912. \python{
  17913. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17914. and \code{explicate\_pred} as appropriately to handle the new expressions
  17915. in \LangCAny{}.
  17916. }
  17917. \newcommand{\CanyASTPython}{
  17918. \begin{array}{lcl}
  17919. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17920. &\MID& \key{TagOf}\LP \Atm \RP
  17921. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17922. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17923. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17924. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17925. \end{array}
  17926. }
  17927. \newcommand{\CanyASTRacket}{
  17928. \begin{array}{lcl}
  17929. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17930. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17931. &\MID& \VALUEOF{\Atm}{\FType} \\
  17932. \Tail &::= & \LP\key{Exit}\RP
  17933. \end{array}
  17934. }
  17935. \begin{figure}[tp]
  17936. \begin{tcolorbox}[colback=white]
  17937. \small
  17938. {\if\edition\racketEd
  17939. \[
  17940. \begin{array}{l}
  17941. \gray{\CvarASTRacket} \\ \hline
  17942. \gray{\CifASTRacket} \\ \hline
  17943. \gray{\CloopASTRacket} \\ \hline
  17944. \gray{\CtupASTRacket} \\ \hline
  17945. \gray{\CfunASTRacket} \\ \hline
  17946. \gray{\ClambdaASTRacket} \\ \hline
  17947. \CanyASTRacket \\
  17948. \begin{array}{lcl}
  17949. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17950. \end{array}
  17951. \end{array}
  17952. \]
  17953. \fi}
  17954. {\if\edition\pythonEd
  17955. \[
  17956. \begin{array}{l}
  17957. \gray{\CifASTPython} \\ \hline
  17958. \gray{\CtupASTPython} \\ \hline
  17959. \gray{\CfunASTPython} \\ \hline
  17960. \gray{\ClambdaASTPython} \\ \hline
  17961. \CanyASTPython \\
  17962. \begin{array}{lcl}
  17963. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17964. \end{array}
  17965. \end{array}
  17966. \]
  17967. \fi}
  17968. \end{tcolorbox}
  17969. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17970. \label{fig:c5-syntax}
  17971. \end{figure}
  17972. \section{Select Instructions}
  17973. \label{sec:select-Lany}
  17974. In the \code{select\_instructions} pass, we translate the primitive
  17975. operations on the \ANYTY{} type to x86 instructions that manipulate
  17976. the three tag bits of the tagged value. In the following descriptions,
  17977. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17978. of translating $e$ into an x86 argument:
  17979. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17980. We recommend compiling the
  17981. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17982. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17983. shifts the destination to the left by the number of bits specified its
  17984. source argument (in this case three, the length of the tag), and it
  17985. preserves the sign of the integer. We use the \key{orq} instruction to
  17986. combine the tag and the value to form the tagged value. \\
  17987. %
  17988. {\if\edition\racketEd
  17989. \begin{lstlisting}
  17990. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17991. |$\Rightarrow$|
  17992. movq |$e'$|, |\itm{lhs'}|
  17993. salq $3, |\itm{lhs'}|
  17994. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17995. \end{lstlisting}
  17996. \fi}
  17997. %
  17998. {\if\edition\pythonEd
  17999. \begin{lstlisting}
  18000. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18001. |$\Rightarrow$|
  18002. movq |$e'$|, |\itm{lhs'}|
  18003. salq $3, |\itm{lhs'}|
  18004. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18005. \end{lstlisting}
  18006. \fi}
  18007. %
  18008. The instruction selection for tuples and procedures is different
  18009. because their is no need to shift them to the left. The rightmost 3
  18010. bits are already zeros, so we simply combine the value and the tag
  18011. using \key{orq}. \\
  18012. %
  18013. {\if\edition\racketEd
  18014. \begin{center}
  18015. \begin{minipage}{\textwidth}
  18016. \begin{lstlisting}
  18017. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18018. |$\Rightarrow$|
  18019. movq |$e'$|, |\itm{lhs'}|
  18020. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18021. \end{lstlisting}
  18022. \end{minipage}
  18023. \end{center}
  18024. \fi}
  18025. %
  18026. {\if\edition\pythonEd
  18027. \begin{lstlisting}
  18028. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18029. |$\Rightarrow$|
  18030. movq |$e'$|, |\itm{lhs'}|
  18031. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18032. \end{lstlisting}
  18033. \fi}
  18034. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18035. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18036. operation extracts the type tag from a value of type \ANYTY{}. The
  18037. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18038. bitwise-and of the value with $111$ ($7$ decimal).
  18039. %
  18040. {\if\edition\racketEd
  18041. \begin{lstlisting}
  18042. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18043. |$\Rightarrow$|
  18044. movq |$e'$|, |\itm{lhs'}|
  18045. andq $7, |\itm{lhs'}|
  18046. \end{lstlisting}
  18047. \fi}
  18048. %
  18049. {\if\edition\pythonEd
  18050. \begin{lstlisting}
  18051. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18052. |$\Rightarrow$|
  18053. movq |$e'$|, |\itm{lhs'}|
  18054. andq $7, |\itm{lhs'}|
  18055. \end{lstlisting}
  18056. \fi}
  18057. \paragraph{\code{ValueOf}}
  18058. The instructions for \key{ValueOf} also differ, depending on whether
  18059. the type $T$ is a pointer (tuple or function) or not (integer or
  18060. Boolean). The following shows the instruction selection for integers
  18061. and Booleans, in which we produce an untagged value by shifting it to
  18062. the right by 3 bits:
  18063. %
  18064. {\if\edition\racketEd
  18065. \begin{lstlisting}
  18066. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18067. |$\Rightarrow$|
  18068. movq |$e'$|, |\itm{lhs'}|
  18069. sarq $3, |\itm{lhs'}|
  18070. \end{lstlisting}
  18071. \fi}
  18072. %
  18073. {\if\edition\pythonEd
  18074. \begin{lstlisting}
  18075. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18076. |$\Rightarrow$|
  18077. movq |$e'$|, |\itm{lhs'}|
  18078. sarq $3, |\itm{lhs'}|
  18079. \end{lstlisting}
  18080. \fi}
  18081. %
  18082. In the case for tuples and procedures, we zero out the rightmost 3
  18083. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18084. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18085. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18086. Finally, we apply \code{andq} with the tagged value to get the desired
  18087. result.
  18088. %
  18089. {\if\edition\racketEd
  18090. \begin{lstlisting}
  18091. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18092. |$\Rightarrow$|
  18093. movq $|$-8$|, |\itm{lhs'}|
  18094. andq |$e'$|, |\itm{lhs'}|
  18095. \end{lstlisting}
  18096. \fi}
  18097. %
  18098. {\if\edition\pythonEd
  18099. \begin{lstlisting}
  18100. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18101. |$\Rightarrow$|
  18102. movq $|$-8$|, |\itm{lhs'}|
  18103. andq |$e'$|, |\itm{lhs'}|
  18104. \end{lstlisting}
  18105. \fi}
  18106. %% \paragraph{Type Predicates} We leave it to the reader to
  18107. %% devise a sequence of instructions to implement the type predicates
  18108. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18109. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18110. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18111. operation combines the effect of \code{ValueOf} with accessing the
  18112. length of a tuple from the tag stored at the zero index of the tuple.
  18113. {\if\edition\racketEd
  18114. \begin{lstlisting}
  18115. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18116. |$\Longrightarrow$|
  18117. movq $|$-8$|, %r11
  18118. andq |$e_1'$|, %r11
  18119. movq 0(%r11), %r11
  18120. andq $126, %r11
  18121. sarq $1, %r11
  18122. movq %r11, |$\itm{lhs'}$|
  18123. \end{lstlisting}
  18124. \fi}
  18125. {\if\edition\pythonEd
  18126. \begin{lstlisting}
  18127. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18128. |$\Longrightarrow$|
  18129. movq $|$-8$|, %r11
  18130. andq |$e_1'$|, %r11
  18131. movq 0(%r11), %r11
  18132. andq $126, %r11
  18133. sarq $1, %r11
  18134. movq %r11, |$\itm{lhs'}$|
  18135. \end{lstlisting}
  18136. \fi}
  18137. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18138. This operation combines the effect of \code{ValueOf} with reading an
  18139. element of the tuple (see
  18140. section~\ref{sec:select-instructions-gc}). However, the index may be
  18141. an arbitrary atom, so instead of computing the offset at compile time,
  18142. we must generate instructions to compute the offset at runtime as
  18143. follows. Note the use of the new instruction \code{imulq}.
  18144. \begin{center}
  18145. \begin{minipage}{0.96\textwidth}
  18146. {\if\edition\racketEd
  18147. \begin{lstlisting}
  18148. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18149. |$\Longrightarrow$|
  18150. movq |$\neg 111$|, %r11
  18151. andq |$e_1'$|, %r11
  18152. movq |$e_2'$|, %rax
  18153. addq $1, %rax
  18154. imulq $8, %rax
  18155. addq %rax, %r11
  18156. movq 0(%r11) |$\itm{lhs'}$|
  18157. \end{lstlisting}
  18158. \fi}
  18159. %
  18160. {\if\edition\pythonEd
  18161. \begin{lstlisting}
  18162. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18163. |$\Longrightarrow$|
  18164. movq $|$-8$|, %r11
  18165. andq |$e_1'$|, %r11
  18166. movq |$e_2'$|, %rax
  18167. addq $1, %rax
  18168. imulq $8, %rax
  18169. addq %rax, %r11
  18170. movq 0(%r11) |$\itm{lhs'}$|
  18171. \end{lstlisting}
  18172. \fi}
  18173. \end{minipage}
  18174. \end{center}
  18175. % $ pacify font lock
  18176. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18177. %% The code generation for
  18178. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18179. %% analogous to the above translation for reading from a tuple.
  18180. \section{Register Allocation for \LangAny{}}
  18181. \label{sec:register-allocation-Lany}
  18182. \index{subject}{register allocation}
  18183. There is an interesting interaction between tagged values and garbage
  18184. collection that has an impact on register allocation. A variable of
  18185. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18186. that needs to be inspected and copied during garbage collection. Thus,
  18187. we need to treat variables of type \ANYTY{} in a similar way to
  18188. variables of tuple type for purposes of register allocation,
  18189. with particular attention to the following:
  18190. \begin{itemize}
  18191. \item If a variable of type \ANYTY{} is live during a function call,
  18192. then it must be spilled. This can be accomplished by changing
  18193. \code{build\_interference} to mark all variables of type \ANYTY{}
  18194. that are live after a \code{callq} to be interfering with all the
  18195. registers.
  18196. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18197. the root stack instead of the normal procedure call stack.
  18198. \end{itemize}
  18199. Another concern regarding the root stack is that the garbage collector
  18200. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18201. tagged value that points to a tuple, and (3) a tagged value that is
  18202. not a tuple. We enable this differentiation by choosing not to use the
  18203. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18204. reserved for identifying plain old pointers to tuples. That way, if
  18205. one of the first three bits is set, then we have a tagged value and
  18206. inspecting the tag can differentiate between tuples ($010$) and the
  18207. other kinds of values.
  18208. %% \begin{exercise}\normalfont
  18209. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18210. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18211. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18212. %% compiler on these new programs and all of your previously created test
  18213. %% programs.
  18214. %% \end{exercise}
  18215. \begin{exercise}\normalfont\normalsize
  18216. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18217. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18218. by removing type annotations. Add five more test programs that
  18219. specifically rely on the language being dynamically typed. That is,
  18220. they should not be legal programs in a statically typed language, but
  18221. nevertheless they should be valid \LangDyn{} programs that run to
  18222. completion without error.
  18223. \end{exercise}
  18224. \begin{figure}[p]
  18225. \begin{tcolorbox}[colback=white]
  18226. {\if\edition\racketEd
  18227. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18228. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18229. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18230. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18231. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18232. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18233. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18234. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18235. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18236. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18237. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18238. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18239. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18240. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18241. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18242. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18243. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18244. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18245. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18246. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18247. \path[->,bend left=15] (Lfun) edge [above] node
  18248. {\ttfamily\footnotesize shrink} (Lfun-2);
  18249. \path[->,bend left=15] (Lfun-2) edge [above] node
  18250. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18251. \path[->,bend left=15] (Lfun-3) edge [above] node
  18252. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18253. \path[->,bend left=15] (Lfun-4) edge [left] node
  18254. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18255. \path[->,bend left=15] (Lfun-5) edge [below] node
  18256. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18257. \path[->,bend left=15] (Lfun-6) edge [below] node
  18258. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18259. \path[->,bend right=15] (Lfun-7) edge [above] node
  18260. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18261. \path[->,bend right=15] (F1-2) edge [right] node
  18262. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18263. \path[->,bend right=15] (F1-3) edge [below] node
  18264. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18265. \path[->,bend right=15] (F1-4) edge [below] node
  18266. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18267. \path[->,bend left=15] (F1-5) edge [above] node
  18268. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18269. \path[->,bend left=15] (F1-6) edge [below] node
  18270. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18271. \path[->,bend left=15] (C3-2) edge [right] node
  18272. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18273. \path[->,bend right=15] (x86-2) edge [right] node
  18274. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18275. \path[->,bend right=15] (x86-2-1) edge [below] node
  18276. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18277. \path[->,bend right=15] (x86-2-2) edge [right] node
  18278. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18279. \path[->,bend left=15] (x86-3) edge [above] node
  18280. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18281. \path[->,bend left=15] (x86-4) edge [right] node
  18282. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18283. \end{tikzpicture}
  18284. \fi}
  18285. {\if\edition\pythonEd
  18286. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18287. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18288. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18289. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18290. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18291. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18292. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18293. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18294. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18295. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18296. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18297. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18298. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18299. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18300. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18301. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18302. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18303. \path[->,bend left=15] (Lfun) edge [above] node
  18304. {\ttfamily\footnotesize shrink} (Lfun-2);
  18305. \path[->,bend left=15] (Lfun-2) edge [above] node
  18306. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18307. \path[->,bend left=15] (Lfun-3) edge [above] node
  18308. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18309. \path[->,bend left=15] (Lfun-4) edge [left] node
  18310. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18311. \path[->,bend left=15] (Lfun-5) edge [below] node
  18312. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18313. \path[->,bend right=15] (Lfun-6) edge [above] node
  18314. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18315. \path[->,bend right=15] (Lfun-7) edge [above] node
  18316. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18317. \path[->,bend right=15] (F1-2) edge [right] node
  18318. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18319. \path[->,bend right=15] (F1-3) edge [below] node
  18320. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18321. \path[->,bend left=15] (F1-5) edge [above] node
  18322. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18323. \path[->,bend left=15] (F1-6) edge [below] node
  18324. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18325. \path[->,bend right=15] (C3-2) edge [right] node
  18326. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18327. \path[->,bend right=15] (x86-2) edge [below] node
  18328. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18329. \path[->,bend right=15] (x86-3) edge [below] node
  18330. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18331. \path[->,bend left=15] (x86-4) edge [above] node
  18332. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18333. \end{tikzpicture}
  18334. \fi}
  18335. \end{tcolorbox}
  18336. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18337. \label{fig:Ldyn-passes}
  18338. \end{figure}
  18339. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  18340. for the compilation of \LangDyn{}.
  18341. % Further Reading
  18342. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18343. %% {\if\edition\pythonEd
  18344. %% \chapter{Objects}
  18345. %% \label{ch:Lobject}
  18346. %% \index{subject}{objects}
  18347. %% \index{subject}{classes}
  18348. %% \setcounter{footnote}{0}
  18349. %% \fi}
  18350. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18351. \chapter{Gradual Typing}
  18352. \label{ch:Lgrad}
  18353. \index{subject}{gradual typing}
  18354. \setcounter{footnote}{0}
  18355. This chapter studies the language \LangGrad{}, in which the programmer
  18356. can choose between static and dynamic type checking in different parts
  18357. of a program, thereby mixing the statically typed \LangLam{} language
  18358. with the dynamically typed \LangDyn{}. There are several approaches to
  18359. mixing static and dynamic typing, including multilanguage
  18360. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18361. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18362. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18363. programmer controls the amount of static versus dynamic checking by
  18364. adding or removing type annotations on parameters and
  18365. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18366. The definition of the concrete syntax of \LangGrad{} is shown in
  18367. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  18368. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18369. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18370. annotations are optional, which is specified in the grammar using the
  18371. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18372. annotations are not optional, but we use the \CANYTY{} type when a type
  18373. annotation is absent.
  18374. %
  18375. Both the type checker and the interpreter for \LangGrad{} require some
  18376. interesting changes to enable gradual typing, which we discuss in the
  18377. next two sections.
  18378. \newcommand{\LgradGrammarRacket}{
  18379. \begin{array}{lcl}
  18380. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18381. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18382. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18383. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18384. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18385. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18386. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18387. \end{array}
  18388. }
  18389. \newcommand{\LgradASTRacket}{
  18390. \begin{array}{lcl}
  18391. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18392. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18393. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18394. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18395. \itm{op} &::=& \code{procedure-arity} \\
  18396. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18397. \end{array}
  18398. }
  18399. \newcommand{\LgradGrammarPython}{
  18400. \begin{array}{lcl}
  18401. \Type &::=& \key{Any}
  18402. \MID \key{int}
  18403. \MID \key{bool}
  18404. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18405. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18406. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18407. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18408. \MID \CARITY{\Exp} \\
  18409. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18410. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18411. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18412. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18413. \end{array}
  18414. }
  18415. \newcommand{\LgradASTPython}{
  18416. \begin{array}{lcl}
  18417. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18418. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18419. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18420. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18421. &\MID& \ARITY{\Exp} \\
  18422. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18423. \MID \RETURN{\Exp} \\
  18424. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18425. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18426. \end{array}
  18427. }
  18428. \begin{figure}[tp]
  18429. \centering
  18430. \begin{tcolorbox}[colback=white]
  18431. \small
  18432. {\if\edition\racketEd
  18433. \[
  18434. \begin{array}{l}
  18435. \gray{\LintGrammarRacket{}} \\ \hline
  18436. \gray{\LvarGrammarRacket{}} \\ \hline
  18437. \gray{\LifGrammarRacket{}} \\ \hline
  18438. \gray{\LwhileGrammarRacket} \\ \hline
  18439. \gray{\LtupGrammarRacket} \\ \hline
  18440. \LgradGrammarRacket \\
  18441. \begin{array}{lcl}
  18442. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18443. \end{array}
  18444. \end{array}
  18445. \]
  18446. \fi}
  18447. {\if\edition\pythonEd
  18448. \[
  18449. \begin{array}{l}
  18450. \gray{\LintGrammarPython{}} \\ \hline
  18451. \gray{\LvarGrammarPython{}} \\ \hline
  18452. \gray{\LifGrammarPython{}} \\ \hline
  18453. \gray{\LwhileGrammarPython} \\ \hline
  18454. \gray{\LtupGrammarPython} \\ \hline
  18455. \LgradGrammarPython \\
  18456. \begin{array}{lcl}
  18457. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18458. \end{array}
  18459. \end{array}
  18460. \]
  18461. \fi}
  18462. \end{tcolorbox}
  18463. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18464. \label{fig:Lgrad-concrete-syntax}
  18465. \end{figure}
  18466. \begin{figure}[tp]
  18467. \centering
  18468. \begin{tcolorbox}[colback=white]
  18469. \small
  18470. {\if\edition\racketEd
  18471. \[
  18472. \begin{array}{l}
  18473. \gray{\LintOpAST} \\ \hline
  18474. \gray{\LvarASTRacket{}} \\ \hline
  18475. \gray{\LifASTRacket{}} \\ \hline
  18476. \gray{\LwhileASTRacket{}} \\ \hline
  18477. \gray{\LtupASTRacket{}} \\ \hline
  18478. \LgradASTRacket \\
  18479. \begin{array}{lcl}
  18480. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18481. \end{array}
  18482. \end{array}
  18483. \]
  18484. \fi}
  18485. {\if\edition\pythonEd
  18486. \[
  18487. \begin{array}{l}
  18488. \gray{\LintASTPython{}} \\ \hline
  18489. \gray{\LvarASTPython{}} \\ \hline
  18490. \gray{\LifASTPython{}} \\ \hline
  18491. \gray{\LwhileASTPython} \\ \hline
  18492. \gray{\LtupASTPython} \\ \hline
  18493. \LgradASTPython \\
  18494. \begin{array}{lcl}
  18495. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18496. \end{array}
  18497. \end{array}
  18498. \]
  18499. \fi}
  18500. \end{tcolorbox}
  18501. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18502. \label{fig:Lgrad-syntax}
  18503. \end{figure}
  18504. % TODO: more road map -Jeremy
  18505. %\clearpage
  18506. \section{Type Checking \LangGrad{}}
  18507. \label{sec:gradual-type-check}
  18508. We begin by discussing the type checking of a partially typed variant
  18509. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18510. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18511. statically typed, so there is nothing special happening there with
  18512. respect to type checking. On the other hand, the \code{inc} function
  18513. does not have type annotations, so the type checker assigns the type
  18514. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18515. \code{+} operator inside \code{inc}. It expects both arguments to have
  18516. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18517. a gradually typed language, such differences are allowed so long as
  18518. the types are \emph{consistent}; that is, they are equal except in
  18519. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18520. is consistent with every other type. Figure~\ref{fig:consistent}
  18521. shows the definition of the
  18522. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18523. %
  18524. So the type checker allows the \code{+} operator to be applied
  18525. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18526. %
  18527. Next consider the call to the \code{map} function shown in
  18528. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18529. tuple. The \code{inc} function has type
  18530. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18531. but parameter \code{f} of \code{map} has type
  18532. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18533. The type checker for \LangGrad{} accepts this call because the two types are
  18534. consistent.
  18535. \begin{figure}[btp]
  18536. % gradual_test_9.rkt
  18537. \begin{tcolorbox}[colback=white]
  18538. {\if\edition\racketEd
  18539. \begin{lstlisting}
  18540. (define (map [f : (Integer -> Integer)]
  18541. [v : (Vector Integer Integer)])
  18542. : (Vector Integer Integer)
  18543. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18544. (define (inc x) (+ x 1))
  18545. (vector-ref (map inc (vector 0 41)) 1)
  18546. \end{lstlisting}
  18547. \fi}
  18548. {\if\edition\pythonEd
  18549. \begin{lstlisting}
  18550. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18551. return f(v[0]), f(v[1])
  18552. def inc(x):
  18553. return x + 1
  18554. t = map(inc, (0, 41))
  18555. print(t[1])
  18556. \end{lstlisting}
  18557. \fi}
  18558. \end{tcolorbox}
  18559. \caption{A partially typed version of the \code{map} example.}
  18560. \label{fig:gradual-map}
  18561. \end{figure}
  18562. \begin{figure}[tbp]
  18563. \begin{tcolorbox}[colback=white]
  18564. {\if\edition\racketEd
  18565. \begin{lstlisting}
  18566. (define/public (consistent? t1 t2)
  18567. (match* (t1 t2)
  18568. [('Integer 'Integer) #t]
  18569. [('Boolean 'Boolean) #t]
  18570. [('Void 'Void) #t]
  18571. [('Any t2) #t]
  18572. [(t1 'Any) #t]
  18573. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18574. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18575. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18576. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18577. (consistent? rt1 rt2))]
  18578. [(other wise) #f]))
  18579. \end{lstlisting}
  18580. \fi}
  18581. {\if\edition\pythonEd
  18582. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18583. def consistent(self, t1, t2):
  18584. match (t1, t2):
  18585. case (AnyType(), _):
  18586. return True
  18587. case (_, AnyType()):
  18588. return True
  18589. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18590. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18591. case (TupleType(ts1), TupleType(ts2)):
  18592. return all(map(self.consistent, ts1, ts2))
  18593. case (_, _):
  18594. return t1 == t2
  18595. \end{lstlisting}
  18596. \fi}
  18597. \end{tcolorbox}
  18598. \caption{The consistency method on types.}
  18599. \label{fig:consistent}
  18600. \end{figure}
  18601. It is also helpful to consider how gradual typing handles programs with an
  18602. error, such as applying \code{map} to a function that sometimes
  18603. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18604. type checker for \LangGrad{} accepts this program because the type of
  18605. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18606. \code{map}; that is,
  18607. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18608. is consistent with
  18609. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18610. One might say that a gradual type checker is optimistic in that it
  18611. accepts programs that might execute without a runtime type error.
  18612. %
  18613. The definition of the type checker for \LangGrad{} is shown in
  18614. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18615. and \ref{fig:type-check-Lgradual-3}.
  18616. %% \begin{figure}[tp]
  18617. %% \centering
  18618. %% \fbox{
  18619. %% \begin{minipage}{0.96\textwidth}
  18620. %% \small
  18621. %% \[
  18622. %% \begin{array}{lcl}
  18623. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18624. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18625. %% \end{array}
  18626. %% \]
  18627. %% \end{minipage}
  18628. %% }
  18629. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18630. %% \label{fig:Lgrad-prime-syntax}
  18631. %% \end{figure}
  18632. \begin{figure}[tbp]
  18633. \begin{tcolorbox}[colback=white]
  18634. {\if\edition\racketEd
  18635. \begin{lstlisting}
  18636. (define (map [f : (Integer -> Integer)]
  18637. [v : (Vector Integer Integer)])
  18638. : (Vector Integer Integer)
  18639. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18640. (define (inc x) (+ x 1))
  18641. (define (true) #t)
  18642. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18643. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18644. \end{lstlisting}
  18645. \fi}
  18646. {\if\edition\pythonEd
  18647. \begin{lstlisting}
  18648. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18649. return f(v[0]), f(v[1])
  18650. def inc(x):
  18651. return x + 1
  18652. def true():
  18653. return True
  18654. def maybe_inc(x):
  18655. return inc(x) if input_int() == 0 else true()
  18656. t = map(maybe_inc, (0, 41))
  18657. print( t[1] )
  18658. \end{lstlisting}
  18659. \fi}
  18660. \end{tcolorbox}
  18661. \caption{A variant of the \code{map} example with an error.}
  18662. \label{fig:map-maybe_inc}
  18663. \end{figure}
  18664. Running this program with input \code{1} triggers an
  18665. error when the \code{maybe\_inc} function returns
  18666. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18667. performs checking at runtime to ensure the integrity of the static
  18668. types, such as the
  18669. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18670. annotation on
  18671. parameter \code{f} of \code{map}.
  18672. Here we give a preview of how the runtime checking is accomplished;
  18673. the following sections provide the details.
  18674. The runtime checking is carried out by a new \code{Cast} AST node that
  18675. is generated in a new pass named \code{cast\_insert}. The output of
  18676. \code{cast\_insert} is a program in the \LangCast{} language, which
  18677. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18678. %
  18679. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18680. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18681. inserted every time the type checker encounters two types that are
  18682. consistent but not equal. In the \code{inc} function, \code{x} is
  18683. cast to \INTTY{} and the result of the \code{+} is cast to
  18684. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18685. is cast from
  18686. \racket{\code{(Any -> Any)}}
  18687. \python{\code{Callable[[Any], Any]}}
  18688. to
  18689. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18690. %
  18691. In the next section we see how to interpret the \code{Cast} node.
  18692. \begin{figure}[btp]
  18693. \begin{tcolorbox}[colback=white]
  18694. {\if\edition\racketEd
  18695. \begin{lstlisting}
  18696. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18697. : (Vector Integer Integer)
  18698. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18699. (define (inc [x : Any]) : Any
  18700. (cast (+ (cast x Any Integer) 1) Integer Any))
  18701. (define (true) : Any (cast #t Boolean Any))
  18702. (define (maybe_inc [x : Any]) : Any
  18703. (if (eq? 0 (read)) (inc x) (true)))
  18704. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18705. (vector 0 41)) 0)
  18706. \end{lstlisting}
  18707. \fi}
  18708. {\if\edition\pythonEd
  18709. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18710. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18711. return f(v[0]), f(v[1])
  18712. def inc(x : Any) -> Any:
  18713. return Cast(Cast(x, Any, int) + 1, int, Any)
  18714. def true() -> Any:
  18715. return Cast(True, bool, Any)
  18716. def maybe_inc(x : Any) -> Any:
  18717. return inc(x) if input_int() == 0 else true()
  18718. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18719. (0, 41))
  18720. print(t[1])
  18721. \end{lstlisting}
  18722. \fi}
  18723. \end{tcolorbox}
  18724. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18725. and \code{maybe\_inc} example.}
  18726. \label{fig:map-cast}
  18727. \end{figure}
  18728. {\if\edition\pythonEd
  18729. \begin{figure}[tbp]
  18730. \begin{tcolorbox}[colback=white]
  18731. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18732. class TypeCheckLgrad(TypeCheckLlambda):
  18733. def type_check_exp(self, e, env) -> Type:
  18734. match e:
  18735. case Name(id):
  18736. return env[id]
  18737. case Constant(value) if isinstance(value, bool):
  18738. return BoolType()
  18739. case Constant(value) if isinstance(value, int):
  18740. return IntType()
  18741. case Call(Name('input_int'), []):
  18742. return IntType()
  18743. case BinOp(left, op, right):
  18744. left_type = self.type_check_exp(left, env)
  18745. self.check_consistent(left_type, IntType(), left)
  18746. right_type = self.type_check_exp(right, env)
  18747. self.check_consistent(right_type, IntType(), right)
  18748. return IntType()
  18749. case IfExp(test, body, orelse):
  18750. test_t = self.type_check_exp(test, env)
  18751. self.check_consistent(test_t, BoolType(), test)
  18752. body_t = self.type_check_exp(body, env)
  18753. orelse_t = self.type_check_exp(orelse, env)
  18754. self.check_consistent(body_t, orelse_t, e)
  18755. return self.join_types(body_t, orelse_t)
  18756. case Call(func, args):
  18757. func_t = self.type_check_exp(func, env)
  18758. args_t = [self.type_check_exp(arg, env) for arg in args]
  18759. match func_t:
  18760. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18761. for (arg_t, param_t) in zip(args_t, params_t):
  18762. self.check_consistent(param_t, arg_t, e)
  18763. return return_t
  18764. case AnyType():
  18765. return AnyType()
  18766. case _:
  18767. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18768. ...
  18769. case _:
  18770. raise Exception('type_check_exp: unexpected ' + repr(e))
  18771. \end{lstlisting}
  18772. \end{tcolorbox}
  18773. \caption{Type checking expressions in the \LangGrad{} language.}
  18774. \label{fig:type-check-Lgradual-1}
  18775. \end{figure}
  18776. \begin{figure}[tbp]
  18777. \begin{tcolorbox}[colback=white]
  18778. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18779. def check_exp(self, e, expected_ty, env):
  18780. match e:
  18781. case Lambda(params, body):
  18782. match expected_ty:
  18783. case FunctionType(params_t, return_t):
  18784. new_env = env.copy().update(zip(params, params_t))
  18785. e.has_type = expected_ty
  18786. body_ty = self.type_check_exp(body, new_env)
  18787. self.check_consistent(body_ty, return_t)
  18788. case AnyType():
  18789. new_env = env.copy().update((p, AnyType()) for p in params)
  18790. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18791. body_ty = self.type_check_exp(body, new_env)
  18792. case _:
  18793. raise Exception('lambda does not have type ' + str(expected_ty))
  18794. case _:
  18795. e_ty = self.type_check_exp(e, env)
  18796. self.check_consistent(e_ty, expected_ty, e)
  18797. \end{lstlisting}
  18798. \end{tcolorbox}
  18799. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18800. \label{fig:type-check-Lgradual-2}
  18801. \end{figure}
  18802. \begin{figure}[tbp]
  18803. \begin{tcolorbox}[colback=white]
  18804. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18805. def type_check_stmt(self, s, env, return_type):
  18806. match s:
  18807. case Assign([Name(id)], value):
  18808. value_ty = self.type_check_exp(value, env)
  18809. if id in env:
  18810. self.check_consistent(env[id], value_ty, value)
  18811. else:
  18812. env[id] = value_ty
  18813. ...
  18814. case _:
  18815. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18816. def type_check_stmts(self, ss, env, return_type):
  18817. for s in ss:
  18818. self.type_check_stmt(s, env, return_type)
  18819. \end{lstlisting}
  18820. \end{tcolorbox}
  18821. \caption{Type checking statements in the \LangGrad{} language.}
  18822. \label{fig:type-check-Lgradual-3}
  18823. \end{figure}
  18824. \begin{figure}[tbp]
  18825. \begin{tcolorbox}[colback=white]
  18826. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18827. def join_types(self, t1, t2):
  18828. match (t1, t2):
  18829. case (AnyType(), _):
  18830. return t2
  18831. case (_, AnyType()):
  18832. return t1
  18833. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18834. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18835. self.join_types(rt1,rt2))
  18836. case (TupleType(ts1), TupleType(ts2)):
  18837. return TupleType(list(map(self.join_types, ts1, ts2)))
  18838. case (_, _):
  18839. return t1
  18840. def check_consistent(self, t1, t2, e):
  18841. if not self.consistent(t1, t2):
  18842. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18843. + ' in ' + repr(e))
  18844. \end{lstlisting}
  18845. \end{tcolorbox}
  18846. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18847. \label{fig:type-check-Lgradual-aux}
  18848. \end{figure}
  18849. \fi}
  18850. {\if\edition\racketEd
  18851. \begin{figure}[tbp]
  18852. \begin{tcolorbox}[colback=white]
  18853. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18854. (define/override (type-check-exp env)
  18855. (lambda (e)
  18856. (define recur (type-check-exp env))
  18857. (match e
  18858. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18859. (define-values (new-es ts)
  18860. (for/lists (exprs types) ([e es])
  18861. (recur e)))
  18862. (define t-ret (type-check-op op ts e))
  18863. (values (Prim op new-es) t-ret)]
  18864. [(Prim 'eq? (list e1 e2))
  18865. (define-values (e1^ t1) (recur e1))
  18866. (define-values (e2^ t2) (recur e2))
  18867. (check-consistent? t1 t2 e)
  18868. (define T (meet t1 t2))
  18869. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18870. [(Prim 'and (list e1 e2))
  18871. (recur (If e1 e2 (Bool #f)))]
  18872. [(Prim 'or (list e1 e2))
  18873. (define tmp (gensym 'tmp))
  18874. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18875. [(If e1 e2 e3)
  18876. (define-values (e1^ T1) (recur e1))
  18877. (define-values (e2^ T2) (recur e2))
  18878. (define-values (e3^ T3) (recur e3))
  18879. (check-consistent? T1 'Boolean e)
  18880. (check-consistent? T2 T3 e)
  18881. (define Tif (meet T2 T3))
  18882. (values (If e1^ e2^ e3^) Tif)]
  18883. [(SetBang x e1)
  18884. (define-values (e1^ T1) (recur e1))
  18885. (define varT (dict-ref env x))
  18886. (check-consistent? T1 varT e)
  18887. (values (SetBang x e1^) 'Void)]
  18888. [(WhileLoop e1 e2)
  18889. (define-values (e1^ T1) (recur e1))
  18890. (check-consistent? T1 'Boolean e)
  18891. (define-values (e2^ T2) ((type-check-exp env) e2))
  18892. (values (WhileLoop e1^ e2^) 'Void)]
  18893. [(Prim 'vector-length (list e1))
  18894. (define-values (e1^ t) (recur e1))
  18895. (match t
  18896. [`(Vector ,ts ...)
  18897. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18898. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18899. \end{lstlisting}
  18900. \end{tcolorbox}
  18901. \caption{Type checker for the \LangGrad{} language, part 1.}
  18902. \label{fig:type-check-Lgradual-1}
  18903. \end{figure}
  18904. \begin{figure}[tbp]
  18905. \begin{tcolorbox}[colback=white]
  18906. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18907. [(Prim 'vector-ref (list e1 e2))
  18908. (define-values (e1^ t1) (recur e1))
  18909. (define-values (e2^ t2) (recur e2))
  18910. (check-consistent? t2 'Integer e)
  18911. (match t1
  18912. [`(Vector ,ts ...)
  18913. (match e2^
  18914. [(Int i)
  18915. (unless (and (0 . <= . i) (i . < . (length ts)))
  18916. (error 'type-check "invalid index ~a in ~a" i e))
  18917. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18918. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18919. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18920. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18921. [(Prim 'vector-set! (list e1 e2 e3) )
  18922. (define-values (e1^ t1) (recur e1))
  18923. (define-values (e2^ t2) (recur e2))
  18924. (define-values (e3^ t3) (recur e3))
  18925. (check-consistent? t2 'Integer e)
  18926. (match t1
  18927. [`(Vector ,ts ...)
  18928. (match e2^
  18929. [(Int i)
  18930. (unless (and (0 . <= . i) (i . < . (length ts)))
  18931. (error 'type-check "invalid index ~a in ~a" i e))
  18932. (check-consistent? (list-ref ts i) t3 e)
  18933. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18934. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18935. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18936. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18937. [(Apply e1 e2s)
  18938. (define-values (e1^ T1) (recur e1))
  18939. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18940. (match T1
  18941. [`(,T1ps ... -> ,T1rt)
  18942. (for ([T2 T2s] [Tp T1ps])
  18943. (check-consistent? T2 Tp e))
  18944. (values (Apply e1^ e2s^) T1rt)]
  18945. [`Any (values (Apply e1^ e2s^) 'Any)]
  18946. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18947. [(Lambda params Tr e1)
  18948. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18949. (match p
  18950. [`[,x : ,T] (values x T)]
  18951. [(? symbol? x) (values x 'Any)])))
  18952. (define-values (e1^ T1)
  18953. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18954. (check-consistent? Tr T1 e)
  18955. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18956. `(,@Ts -> ,Tr))]
  18957. [else ((super type-check-exp env) e)]
  18958. )))
  18959. \end{lstlisting}
  18960. \end{tcolorbox}
  18961. \caption{Type checker for the \LangGrad{} language, part 2.}
  18962. \label{fig:type-check-Lgradual-2}
  18963. \end{figure}
  18964. \begin{figure}[tbp]
  18965. \begin{tcolorbox}[colback=white]
  18966. \begin{lstlisting}
  18967. (define/override (type-check-def env)
  18968. (lambda (e)
  18969. (match e
  18970. [(Def f params rt info body)
  18971. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18972. (match p
  18973. [`[,x : ,T] (values x T)]
  18974. [(? symbol? x) (values x 'Any)])))
  18975. (define new-env (append (map cons xs ps) env))
  18976. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18977. (check-consistent? ty^ rt e)
  18978. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  18979. [else (error 'type-check "ill-formed function definition ~a" e)]
  18980. )))
  18981. (define/override (type-check-program e)
  18982. (match e
  18983. [(Program info body)
  18984. (define-values (body^ ty) ((type-check-exp '()) body))
  18985. (check-consistent? ty 'Integer e)
  18986. (ProgramDefsExp info '() body^)]
  18987. [(ProgramDefsExp info ds body)
  18988. (define new-env (for/list ([d ds])
  18989. (cons (Def-name d) (fun-def-type d))))
  18990. (define ds^ (for/list ([d ds])
  18991. ((type-check-def new-env) d)))
  18992. (define-values (body^ ty) ((type-check-exp new-env) body))
  18993. (check-consistent? ty 'Integer e)
  18994. (ProgramDefsExp info ds^ body^)]
  18995. [else (super type-check-program e)]))
  18996. \end{lstlisting}
  18997. \end{tcolorbox}
  18998. \caption{Type checker for the \LangGrad{} language, part 3.}
  18999. \label{fig:type-check-Lgradual-3}
  19000. \end{figure}
  19001. \begin{figure}[tbp]
  19002. \begin{tcolorbox}[colback=white]
  19003. \begin{lstlisting}
  19004. (define/public (join t1 t2)
  19005. (match* (t1 t2)
  19006. [('Integer 'Integer) 'Integer]
  19007. [('Boolean 'Boolean) 'Boolean]
  19008. [('Void 'Void) 'Void]
  19009. [('Any t2) t2]
  19010. [(t1 'Any) t1]
  19011. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19012. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19013. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19014. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19015. -> ,(join rt1 rt2))]))
  19016. (define/public (meet t1 t2)
  19017. (match* (t1 t2)
  19018. [('Integer 'Integer) 'Integer]
  19019. [('Boolean 'Boolean) 'Boolean]
  19020. [('Void 'Void) 'Void]
  19021. [('Any t2) 'Any]
  19022. [(t1 'Any) 'Any]
  19023. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19024. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19025. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19026. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19027. -> ,(meet rt1 rt2))]))
  19028. (define/public (check-consistent? t1 t2 e)
  19029. (unless (consistent? t1 t2)
  19030. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19031. (define explicit-prim-ops
  19032. (set-union
  19033. (type-predicates)
  19034. (set 'procedure-arity 'eq? 'not 'and 'or
  19035. 'vector 'vector-length 'vector-ref 'vector-set!
  19036. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19037. (define/override (fun-def-type d)
  19038. (match d
  19039. [(Def f params rt info body)
  19040. (define ps
  19041. (for/list ([p params])
  19042. (match p
  19043. [`[,x : ,T] T]
  19044. [(? symbol?) 'Any]
  19045. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19046. `(,@ps -> ,rt)]
  19047. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19048. \end{lstlisting}
  19049. \end{tcolorbox}
  19050. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19051. \label{fig:type-check-Lgradual-aux}
  19052. \end{figure}
  19053. \fi}
  19054. \clearpage
  19055. \section{Interpreting \LangCast{}}
  19056. \label{sec:interp-casts}
  19057. The runtime behavior of casts involving simple types such as
  19058. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19059. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19060. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19061. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19062. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19063. operator, by checking the value's tag and either retrieving
  19064. the underlying integer or signaling an error if the tag is not the
  19065. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19066. %
  19067. Things get more interesting with casts involving
  19068. \racket{function and tuple types}\python{function, tuple, and array types}.
  19069. Consider the cast of the function \code{maybe\_inc} from
  19070. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19071. to
  19072. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19073. shown in figure~\ref{fig:map-maybe_inc}.
  19074. When the \code{maybe\_inc} function flows through
  19075. this cast at runtime, we don't know whether it will return
  19076. an integer, because that depends on the input from the user.
  19077. The \LangCast{} interpreter therefore delays the checking
  19078. of the cast until the function is applied. To do so it
  19079. wraps \code{maybe\_inc} in a new function that casts its parameter
  19080. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19081. casts the return value from \CANYTY{} to \INTTY{}.
  19082. {\if\edition\pythonEd
  19083. %
  19084. There are further complications regarding casts on mutable data
  19085. such as the \code{list} type introduced in
  19086. the challenge assignment of section~\ref{sec:arrays}.
  19087. %
  19088. \fi}
  19089. %
  19090. Consider the example presented in figure~\ref{fig:map-bang} that
  19091. defines a partially typed version of \code{map} whose parameter
  19092. \code{v} has type
  19093. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19094. and that updates \code{v} in place
  19095. instead of returning a new tuple. So, we name this function
  19096. \code{map\_inplace}. We apply \code{map\_inplace} to an
  19097. \racket{tuple}\python{array} of integers, so the type checker inserts a
  19098. cast from
  19099. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19100. to
  19101. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19102. A naive way for the \LangCast{} interpreter to cast between
  19103. \racket{tuple}\python{array} types would be a build a new
  19104. \racket{tuple}\python{array}
  19105. whose elements are the result
  19106. of casting each of the original elements to the appropriate target
  19107. type.
  19108. However, this approach is not valid for mutable data structures.
  19109. In the example of figure~\ref{fig:map-bang},
  19110. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19111. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19112. the original one.
  19113. \begin{figure}[tbp]
  19114. \begin{tcolorbox}[colback=white]
  19115. % gradual_test_11.rkt
  19116. {\if\edition\racketEd
  19117. \begin{lstlisting}
  19118. (define (map_inplace [f : (Any -> Any)]
  19119. [v : (Vector Any Any)]) : Void
  19120. (begin
  19121. (vector-set! v 0 (f (vector-ref v 0)))
  19122. (vector-set! v 1 (f (vector-ref v 1)))))
  19123. (define (inc x) (+ x 1))
  19124. (let ([v (vector 0 41)])
  19125. (begin (map_inplace inc v) (vector-ref v 1)))
  19126. \end{lstlisting}
  19127. \fi}
  19128. {\if\edition\pythonEd
  19129. \begin{lstlisting}
  19130. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19131. i = 0
  19132. while i != len(v):
  19133. v[i] = f(v[i])
  19134. i = i + 1
  19135. def inc(x : int) -> int:
  19136. return x + 1
  19137. v = [0, 41]
  19138. map_inplace(inc, v)
  19139. print( v[1] )
  19140. \end{lstlisting}
  19141. \fi}
  19142. \end{tcolorbox}
  19143. \caption{An example involving casts on arrays.}
  19144. \label{fig:map-bang}
  19145. \end{figure}
  19146. Instead the interpreter needs to create a new kind of value, a
  19147. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19148. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19149. and then applies a
  19150. cast to the resulting value. On a write, the proxy casts the argument
  19151. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19152. \racket{
  19153. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19154. \code{0} from \INTTY{} to \CANYTY{}.
  19155. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19156. from \CANYTY{} to \INTTY{}.
  19157. }
  19158. \python{
  19159. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19160. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19161. For the subscript on the left of the assignment,
  19162. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19163. }
  19164. The final category of cast that we need to consider consist of casts between
  19165. the \CANYTY{} type and higher-order types such as functions and
  19166. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  19167. variant of \code{map\_inplace} in which parameter \code{v} does not
  19168. have a type annotation, so it is given type \CANYTY{}. In the call to
  19169. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19170. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19171. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19172. \code{Inject}, but that doesn't work because
  19173. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19174. a flat type. Instead, we must first cast to
  19175. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19176. and then inject to \CANYTY{}.
  19177. \begin{figure}[tbp]
  19178. \begin{tcolorbox}[colback=white]
  19179. {\if\edition\racketEd
  19180. \begin{lstlisting}
  19181. (define (map_inplace [f : (Any -> Any)] v) : Void
  19182. (begin
  19183. (vector-set! v 0 (f (vector-ref v 0)))
  19184. (vector-set! v 1 (f (vector-ref v 1)))))
  19185. (define (inc x) (+ x 1))
  19186. (let ([v (vector 0 41)])
  19187. (begin (map_inplace inc v) (vector-ref v 1)))
  19188. \end{lstlisting}
  19189. \fi}
  19190. {\if\edition\pythonEd
  19191. \begin{lstlisting}
  19192. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19193. i = 0
  19194. while i != len(v):
  19195. v[i] = f(v[i])
  19196. i = i + 1
  19197. def inc(x):
  19198. return x + 1
  19199. v = [0, 41]
  19200. map_inplace(inc, v)
  19201. print( v[1] )
  19202. \end{lstlisting}
  19203. \fi}
  19204. \end{tcolorbox}
  19205. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  19206. \label{fig:map-any}
  19207. \end{figure}
  19208. \begin{figure}[tbp]
  19209. \begin{tcolorbox}[colback=white]
  19210. {\if\edition\racketEd
  19211. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19212. (define/public (apply_cast v s t)
  19213. (match* (s t)
  19214. [(t1 t2) #:when (equal? t1 t2) v]
  19215. [('Any t2)
  19216. (match t2
  19217. [`(,ts ... -> ,rt)
  19218. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19219. (define v^ (apply-project v any->any))
  19220. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19221. [`(Vector ,ts ...)
  19222. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19223. (define v^ (apply-project v vec-any))
  19224. (apply_cast v^ vec-any `(Vector ,@ts))]
  19225. [else (apply-project v t2)])]
  19226. [(t1 'Any)
  19227. (match t1
  19228. [`(,ts ... -> ,rt)
  19229. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19230. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19231. (apply-inject v^ (any-tag any->any))]
  19232. [`(Vector ,ts ...)
  19233. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19234. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19235. (apply-inject v^ (any-tag vec-any))]
  19236. [else (apply-inject v (any-tag t1))])]
  19237. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19238. (define x (gensym 'x))
  19239. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19240. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19241. (define cast-writes
  19242. (for/list ([t1 ts1] [t2 ts2])
  19243. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19244. `(vector-proxy ,(vector v (apply vector cast-reads)
  19245. (apply vector cast-writes)))]
  19246. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19247. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19248. `(function ,xs ,(Cast
  19249. (Apply (Value v)
  19250. (for/list ([x xs][t1 ts1][t2 ts2])
  19251. (Cast (Var x) t2 t1)))
  19252. rt1 rt2) ())]
  19253. ))
  19254. \end{lstlisting}
  19255. \fi}
  19256. {\if\edition\pythonEd
  19257. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19258. def apply_cast(self, value, src, tgt):
  19259. match (src, tgt):
  19260. case (AnyType(), FunctionType(ps2, rt2)):
  19261. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19262. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19263. case (AnyType(), TupleType(ts2)):
  19264. anytup = TupleType([AnyType() for t1 in ts2])
  19265. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19266. case (AnyType(), ListType(t2)):
  19267. anylist = ListType([AnyType() for t1 in ts2])
  19268. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19269. case (AnyType(), AnyType()):
  19270. return value
  19271. case (AnyType(), _):
  19272. return self.apply_project(value, tgt)
  19273. case (FunctionType(ps1,rt1), AnyType()):
  19274. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19275. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19276. case (TupleType(ts1), AnyType()):
  19277. anytup = TupleType([AnyType() for t1 in ts1])
  19278. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19279. case (ListType(t1), AnyType()):
  19280. anylist = ListType(AnyType())
  19281. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19282. case (_, AnyType()):
  19283. return self.apply_inject(value, src)
  19284. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19285. params = [generate_name('x') for p in ps2]
  19286. args = [Cast(Name(x), t2, t1)
  19287. for (x,t1,t2) in zip(params, ps1, ps2)]
  19288. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19289. return Function('cast', params, [Return(body)], {})
  19290. case (TupleType(ts1), TupleType(ts2)):
  19291. x = generate_name('x')
  19292. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19293. for (t1,t2) in zip(ts1,ts2)]
  19294. return ProxiedTuple(value, reads)
  19295. case (ListType(t1), ListType(t2)):
  19296. x = generate_name('x')
  19297. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19298. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19299. return ProxiedList(value, read, write)
  19300. case (t1, t2) if t1 == t2:
  19301. return value
  19302. case (t1, t2):
  19303. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19304. def apply_inject(self, value, src):
  19305. return Tagged(value, self.type_to_tag(src))
  19306. def apply_project(self, value, tgt):
  19307. match value:
  19308. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19309. return val
  19310. case _:
  19311. raise Exception('apply_project, unexpected ' + repr(value))
  19312. \end{lstlisting}
  19313. \fi}
  19314. \end{tcolorbox}
  19315. \caption{The \code{apply\_cast} auxiliary method.}
  19316. \label{fig:apply_cast}
  19317. \end{figure}
  19318. The \LangCast{} interpreter uses an auxiliary function named
  19319. \code{apply\_cast} to cast a value from a source type to a target type,
  19320. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19321. the kinds of casts that we've discussed in this section.
  19322. %
  19323. The definition of the interpreter for \LangCast{} is shown in
  19324. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19325. dispatching to \code{apply\_cast}.
  19326. \racket{To handle the addition of tuple
  19327. proxies, we update the tuple primitives in \code{interp-op} using the
  19328. functions given in figure~\ref{fig:guarded-tuple}.}
  19329. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19330. \begin{figure}[tbp]
  19331. \begin{tcolorbox}[colback=white]
  19332. {\if\edition\racketEd
  19333. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19334. (define interp-Lcast-class
  19335. (class interp-Llambda-class
  19336. (super-new)
  19337. (inherit apply-fun apply-inject apply-project)
  19338. (define/override (interp-op op)
  19339. (match op
  19340. ['vector-length guarded-vector-length]
  19341. ['vector-ref guarded-vector-ref]
  19342. ['vector-set! guarded-vector-set!]
  19343. ['any-vector-ref (lambda (v i)
  19344. (match v [`(tagged ,v^ ,tg)
  19345. (guarded-vector-ref v^ i)]))]
  19346. ['any-vector-set! (lambda (v i a)
  19347. (match v [`(tagged ,v^ ,tg)
  19348. (guarded-vector-set! v^ i a)]))]
  19349. ['any-vector-length (lambda (v)
  19350. (match v [`(tagged ,v^ ,tg)
  19351. (guarded-vector-length v^)]))]
  19352. [else (super interp-op op)]
  19353. ))
  19354. (define/override ((interp-exp env) e)
  19355. (define (recur e) ((interp-exp env) e))
  19356. (match e
  19357. [(Value v) v]
  19358. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19359. [else ((super interp-exp env) e)]))
  19360. ))
  19361. (define (interp-Lcast p)
  19362. (send (new interp-Lcast-class) interp-program p))
  19363. \end{lstlisting}
  19364. \fi}
  19365. {\if\edition\pythonEd
  19366. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19367. class InterpLcast(InterpLany):
  19368. def interp_exp(self, e, env):
  19369. match e:
  19370. case Cast(value, src, tgt):
  19371. v = self.interp_exp(value, env)
  19372. return self.apply_cast(v, src, tgt)
  19373. case ValueExp(value):
  19374. return value
  19375. ...
  19376. case _:
  19377. return super().interp_exp(e, env)
  19378. \end{lstlisting}
  19379. \fi}
  19380. \end{tcolorbox}
  19381. \caption{The interpreter for \LangCast{}.}
  19382. \label{fig:interp-Lcast}
  19383. \end{figure}
  19384. {\if\edition\racketEd
  19385. \begin{figure}[tbp]
  19386. \begin{tcolorbox}[colback=white]
  19387. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19388. (define (guarded-vector-ref vec i)
  19389. (match vec
  19390. [`(vector-proxy ,proxy)
  19391. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19392. (define rd (vector-ref (vector-ref proxy 1) i))
  19393. (apply-fun rd (list val) 'guarded-vector-ref)]
  19394. [else (vector-ref vec i)]))
  19395. (define (guarded-vector-set! vec i arg)
  19396. (match vec
  19397. [`(vector-proxy ,proxy)
  19398. (define wr (vector-ref (vector-ref proxy 2) i))
  19399. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19400. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19401. [else (vector-set! vec i arg)]))
  19402. (define (guarded-vector-length vec)
  19403. (match vec
  19404. [`(vector-proxy ,proxy)
  19405. (guarded-vector-length (vector-ref proxy 0))]
  19406. [else (vector-length vec)]))
  19407. \end{lstlisting}
  19408. %% {\if\edition\pythonEd
  19409. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19410. %% UNDER CONSTRUCTION
  19411. %% \end{lstlisting}
  19412. %% \fi}
  19413. \end{tcolorbox}
  19414. \caption{The \code{guarded-vector} auxiliary functions.}
  19415. \label{fig:guarded-tuple}
  19416. \end{figure}
  19417. \fi}
  19418. {\if\edition\pythonEd
  19419. \section{Overload Resolution}
  19420. \label{sec:gradual-resolution}
  19421. Recall that when we added support for arrays in
  19422. section~\ref{sec:arrays}, the syntax for the array operations were the
  19423. same as for tuple operations (e.g., accessing an element, getting the
  19424. length). So we performed overload resolution, with a pass named
  19425. \code{resolve}, to separate the array and tuple operations. In
  19426. particular, we introduced the primitives \code{array\_load},
  19427. \code{array\_store}, and \code{array\_len}.
  19428. For gradual typing, we further overload these operators to work on
  19429. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19430. updated with new cases for the \CANYTY{} type, translating the element
  19431. access and length operations to the primitives \code{any\_load},
  19432. \code{any\_store}, and \code{any\_len}.
  19433. \fi}
  19434. \section{Cast Insertion}
  19435. \label{sec:gradual-insert-casts}
  19436. In our discussion of type checking of \LangGrad{}, we mentioned how
  19437. the runtime aspect of type checking is carried out by the \code{Cast}
  19438. AST node, which is added to the program by a new pass named
  19439. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19440. language. We now discuss the details of this pass.
  19441. The \code{cast\_insert} pass is closely related to the type checker
  19442. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19443. In particular, the type checker allows implicit casts between
  19444. consistent types. The job of the \code{cast\_insert} pass is to make
  19445. those casts explicit. It does so by inserting
  19446. \code{Cast} nodes into the AST.
  19447. %
  19448. For the most part, the implicit casts occur in places where the type
  19449. checker checks two types for consistency. Consider the case for
  19450. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19451. checker requires that the type of the left operand is consistent with
  19452. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19453. \code{Cast} around the left operand, converting from its type to
  19454. \INTTY{}. The story is similar for the right operand. It is not always
  19455. necessary to insert a cast, e.g., if the left operand already has type
  19456. \INTTY{} then there is no need for a \code{Cast}.
  19457. Some of the implicit casts are not as straightforward. One such case
  19458. arises with the
  19459. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19460. see that the type checker requires that the two branches have
  19461. consistent types and that type of the conditional expression is the
  19462. meet of the branches' types. In the target language \LangCast{}, both
  19463. branches will need to have the same type, and that type
  19464. will be the type of the conditional expression. Thus, each branch requires
  19465. a \code{Cast} to convert from its type to the meet of the branches' types.
  19466. The case for the function call exhibits another interesting situation. If
  19467. the function expression is of type \CANYTY{}, then it needs to be cast
  19468. to a function type so that it can be used in a function call in
  19469. \LangCast{}. Which function type should it be cast to? The parameter
  19470. and return types are unknown, so we can simply use \CANYTY{} for all
  19471. of them. Furthermore, in \LangCast{} the argument types will need to
  19472. exactly match the parameter types, so we must cast all the arguments
  19473. to type \CANYTY{} (if they are not already of that type).
  19474. {\if\edition\racketEd
  19475. %
  19476. Likewise, the cases for the tuple operators \code{vector-length},
  19477. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19478. where the tuple expression is of type \CANYTY{}. Instead of
  19479. handling these situations with casts, we recommend translating
  19480. the special-purpose variants of the tuple operators that handle
  19481. tuples of type \CANYTY{}: \code{any-vector-length},
  19482. \code{any-vector-ref}, and \code{any-vector-set!}.
  19483. %
  19484. \fi}
  19485. \section{Lower Casts}
  19486. \label{sec:lower_casts}
  19487. The next step in the journey toward x86 is the \code{lower\_casts}
  19488. pass that translates the casts in \LangCast{} to the lower-level
  19489. \code{Inject} and \code{Project} operators and new operators for
  19490. proxies, extending the \LangLam{} language to \LangProxy{}.
  19491. The \LangProxy{} language can also be described as an extension of
  19492. \LangAny{}, with the addition of proxies. We recommend creating an
  19493. auxiliary function named \code{lower\_cast} that takes an expression
  19494. (in \LangCast{}), a source type, and a target type and translates it
  19495. to an expression in \LangProxy{}.
  19496. The \code{lower\_cast} function can follow a code structure similar to
  19497. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19498. the interpreter for \LangCast{}, because it must handle the same cases
  19499. as \code{apply\_cast} and it needs to mimic the behavior of
  19500. \code{apply\_cast}. The most interesting cases concern
  19501. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19502. {\if\edition\racketEd
  19503. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19504. type to another tuple type is accomplished by creating a proxy that
  19505. intercepts the operations on the underlying tuple. Here we make the
  19506. creation of the proxy explicit with the \code{vector-proxy} AST
  19507. node. It takes three arguments: the first is an expression for the
  19508. tuple, the second is tuple of functions for casting an element that is
  19509. being read from the tuple, and the third is a tuple of functions for
  19510. casting an element that is being written to the array. You can create
  19511. the functions for reading and writing using lambda expressions. Also,
  19512. as we show in the next section, we need to differentiate these tuples
  19513. of functions from the user-created ones, so we recommend using a new
  19514. AST node named \code{raw-vector} instead of \code{vector}.
  19515. %
  19516. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19517. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19518. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19519. \fi}
  19520. {\if\edition\pythonEd
  19521. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19522. type to another array type is accomplished by creating a proxy that
  19523. intercepts the operations on the underlying array. Here we make the
  19524. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19525. takes fives arguments: the first is an expression for the array, the
  19526. second is a function for casting an element that is being read from
  19527. the array, the third is a function for casting an element that is
  19528. being written to the array, the fourth is the type of the underlying
  19529. array, and the fifth is the type of the proxied array. You can create
  19530. the functions for reading and writing using lambda expressions.
  19531. A cast between two tuple types can be handled in a similar manner. We
  19532. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19533. immutable, so there is no need for a function to cast the value during
  19534. a write. Because there is a separate element type for each slot in
  19535. the tuple, we need not just one function for casting during a read,
  19536. but instead a tuple of functions.
  19537. %
  19538. Also, as we show in the next section, we need to differentiate these
  19539. tuples from the user-created ones, so we recommend using a new AST
  19540. node named \code{RawTuple} instead of \code{Tuple} to create the
  19541. tuples of functions.
  19542. %
  19543. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19544. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19545. that involved casting an array of integers to an array of \CANYTY{}.
  19546. \fi}
  19547. \begin{figure}[tbp]
  19548. \begin{tcolorbox}[colback=white]
  19549. {\if\edition\racketEd
  19550. \begin{lstlisting}
  19551. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19552. (begin
  19553. (vector-set! v 0 (f (vector-ref v 0)))
  19554. (vector-set! v 1 (f (vector-ref v 1)))))
  19555. (define (inc [x : Any]) : Any
  19556. (inject (+ (project x Integer) 1) Integer))
  19557. (let ([v (vector 0 41)])
  19558. (begin
  19559. (map_inplace inc (vector-proxy v
  19560. (raw-vector (lambda: ([x9 : Integer]) : Any
  19561. (inject x9 Integer))
  19562. (lambda: ([x9 : Integer]) : Any
  19563. (inject x9 Integer)))
  19564. (raw-vector (lambda: ([x9 : Any]) : Integer
  19565. (project x9 Integer))
  19566. (lambda: ([x9 : Any]) : Integer
  19567. (project x9 Integer)))))
  19568. (vector-ref v 1)))
  19569. \end{lstlisting}
  19570. \fi}
  19571. {\if\edition\pythonEd
  19572. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19573. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19574. i = 0
  19575. while i != array_len(v):
  19576. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19577. i = (i + 1)
  19578. def inc(x : int) -> int:
  19579. return (x + 1)
  19580. def main() -> int:
  19581. v = [0, 41]
  19582. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19583. print(array_load(v, 1))
  19584. return 0
  19585. \end{lstlisting}
  19586. \fi}
  19587. \end{tcolorbox}
  19588. \caption{Output of \code{lower\_casts} on the example shown in
  19589. figure~\ref{fig:map-bang}.}
  19590. \label{fig:map-bang-lower-cast}
  19591. \end{figure}
  19592. A cast from one function type to another function type is accomplished
  19593. by generating a \code{lambda} whose parameter and return types match
  19594. the target function type. The body of the \code{lambda} should cast
  19595. the parameters from the target type to the source type. (Yes,
  19596. backward! Functions are contravariant\index{subject}{contravariant}
  19597. in the parameters.). Afterward, call the underlying function and then
  19598. cast the result from the source return type to the target return type.
  19599. Figure~\ref{fig:map-lower-cast} shows the output of the
  19600. \code{lower\_casts} pass on the \code{map} example give in
  19601. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19602. call to \code{map} is wrapped in a \code{lambda}.
  19603. \begin{figure}[tbp]
  19604. \begin{tcolorbox}[colback=white]
  19605. {\if\edition\racketEd
  19606. \begin{lstlisting}
  19607. (define (map [f : (Integer -> Integer)]
  19608. [v : (Vector Integer Integer)])
  19609. : (Vector Integer Integer)
  19610. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19611. (define (inc [x : Any]) : Any
  19612. (inject (+ (project x Integer) 1) Integer))
  19613. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19614. (project (inc (inject x9 Integer)) Integer))
  19615. (vector 0 41)) 1)
  19616. \end{lstlisting}
  19617. \fi}
  19618. {\if\edition\pythonEd
  19619. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19620. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19621. return (f(v[0]), f(v[1]),)
  19622. def inc(x : any) -> any:
  19623. return inject((project(x, int) + 1), int)
  19624. def main() -> int:
  19625. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19626. print(t[1])
  19627. return 0
  19628. \end{lstlisting}
  19629. \fi}
  19630. \end{tcolorbox}
  19631. \caption{Output of \code{lower\_casts} on the example shown in
  19632. figure~\ref{fig:gradual-map}.}
  19633. \label{fig:map-lower-cast}
  19634. \end{figure}
  19635. \section{Differentiate Proxies}
  19636. \label{sec:differentiate-proxies}
  19637. So far, the responsibility of differentiating tuples and tuple proxies
  19638. has been the job of the interpreter.
  19639. %
  19640. \racket{For example, the interpreter for \LangCast{} implements
  19641. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19642. figure~\ref{fig:guarded-tuple}.}
  19643. %
  19644. In the \code{differentiate\_proxies} pass we shift this responsibility
  19645. to the generated code.
  19646. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19647. we used the type \TUPLETYPENAME{} for both
  19648. real tuples and tuple proxies.
  19649. \python{Similarly, we use the type \code{list} for both arrays and
  19650. array proxies.}
  19651. In \LangPVec{} we return the
  19652. \TUPLETYPENAME{} type to its original
  19653. meaning, as the type of just tuples, and we introduce a new type,
  19654. \PTUPLETYNAME{}, whose values
  19655. can be either real tuples or tuple
  19656. proxies.
  19657. %
  19658. {\if\edition\pythonEd
  19659. Likewise, we return the
  19660. \ARRAYTYPENAME{} type to its original
  19661. meaning, as the type of arrays, and we introduce a new type,
  19662. \PARRAYTYNAME{}, whose values
  19663. can be either arrays or array proxies.
  19664. These new types come with a suite of new primitive operations.
  19665. \fi}
  19666. {\if\edition\racketEd
  19667. A tuple proxy is represented by a tuple containing three things: (1) the
  19668. underlying tuple, (2) a tuple of functions for casting elements that
  19669. are read from the tuple, and (3) a tuple of functions for casting
  19670. values to be written to the tuple. So, we define the following
  19671. abbreviation for the type of a tuple proxy:
  19672. \[
  19673. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19674. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19675. \]
  19676. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19677. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19678. %
  19679. Next we describe each of the new primitive operations.
  19680. \begin{description}
  19681. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19682. (\key{PVector} $T \ldots$)]\ \\
  19683. %
  19684. This operation brands a vector as a value of the \code{PVector} type.
  19685. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19686. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19687. %
  19688. This operation brands a vector proxy as value of the \code{PVector} type.
  19689. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19690. \BOOLTY{}] \ \\
  19691. %
  19692. This returns true if the value is a tuple proxy and false if it is a
  19693. real tuple.
  19694. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19695. (\key{Vector} $T \ldots$)]\ \\
  19696. %
  19697. Assuming that the input is a tuple, this operation returns the
  19698. tuple.
  19699. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19700. $\to$ \BOOLTY{}]\ \\
  19701. %
  19702. Given a tuple proxy, this operation returns the length of the tuple.
  19703. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19704. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19705. %
  19706. Given a tuple proxy, this operation returns the $i$th element of the
  19707. tuple.
  19708. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19709. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19710. Given a tuple proxy, this operation writes a value to the $i$th element
  19711. of the tuple.
  19712. \end{description}
  19713. \fi}
  19714. {\if\edition\pythonEd
  19715. %
  19716. A tuple proxy is represented by a tuple containing 1) the underlying
  19717. tuple and 2) a tuple of functions for casting elements that are read
  19718. from the tuple. The \LangPVec{} language includes the following AST
  19719. classes and primitive functions.
  19720. \begin{description}
  19721. \item[\code{InjectTuple}] \ \\
  19722. %
  19723. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19724. \item[\code{InjectTupleProxy}]\ \\
  19725. %
  19726. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19727. \item[\code{is\_tuple\_proxy}]\ \\
  19728. %
  19729. This primitive returns true if the value is a tuple proxy and false
  19730. if it is a tuple.
  19731. \item[\code{project\_tuple}]\ \\
  19732. %
  19733. Converts a tuple that is branded as \PTUPLETYNAME{}
  19734. back to a tuple.
  19735. \item[\code{proxy\_tuple\_len}]\ \\
  19736. %
  19737. Given a tuple proxy, returns the length of the underlying tuple.
  19738. \item[\code{proxy\_tuple\_load}]\ \\
  19739. %
  19740. Given a tuple proxy, returns the $i$th element of the underlying
  19741. tuple.
  19742. \end{description}
  19743. An array proxy is represented by a tuple containing 1) the underlying
  19744. array, 2) a function for casting elements that are read from the
  19745. array, and 3) a function for casting elements that are written to the
  19746. array. The \LangPVec{} language includes the following AST classes
  19747. and primitive functions.
  19748. \begin{description}
  19749. \item[\code{InjectList}]\ \\
  19750. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19751. \item[\code{InjectListProxy}]\ \\
  19752. %
  19753. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19754. \item[\code{is\_array\_proxy}]\ \\
  19755. %
  19756. Returns true if the value is a array proxy and false if it is an
  19757. array.
  19758. \item[\code{project\_array}]\ \\
  19759. %
  19760. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19761. array.
  19762. \item[\code{proxy\_array\_len}]\ \\
  19763. %
  19764. Given a array proxy, returns the length of the underlying array.
  19765. \item[\code{proxy\_array\_load}]\ \\
  19766. %
  19767. Given a array proxy, returns the $i$th element of the underlying
  19768. array.
  19769. \item[\code{proxy\_array\_store}]\ \\
  19770. %
  19771. Given an array proxy, writes a value to the $i$th element of the
  19772. underlying array.
  19773. \end{description}
  19774. \fi}
  19775. Now we discuss the translation that differentiates tuples and arrays
  19776. from proxies. First, every type annotation in the program is
  19777. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19778. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19779. places. For example, we wrap every tuple creation with an
  19780. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19781. %
  19782. {\if\edition\racketEd
  19783. \begin{minipage}{0.96\textwidth}
  19784. \begin{lstlisting}
  19785. (vector |$e_1 \ldots e_n$|)
  19786. |$\Rightarrow$|
  19787. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19788. \end{lstlisting}
  19789. \end{minipage}
  19790. \fi}
  19791. {\if\edition\pythonEd
  19792. \begin{lstlisting}
  19793. Tuple(|$e_1, \ldots, e_n$|)
  19794. |$\Rightarrow$|
  19795. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19796. \end{lstlisting}
  19797. \fi}
  19798. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19799. AST node that we introduced in the previous
  19800. section does not get injected.
  19801. {\if\edition\racketEd
  19802. \begin{lstlisting}
  19803. (raw-vector |$e_1 \ldots e_n$|)
  19804. |$\Rightarrow$|
  19805. (vector |$e'_1 \ldots e'_n$|)
  19806. \end{lstlisting}
  19807. \fi}
  19808. {\if\edition\pythonEd
  19809. \begin{lstlisting}
  19810. RawTuple(|$e_1, \ldots, e_n$|)
  19811. |$\Rightarrow$|
  19812. Tuple(|$e'_1, \ldots, e'_n$|)
  19813. \end{lstlisting}
  19814. \fi}
  19815. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19816. translates as follows:
  19817. %
  19818. {\if\edition\racketEd
  19819. \begin{lstlisting}
  19820. (vector-proxy |$e_1~e_2~e_3$|)
  19821. |$\Rightarrow$|
  19822. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19823. \end{lstlisting}
  19824. \fi}
  19825. {\if\edition\pythonEd
  19826. \begin{lstlisting}
  19827. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19828. |$\Rightarrow$|
  19829. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19830. \end{lstlisting}
  19831. \fi}
  19832. We translate the element access operations into conditional
  19833. expressions that check whether the value is a proxy and then dispatch
  19834. to either the appropriate proxy tuple operation or the regular tuple
  19835. operation.
  19836. {\if\edition\racketEd
  19837. \begin{lstlisting}
  19838. (vector-ref |$e_1$| |$i$|)
  19839. |$\Rightarrow$|
  19840. (let ([|$v~e_1$|])
  19841. (if (proxy? |$v$|)
  19842. (proxy-vector-ref |$v$| |$i$|)
  19843. (vector-ref (project-vector |$v$|) |$i$|)
  19844. \end{lstlisting}
  19845. \fi}
  19846. %
  19847. Note that in the branch for a tuple, we must apply
  19848. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19849. from the tuple.
  19850. The translation of array operations is similar to the ones for tuples.
  19851. \section{Reveal Casts}
  19852. \label{sec:reveal-casts-gradual}
  19853. {\if\edition\racketEd
  19854. Recall that the \code{reveal\_casts} pass
  19855. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19856. \code{Inject} and \code{Project} into lower-level operations.
  19857. %
  19858. In particular, \code{Project} turns into a conditional expression that
  19859. inspects the tag and retrieves the underlying value. Here we need to
  19860. augment the translation of \code{Project} to handle the situation in which
  19861. the target type is \code{PVector}. Instead of using
  19862. \code{vector-length} we need to use \code{proxy-vector-length}.
  19863. \begin{lstlisting}
  19864. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19865. |$\Rightarrow$|
  19866. (let |$\itm{tmp}$| |$e'$|
  19867. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19868. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19869. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19870. (exit)))
  19871. \end{lstlisting}
  19872. \fi}
  19873. %
  19874. {\if\edition\pythonEd
  19875. Recall that the $\itm{tagof}$ function determines the bits used to
  19876. identify values of different types and it is used in the \code{reveal\_casts}
  19877. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19878. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19879. decimal), just like the tuple and array types.
  19880. \fi}
  19881. %
  19882. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19883. \section{Closure Conversion}
  19884. \label{sec:closure-conversion-gradual}
  19885. The auxiliary function that translates type annotations needs to be
  19886. updated to handle the \PTUPLETYNAME{}
  19887. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19888. %
  19889. Otherwise, the only other changes are adding cases that copy the new
  19890. AST nodes.
  19891. \section{Select Instructions}
  19892. \label{sec:select-instructions-gradual}
  19893. Recall that the \code{select\_instructions} pass is responsible for
  19894. lowering the primitive operations into x86 instructions. So, we need
  19895. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19896. to x86. To do so, the first question we need to answer is how to
  19897. differentiate between tuple and tuples proxies\python{, and likewise for
  19898. arrays and array proxies}. We need just one bit to accomplish this;
  19899. we use the bit in position $63$ of the 64-bit tag at the front of
  19900. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19901. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19902. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19903. it that way.
  19904. {\if\edition\racketEd
  19905. \begin{lstlisting}
  19906. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19907. |$\Rightarrow$|
  19908. movq |$e'_1$|, |$\itm{lhs'}$|
  19909. \end{lstlisting}
  19910. \fi}
  19911. {\if\edition\pythonEd
  19912. \begin{lstlisting}
  19913. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19914. |$\Rightarrow$|
  19915. movq |$e'_1$|, |$\itm{lhs'}$|
  19916. \end{lstlisting}
  19917. \fi}
  19918. \python{The translation for \code{InjectList} is also a move instruction.}
  19919. \noindent On the other hand,
  19920. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19921. $63$ to $1$.
  19922. %
  19923. {\if\edition\racketEd
  19924. \begin{lstlisting}
  19925. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19926. |$\Rightarrow$|
  19927. movq |$e'_1$|, %r11
  19928. movq |$(1 << 63)$|, %rax
  19929. orq 0(%r11), %rax
  19930. movq %rax, 0(%r11)
  19931. movq %r11, |$\itm{lhs'}$|
  19932. \end{lstlisting}
  19933. \fi}
  19934. {\if\edition\pythonEd
  19935. \begin{lstlisting}
  19936. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19937. |$\Rightarrow$|
  19938. movq |$e'_1$|, %r11
  19939. movq |$(1 << 63)$|, %rax
  19940. orq 0(%r11), %rax
  19941. movq %rax, 0(%r11)
  19942. movq %r11, |$\itm{lhs'}$|
  19943. \end{lstlisting}
  19944. \fi}
  19945. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19946. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19947. The \racket{\code{proxy?} operation consumes}%
  19948. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19949. consume}
  19950. the information so carefully stashed away by the injections. It
  19951. isolates bit $63$ to tell whether the value is a proxy.
  19952. %
  19953. {\if\edition\racketEd
  19954. \begin{lstlisting}
  19955. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19956. |$\Rightarrow$|
  19957. movq |$e_1'$|, %r11
  19958. movq 0(%r11), %rax
  19959. sarq $63, %rax
  19960. andq $1, %rax
  19961. movq %rax, |$\itm{lhs'}$|
  19962. \end{lstlisting}
  19963. \fi}%
  19964. %
  19965. {\if\edition\pythonEd
  19966. \begin{lstlisting}
  19967. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19968. |$\Rightarrow$|
  19969. movq |$e_1'$|, %r11
  19970. movq 0(%r11), %rax
  19971. sarq $63, %rax
  19972. andq $1, %rax
  19973. movq %rax, |$\itm{lhs'}$|
  19974. \end{lstlisting}
  19975. \fi}%
  19976. %
  19977. The \racket{\code{project-vector} operation is}
  19978. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19979. straightforward to translate, so we leave that to the reader.
  19980. Regarding the element access operations for tuples\python{ and arrays}, the
  19981. runtime provides procedures that implement them (they are recursive
  19982. functions!), so here we simply need to translate these tuple
  19983. operations into the appropriate function call. For example, here is
  19984. the translation for
  19985. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19986. {\if\edition\racketEd
  19987. \begin{minipage}{0.96\textwidth}
  19988. \begin{lstlisting}
  19989. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19990. |$\Rightarrow$|
  19991. movq |$e_1'$|, %rdi
  19992. movq |$e_2'$|, %rsi
  19993. callq proxy_vector_ref
  19994. movq %rax, |$\itm{lhs'}$|
  19995. \end{lstlisting}
  19996. \end{minipage}
  19997. \fi}
  19998. {\if\edition\pythonEd
  19999. \begin{lstlisting}
  20000. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20001. |$\Rightarrow$|
  20002. movq |$e_1'$|, %rdi
  20003. movq |$e_2'$|, %rsi
  20004. callq proxy_vector_ref
  20005. movq %rax, |$\itm{lhs'}$|
  20006. \end{lstlisting}
  20007. \fi}
  20008. {\if\edition\pythonEd
  20009. % TODO: revisit the names vecof for python -Jeremy
  20010. We translate
  20011. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20012. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20013. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20014. \fi}
  20015. We have another batch of operations to deal with: those for the
  20016. \CANYTY{} type. Recall that we generate an
  20017. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20018. there is a element access on something of type \CANYTY{}, and
  20019. similarly for
  20020. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20021. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20022. section~\ref{sec:select-Lany} we selected instructions for these
  20023. operations on the basis of the idea that the underlying value was a tuple or
  20024. array. But in the current setting, the underlying value is of type
  20025. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20026. functions to deal with this:
  20027. \code{proxy\_vector\_ref},
  20028. \code{proxy\_vector\_set}, and
  20029. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  20030. to determine whether the value is a proxy, and then
  20031. dispatches to the the appropriate code.
  20032. %
  20033. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20034. can be translated as follows.
  20035. We begin by projecting the underlying value out of the tagged value and
  20036. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20037. {\if\edition\racketEd
  20038. \begin{lstlisting}
  20039. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  20040. |$\Rightarrow$|
  20041. movq |$\neg 111$|, %rdi
  20042. andq |$e_1'$|, %rdi
  20043. movq |$e_2'$|, %rsi
  20044. callq proxy_vector_ref
  20045. movq %rax, |$\itm{lhs'}$|
  20046. \end{lstlisting}
  20047. \fi}
  20048. {\if\edition\pythonEd
  20049. \begin{lstlisting}
  20050. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20051. |$\Rightarrow$|
  20052. movq |$\neg 111$|, %rdi
  20053. andq |$e_1'$|, %rdi
  20054. movq |$e_2'$|, %rsi
  20055. callq proxy_vector_ref
  20056. movq %rax, |$\itm{lhs'}$|
  20057. \end{lstlisting}
  20058. \fi}
  20059. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20060. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20061. are translated in a similar way. Alternatively, you could generate
  20062. instructions to open-code
  20063. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20064. and \code{proxy\_vector\_length} functions.
  20065. \begin{exercise}\normalfont\normalsize
  20066. Implement a compiler for the gradually typed \LangGrad{} language by
  20067. extending and adapting your compiler for \LangLam{}. Create ten new
  20068. partially typed test programs. In addition to testing with these
  20069. new programs, test your compiler on all the tests for \LangLam{}
  20070. and for \LangDyn{}.
  20071. %
  20072. \racket{Sometimes you may get a type checking error on the
  20073. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20074. the \CANYTY{} type around each subexpression that has caused a type
  20075. error. Although \LangDyn{} does not have explicit casts, you can
  20076. induce one by wrapping the subexpression \code{e} with a call to
  20077. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20078. %
  20079. \python{Sometimes you may get a type checking error on the
  20080. \LangDyn{} programs but you can adapt them by inserting a
  20081. temporary variable of type \CANYTY{} that is initialized with the
  20082. troublesome expression.}
  20083. \end{exercise}
  20084. \begin{figure}[p]
  20085. \begin{tcolorbox}[colback=white]
  20086. {\if\edition\racketEd
  20087. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20088. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20089. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20090. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20091. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20092. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20093. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20094. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20095. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20096. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20097. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20098. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20099. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20100. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20101. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20102. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20103. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20104. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20105. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20106. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20107. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20108. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20109. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20110. \path[->,bend left=15] (Lgradual) edge [above] node
  20111. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20112. \path[->,bend left=15] (Lgradual2) edge [above] node
  20113. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20114. \path[->,bend left=15] (Lgradual3) edge [above] node
  20115. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20116. \path[->,bend left=15] (Lgradual4) edge [left] node
  20117. {\ttfamily\footnotesize shrink} (Lgradualr);
  20118. \path[->,bend left=15] (Lgradualr) edge [above] node
  20119. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20120. \path[->,bend right=15] (Lgradualp) edge [above] node
  20121. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20122. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20123. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20124. \path[->,bend right=15] (Llambdapp) edge [above] node
  20125. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20126. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20127. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20128. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20129. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20130. \path[->,bend left=15] (F1-2) edge [above] node
  20131. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20132. \path[->,bend left=15] (F1-3) edge [left] node
  20133. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20134. \path[->,bend left=15] (F1-4) edge [below] node
  20135. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20136. \path[->,bend right=15] (F1-5) edge [above] node
  20137. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20138. \path[->,bend right=15] (F1-6) edge [above] node
  20139. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20140. \path[->,bend right=15] (C3-2) edge [right] node
  20141. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20142. \path[->,bend right=15] (x86-2) edge [right] node
  20143. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20144. \path[->,bend right=15] (x86-2-1) edge [below] node
  20145. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20146. \path[->,bend right=15] (x86-2-2) edge [right] node
  20147. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20148. \path[->,bend left=15] (x86-3) edge [above] node
  20149. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20150. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20151. \end{tikzpicture}
  20152. \fi}
  20153. {\if\edition\pythonEd
  20154. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20155. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20156. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20157. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20158. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20159. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20160. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20161. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20162. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20163. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20164. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20165. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20166. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20167. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20168. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20169. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20170. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20171. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20172. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20173. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20174. \path[->,bend left=15] (Lgradual) edge [above] node
  20175. {\ttfamily\footnotesize shrink} (Lgradual2);
  20176. \path[->,bend left=15] (Lgradual2) edge [above] node
  20177. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20178. \path[->,bend left=15] (Lgradual3) edge [above] node
  20179. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20180. \path[->,bend left=15] (Lgradual4) edge [left] node
  20181. {\ttfamily\footnotesize resolve} (Lgradualr);
  20182. \path[->,bend left=15] (Lgradualr) edge [below] node
  20183. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20184. \path[->,bend right=15] (Lgradualp) edge [above] node
  20185. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20186. \path[->,bend right=15] (Llambdapp) edge [above] node
  20187. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20188. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20189. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20190. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20191. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20192. \path[->,bend left=15] (F1-1) edge [above] node
  20193. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20194. \path[->,bend left=15] (F1-2) edge [above] node
  20195. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20196. \path[->,bend left=15] (F1-3) edge [right] node
  20197. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20198. \path[->,bend right=15] (F1-5) edge [above] node
  20199. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20200. \path[->,bend right=15] (F1-6) edge [above] node
  20201. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20202. \path[->,bend right=15] (C3-2) edge [right] node
  20203. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20204. \path[->,bend right=15] (x86-2) edge [below] node
  20205. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20206. \path[->,bend right=15] (x86-3) edge [below] node
  20207. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20208. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20209. \end{tikzpicture}
  20210. \fi}
  20211. \end{tcolorbox}
  20212. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20213. \label{fig:Lgradual-passes}
  20214. \end{figure}
  20215. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20216. needed for the compilation of \LangGrad{}.
  20217. \section{Further Reading}
  20218. This chapter just scratches the surface of gradual typing. The basic
  20219. approach described here is missing two key ingredients that one would
  20220. want in a implementation of gradual typing: blame
  20221. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20222. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20223. problem addressed by blame tracking is that when a cast on a
  20224. higher-order value fails, it often does so at a point in the program
  20225. that is far removed from the original cast. Blame tracking is a
  20226. technique for propagating extra information through casts and proxies
  20227. so that when a cast fails, the error message can point back to the
  20228. original location of the cast in the source program.
  20229. The problem addressed by space-efficient casts also relates to
  20230. higher-order casts. It turns out that in partially typed programs, a
  20231. function or tuple can flow through a great many casts at runtime. With
  20232. the approach described in this chapter, each cast adds another
  20233. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20234. considerable space, but it also makes the function calls and tuple
  20235. operations slow. For example, a partially typed version of quicksort
  20236. could, in the worst case, build a chain of proxies of length $O(n)$
  20237. around the tuple, changing the overall time complexity of the
  20238. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20239. solution to this problem by representing casts using the coercion
  20240. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20241. long chains of proxies by compressing them into a concise normal
  20242. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20243. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20244. the Grift compiler:
  20245. \begin{center}
  20246. \url{https://github.com/Gradual-Typing/Grift}
  20247. \end{center}
  20248. There are also interesting interactions between gradual typing and
  20249. other language features, such as generics, information-flow types, and
  20250. type inference, to name a few. We recommend to the reader the
  20251. online gradual typing bibliography for more material:
  20252. \begin{center}
  20253. \url{http://samth.github.io/gradual-typing-bib/}
  20254. \end{center}
  20255. % TODO: challenge problem:
  20256. % type analysis and type specialization?
  20257. % coercions?
  20258. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20259. \chapter{Generics}
  20260. \label{ch:Lpoly}
  20261. \index{subject}{parametric polymorphism}
  20262. \index{subject}{generics}
  20263. \setcounter{footnote}{0}
  20264. This chapter studies the compilation of
  20265. generics\index{subject}{generics} (aka parametric
  20266. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20267. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20268. enable programmers to make code more reusable by parameterizing
  20269. functions and data structures with respect to the types on which they
  20270. operate. For example, figure~\ref{fig:map-poly} revisits the
  20271. \code{map} example and this time gives it a more fitting type. This
  20272. \code{map} function is parameterized with respect to the element type
  20273. of the tuple. The type of \code{map} is the following generic type
  20274. specified by the \code{All} type with parameter \code{T}:
  20275. \if\edition\racketEd
  20276. \begin{lstlisting}
  20277. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20278. \end{lstlisting}
  20279. \fi
  20280. \if\edition\pythonEd
  20281. \begin{lstlisting}
  20282. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20283. \end{lstlisting}
  20284. \fi
  20285. %
  20286. The idea is that \code{map} can be used at \emph{all} choices of a
  20287. type for parameter \code{T}. In the example shown in
  20288. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20289. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20290. \code{T}, but we could have just as well applied \code{map} to a tuple
  20291. of Booleans.
  20292. %
  20293. A \emph{monomorphic} function is simply one that is not generic.
  20294. %
  20295. We use the term \emph{instantiation} for the process (within the
  20296. language implementation) of turning a generic function into a
  20297. monomorphic one, where the type parameters have been replaced by
  20298. types.
  20299. \if\edition\pythonEd
  20300. %
  20301. In Python, when writing a generic function such as \code{map}, one
  20302. does not explicitly write down its generic type (using \code{All}).
  20303. Instead, the fact that it is generic is implied by the use of type
  20304. variables (such as \code{T}) in the type annotations of its
  20305. parameters.
  20306. %
  20307. \fi
  20308. \begin{figure}[tbp]
  20309. % poly_test_2.rkt
  20310. \begin{tcolorbox}[colback=white]
  20311. \if\edition\racketEd
  20312. \begin{lstlisting}
  20313. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20314. (define (map f v)
  20315. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20316. (define (inc [x : Integer]) : Integer (+ x 1))
  20317. (vector-ref (map inc (vector 0 41)) 1)
  20318. \end{lstlisting}
  20319. \fi
  20320. \if\edition\pythonEd
  20321. \begin{lstlisting}
  20322. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20323. return (f(tup[0]), f(tup[1]))
  20324. def add1(x : int) -> int:
  20325. return x + 1
  20326. t = map(add1, (0, 41))
  20327. print(t[1])
  20328. \end{lstlisting}
  20329. \fi
  20330. \end{tcolorbox}
  20331. \caption{A generic version of the \code{map} function.}
  20332. \label{fig:map-poly}
  20333. \end{figure}
  20334. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20335. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20336. shows the definition of the abstract syntax.
  20337. %
  20338. \if\edition\racketEd
  20339. We add a second form for function definitions in which a type
  20340. declaration comes before the \code{define}. In the abstract syntax,
  20341. the return type in the \code{Def} is \CANYTY{}, but that should be
  20342. ignored in favor of the return type in the type declaration. (The
  20343. \CANYTY{} comes from using the same parser as discussed in
  20344. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20345. enables the use of an \code{All} type for a function, thereby making
  20346. it generic.
  20347. \fi
  20348. %
  20349. The grammar for types is extended to include the type of a generic
  20350. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  20351. abstract syntax)}.
  20352. \newcommand{\LpolyGrammarRacket}{
  20353. \begin{array}{lcl}
  20354. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20355. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20356. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20357. \end{array}
  20358. }
  20359. \newcommand{\LpolyASTRacket}{
  20360. \begin{array}{lcl}
  20361. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20362. \Def &::=& \DECL{\Var}{\Type} \\
  20363. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20364. \end{array}
  20365. }
  20366. \newcommand{\LpolyGrammarPython}{
  20367. \begin{array}{lcl}
  20368. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20369. \end{array}
  20370. }
  20371. \newcommand{\LpolyASTPython}{
  20372. \begin{array}{lcl}
  20373. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20374. \MID \key{GenericVar}\LP\Var\RP
  20375. \end{array}
  20376. }
  20377. \begin{figure}[tp]
  20378. \centering
  20379. \begin{tcolorbox}[colback=white]
  20380. \footnotesize
  20381. \if\edition\racketEd
  20382. \[
  20383. \begin{array}{l}
  20384. \gray{\LintGrammarRacket{}} \\ \hline
  20385. \gray{\LvarGrammarRacket{}} \\ \hline
  20386. \gray{\LifGrammarRacket{}} \\ \hline
  20387. \gray{\LwhileGrammarRacket} \\ \hline
  20388. \gray{\LtupGrammarRacket} \\ \hline
  20389. \gray{\LfunGrammarRacket} \\ \hline
  20390. \gray{\LlambdaGrammarRacket} \\ \hline
  20391. \LpolyGrammarRacket \\
  20392. \begin{array}{lcl}
  20393. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20394. \end{array}
  20395. \end{array}
  20396. \]
  20397. \fi
  20398. \if\edition\pythonEd
  20399. \[
  20400. \begin{array}{l}
  20401. \gray{\LintGrammarPython{}} \\ \hline
  20402. \gray{\LvarGrammarPython{}} \\ \hline
  20403. \gray{\LifGrammarPython{}} \\ \hline
  20404. \gray{\LwhileGrammarPython} \\ \hline
  20405. \gray{\LtupGrammarPython} \\ \hline
  20406. \gray{\LfunGrammarPython} \\ \hline
  20407. \gray{\LlambdaGrammarPython} \\\hline
  20408. \LpolyGrammarPython \\
  20409. \begin{array}{lcl}
  20410. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20411. \end{array}
  20412. \end{array}
  20413. \]
  20414. \fi
  20415. \end{tcolorbox}
  20416. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20417. (figure~\ref{fig:Llam-concrete-syntax}).}
  20418. \label{fig:Lpoly-concrete-syntax}
  20419. \end{figure}
  20420. \begin{figure}[tp]
  20421. \centering
  20422. \begin{tcolorbox}[colback=white]
  20423. \footnotesize
  20424. \if\edition\racketEd
  20425. \[
  20426. \begin{array}{l}
  20427. \gray{\LintOpAST} \\ \hline
  20428. \gray{\LvarASTRacket{}} \\ \hline
  20429. \gray{\LifASTRacket{}} \\ \hline
  20430. \gray{\LwhileASTRacket{}} \\ \hline
  20431. \gray{\LtupASTRacket{}} \\ \hline
  20432. \gray{\LfunASTRacket} \\ \hline
  20433. \gray{\LlambdaASTRacket} \\ \hline
  20434. \LpolyASTRacket \\
  20435. \begin{array}{lcl}
  20436. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20437. \end{array}
  20438. \end{array}
  20439. \]
  20440. \fi
  20441. \if\edition\pythonEd
  20442. \[
  20443. \begin{array}{l}
  20444. \gray{\LintASTPython} \\ \hline
  20445. \gray{\LvarASTPython{}} \\ \hline
  20446. \gray{\LifASTPython{}} \\ \hline
  20447. \gray{\LwhileASTPython{}} \\ \hline
  20448. \gray{\LtupASTPython{}} \\ \hline
  20449. \gray{\LfunASTPython} \\ \hline
  20450. \gray{\LlambdaASTPython} \\ \hline
  20451. \LpolyASTPython \\
  20452. \begin{array}{lcl}
  20453. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20454. \end{array}
  20455. \end{array}
  20456. \]
  20457. \fi
  20458. \end{tcolorbox}
  20459. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20460. (figure~\ref{fig:Llam-syntax}).}
  20461. \label{fig:Lpoly-syntax}
  20462. \end{figure}
  20463. By including the \code{All} type in the $\Type$ nonterminal of the
  20464. grammar we choose to make generics first class, which has interesting
  20465. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20466. not include syntax for the \code{All} type. It is inferred for functions whose
  20467. type annotations contain type variables.} Many languages with generics, such as
  20468. C++~\citep{stroustrup88:_param_types} and Standard
  20469. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20470. may be helpful to see an example of first-class generics in action. In
  20471. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20472. whose parameter is a generic function. Indeed, because the grammar for
  20473. $\Type$ includes the \code{All} type, a generic function may also be
  20474. returned from a function or stored inside a tuple. The body of
  20475. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20476. and also to an integer, which would not be possible if \code{f} were
  20477. not generic.
  20478. \begin{figure}[tbp]
  20479. \begin{tcolorbox}[colback=white]
  20480. \if\edition\racketEd
  20481. \begin{lstlisting}
  20482. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20483. (define (apply_twice f)
  20484. (if (f #t) (f 42) (f 777)))
  20485. (: id (All (T) (T -> T)))
  20486. (define (id x) x)
  20487. (apply_twice id)
  20488. \end{lstlisting}
  20489. \fi
  20490. \if\edition\pythonEd
  20491. \begin{lstlisting}
  20492. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20493. if f(True):
  20494. return f(42)
  20495. else:
  20496. return f(777)
  20497. def id(x: T) -> T:
  20498. return x
  20499. print(apply_twice(id))
  20500. \end{lstlisting}
  20501. \fi
  20502. \end{tcolorbox}
  20503. \caption{An example illustrating first-class generics.}
  20504. \label{fig:apply-twice}
  20505. \end{figure}
  20506. The type checker for \LangPoly{} shown in
  20507. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20508. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20509. \if\edition\pythonEd
  20510. %
  20511. Regarding function definitions, if the type annotations on its
  20512. parameters contain generic variables, then the function is generic and
  20513. therefore its type is an \code{All} type wrapped around a function
  20514. type. Otherwise the function is monomorphic and its type is simply
  20515. a function type.
  20516. %
  20517. \fi
  20518. The type checking of a function application is extended to handle the
  20519. case in which the operator expression is a generic function. In that case
  20520. the type arguments are deduced by matching the type of the parameters
  20521. with the types of the arguments.
  20522. %
  20523. The \code{match\_types} auxiliary function
  20524. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20525. recursively descending through a parameter type \code{param\_ty} and
  20526. the corresponding argument type \code{arg\_ty}, making sure that they
  20527. are equal except when there is a type parameter in the parameter
  20528. type. Upon encountering a type parameter for the first time, the
  20529. algorithm deduces an association of the type parameter to the
  20530. corresponding part of the argument type. If it is not the first time
  20531. that the type parameter has been encountered, the algorithm looks up
  20532. its deduced type and makes sure that it is equal to the corresponding
  20533. part of the argument type. The return type of the application is the
  20534. return type of the generic function with the type parameters
  20535. replaced by the deduced type arguments, using the
  20536. \code{substitute\_type} auxiliary function, which is also listed in
  20537. figure~\ref{fig:type-check-Lpoly-aux}.
  20538. The type checker extends type equality to handle the \code{All} type.
  20539. This is not quite as simple as for other types, such as function and
  20540. tuple types, because two \code{All} types can be syntactically
  20541. different even though they are equivalent. For example,
  20542. %
  20543. \racket{\code{(All (T) (T -> T))}}
  20544. \python{\code{All[[T], Callable[[T], T]]}}
  20545. is equivalent to
  20546. \racket{\code{(All (U) (U -> U))}}
  20547. \python{\code{All[[U], Callable[[U], U]]}}.
  20548. %
  20549. Two generic types should be considered equal if they differ only in
  20550. the choice of the names of the type parameters. The definition of type
  20551. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20552. parameters in one type to match the type parameters of the other type.
  20553. \if\edition\racketEd
  20554. %
  20555. The type checker also ensures that only defined type variables appear
  20556. in type annotations. The \code{check\_well\_formed} function for which
  20557. the definition is shown in figure~\ref{fig:well-formed-types}
  20558. recursively inspects a type, making sure that each type variable has
  20559. been defined.
  20560. %
  20561. \fi
  20562. \begin{figure}[tbp]
  20563. \begin{tcolorbox}[colback=white]
  20564. \if\edition\racketEd
  20565. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20566. (define type-check-poly-class
  20567. (class type-check-Llambda-class
  20568. (super-new)
  20569. (inherit check-type-equal?)
  20570. (define/override (type-check-apply env e1 es)
  20571. (define-values (e^ ty) ((type-check-exp env) e1))
  20572. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20573. ((type-check-exp env) e)))
  20574. (match ty
  20575. [`(,ty^* ... -> ,rt)
  20576. (for ([arg-ty ty*] [param-ty ty^*])
  20577. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20578. (values e^ es^ rt)]
  20579. [`(All ,xs (,tys ... -> ,rt))
  20580. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20581. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20582. (match_types env^^ param-ty arg-ty)))
  20583. (define targs
  20584. (for/list ([x xs])
  20585. (match (dict-ref env^^ x (lambda () #f))
  20586. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20587. x (Apply e1 es))]
  20588. [ty ty])))
  20589. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20590. [else (error 'type-check "expected a function, not ~a" ty)]))
  20591. (define/override ((type-check-exp env) e)
  20592. (match e
  20593. [(Lambda `([,xs : ,Ts] ...) rT body)
  20594. (for ([T Ts]) ((check_well_formed env) T))
  20595. ((check_well_formed env) rT)
  20596. ((super type-check-exp env) e)]
  20597. [(HasType e1 ty)
  20598. ((check_well_formed env) ty)
  20599. ((super type-check-exp env) e)]
  20600. [else ((super type-check-exp env) e)]))
  20601. (define/override ((type-check-def env) d)
  20602. (verbose 'type-check "poly/def" d)
  20603. (match d
  20604. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20605. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20606. (for ([p ps]) ((check_well_formed ts-env) p))
  20607. ((check_well_formed ts-env) rt)
  20608. (define new-env (append ts-env (map cons xs ps) env))
  20609. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20610. (check-type-equal? ty^ rt body)
  20611. (Generic ts (Def f p:t* rt info body^))]
  20612. [else ((super type-check-def env) d)]))
  20613. (define/override (type-check-program p)
  20614. (match p
  20615. [(Program info body)
  20616. (type-check-program (ProgramDefsExp info '() body))]
  20617. [(ProgramDefsExp info ds body)
  20618. (define ds^ (combine-decls-defs ds))
  20619. (define new-env (for/list ([d ds^])
  20620. (cons (def-name d) (fun-def-type d))))
  20621. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20622. (define-values (body^ ty) ((type-check-exp new-env) body))
  20623. (check-type-equal? ty 'Integer body)
  20624. (ProgramDefsExp info ds^^ body^)]))
  20625. ))
  20626. \end{lstlisting}
  20627. \fi
  20628. \if\edition\pythonEd
  20629. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20630. def type_check_exp(self, e, env):
  20631. match e:
  20632. case Call(Name(f), args) if f in builtin_functions:
  20633. return super().type_check_exp(e, env)
  20634. case Call(func, args):
  20635. func_t = self.type_check_exp(func, env)
  20636. func.has_type = func_t
  20637. match func_t:
  20638. case AllType(ps, FunctionType(p_tys, rt)):
  20639. for arg in args:
  20640. arg.has_type = self.type_check_exp(arg, env)
  20641. arg_tys = [arg.has_type for arg in args]
  20642. deduced = {}
  20643. for (p, a) in zip(p_tys, arg_tys):
  20644. self.match_types(p, a, deduced, e)
  20645. return self.substitute_type(rt, deduced)
  20646. case _:
  20647. return super().type_check_exp(e, env)
  20648. case _:
  20649. return super().type_check_exp(e, env)
  20650. def type_check(self, p):
  20651. match p:
  20652. case Module(body):
  20653. env = {}
  20654. for s in body:
  20655. match s:
  20656. case FunctionDef(name, params, bod, dl, returns, comment):
  20657. params_t = [t for (x,t) in params]
  20658. ty_params = set()
  20659. for t in params_t:
  20660. ty_params |$\mid$|= self.generic_variables(t)
  20661. ty = FunctionType(params_t, returns)
  20662. if len(ty_params) > 0:
  20663. ty = AllType(list(ty_params), ty)
  20664. env[name] = ty
  20665. self.check_stmts(body, IntType(), env)
  20666. case _:
  20667. raise Exception('type_check: unexpected ' + repr(p))
  20668. \end{lstlisting}
  20669. \fi
  20670. \end{tcolorbox}
  20671. \caption{Type checker for the \LangPoly{} language.}
  20672. \label{fig:type-check-Lpoly}
  20673. \end{figure}
  20674. \begin{figure}[tbp]
  20675. \begin{tcolorbox}[colback=white]
  20676. \if\edition\racketEd
  20677. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20678. (define/override (type-equal? t1 t2)
  20679. (match* (t1 t2)
  20680. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20681. (define env (map cons xs ys))
  20682. (type-equal? (substitute_type env T1) T2)]
  20683. [(other wise)
  20684. (super type-equal? t1 t2)]))
  20685. (define/public (match_types env pt at)
  20686. (match* (pt at)
  20687. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20688. [('Void 'Void) env] [('Any 'Any) env]
  20689. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20690. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20691. (match_types env^ pt1 at1))]
  20692. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20693. (define env^ (match_types env prt art))
  20694. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20695. (match_types env^^ pt1 at1))]
  20696. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20697. (define env^ (append (map cons pxs axs) env))
  20698. (match_types env^ pt1 at1)]
  20699. [((? symbol? x) at)
  20700. (match (dict-ref env x (lambda () #f))
  20701. [#f (error 'type-check "undefined type variable ~a" x)]
  20702. ['Type (cons (cons x at) env)]
  20703. [t^ (check-type-equal? at t^ 'matching) env])]
  20704. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20705. (define/public (substitute_type env pt)
  20706. (match pt
  20707. ['Integer 'Integer] ['Boolean 'Boolean]
  20708. ['Void 'Void] ['Any 'Any]
  20709. [`(Vector ,ts ...)
  20710. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20711. [`(,ts ... -> ,rt)
  20712. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20713. [`(All ,xs ,t)
  20714. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20715. [(? symbol? x) (dict-ref env x)]
  20716. [else (error 'type-check "expected a type not ~a" pt)]))
  20717. (define/public (combine-decls-defs ds)
  20718. (match ds
  20719. ['() '()]
  20720. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20721. (unless (equal? name f)
  20722. (error 'type-check "name mismatch, ~a != ~a" name f))
  20723. (match type
  20724. [`(All ,xs (,ps ... -> ,rt))
  20725. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20726. (cons (Generic xs (Def name params^ rt info body))
  20727. (combine-decls-defs ds^))]
  20728. [`(,ps ... -> ,rt)
  20729. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20730. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20731. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20732. [`(,(Def f params rt info body) . ,ds^)
  20733. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20734. \end{lstlisting}
  20735. \fi
  20736. \if\edition\pythonEd
  20737. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20738. def match_types(self, param_ty, arg_ty, deduced, e):
  20739. match (param_ty, arg_ty):
  20740. case (GenericVar(id), _):
  20741. if id in deduced:
  20742. self.check_type_equal(arg_ty, deduced[id], e)
  20743. else:
  20744. deduced[id] = arg_ty
  20745. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20746. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20747. new_arg_ty = self.substitute_type(arg_ty, rename)
  20748. self.match_types(ty, new_arg_ty, deduced, e)
  20749. case (TupleType(ps), TupleType(ts)):
  20750. for (p, a) in zip(ps, ts):
  20751. self.match_types(p, a, deduced, e)
  20752. case (ListType(p), ListType(a)):
  20753. self.match_types(p, a, deduced, e)
  20754. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20755. for (pp, ap) in zip(pps, aps):
  20756. self.match_types(pp, ap, deduced, e)
  20757. self.match_types(prt, art, deduced, e)
  20758. case (IntType(), IntType()):
  20759. pass
  20760. case (BoolType(), BoolType()):
  20761. pass
  20762. case _:
  20763. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20764. def substitute_type(self, ty, var_map):
  20765. match ty:
  20766. case GenericVar(id):
  20767. return var_map[id]
  20768. case AllType(ps, ty):
  20769. new_map = copy.deepcopy(var_map)
  20770. for p in ps:
  20771. new_map[p] = GenericVar(p)
  20772. return AllType(ps, self.substitute_type(ty, new_map))
  20773. case TupleType(ts):
  20774. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20775. case ListType(ty):
  20776. return ListType(self.substitute_type(ty, var_map))
  20777. case FunctionType(pts, rt):
  20778. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20779. self.substitute_type(rt, var_map))
  20780. case IntType():
  20781. return IntType()
  20782. case BoolType():
  20783. return BoolType()
  20784. case _:
  20785. raise Exception('substitute_type: unexpected ' + repr(ty))
  20786. def check_type_equal(self, t1, t2, e):
  20787. match (t1, t2):
  20788. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20789. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20790. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20791. case (_, _):
  20792. return super().check_type_equal(t1, t2, e)
  20793. \end{lstlisting}
  20794. \fi
  20795. \end{tcolorbox}
  20796. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20797. \label{fig:type-check-Lpoly-aux}
  20798. \end{figure}
  20799. \if\edition\racketEd
  20800. \begin{figure}[tbp]
  20801. \begin{tcolorbox}[colback=white]
  20802. \begin{lstlisting}
  20803. (define/public ((check_well_formed env) ty)
  20804. (match ty
  20805. ['Integer (void)]
  20806. ['Boolean (void)]
  20807. ['Void (void)]
  20808. [(? symbol? a)
  20809. (match (dict-ref env a (lambda () #f))
  20810. ['Type (void)]
  20811. [else (error 'type-check "undefined type variable ~a" a)])]
  20812. [`(Vector ,ts ...)
  20813. (for ([t ts]) ((check_well_formed env) t))]
  20814. [`(,ts ... -> ,t)
  20815. (for ([t ts]) ((check_well_formed env) t))
  20816. ((check_well_formed env) t)]
  20817. [`(All ,xs ,t)
  20818. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20819. ((check_well_formed env^) t)]
  20820. [else (error 'type-check "unrecognized type ~a" ty)]))
  20821. \end{lstlisting}
  20822. \end{tcolorbox}
  20823. \caption{Well-formed types.}
  20824. \label{fig:well-formed-types}
  20825. \end{figure}
  20826. \fi
  20827. % TODO: interpreter for R'_10
  20828. \clearpage
  20829. \section{Compiling Generics}
  20830. \label{sec:compiling-poly}
  20831. Broadly speaking, there are four approaches to compiling generics, as
  20832. follows:
  20833. \begin{description}
  20834. \item[Monomorphization] generates a different version of a generic
  20835. function for each set of type arguments with which it is used,
  20836. producing type-specialized code. This approach results in the most
  20837. efficient code but requires whole-program compilation (no separate
  20838. compilation) and may increase code size. Unfortunately,
  20839. monomorphization is incompatible with first-class generics, because
  20840. it is not always possible to determine which generic functions are
  20841. used with which type arguments during compilation. (It can be done
  20842. at runtime, with just-in-time compilation.) Monomorphization is
  20843. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20844. generic functions in NESL~\citep{Blelloch:1993aa} and
  20845. ML~\citep{Weeks:2006aa}.
  20846. \item[Uniform representation] generates one version of each generic
  20847. function and requires all values to have a common \emph{boxed} format,
  20848. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20849. generic and monomorphic code is compiled similarly to code in a
  20850. dynamically typed language (like \LangDyn{}), in which primitive
  20851. operators require their arguments to be projected from \CANYTY{} and
  20852. their results to be injected into \CANYTY{}. (In object-oriented
  20853. languages, the projection is accomplished via virtual method
  20854. dispatch.) The uniform representation approach is compatible with
  20855. separate compilation and with first-class generics. However, it
  20856. produces the least efficient code because it introduces overhead in
  20857. the entire program. This approach is used in
  20858. Java~\citep{Bracha:1998fk},
  20859. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20860. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20861. \item[Mixed representation] generates one version of each generic
  20862. function, using a boxed representation for type variables. However,
  20863. monomorphic code is compiled as usual (as in \LangLam{}), and
  20864. conversions are performed at the boundaries between monomorphic code
  20865. and polymorphic code (e.g., when a generic function is instantiated
  20866. and called). This approach is compatible with separate compilation
  20867. and first-class generics and maintains efficiency in monomorphic
  20868. code. The trade-off is increased overhead at the boundary between
  20869. monomorphic and generic code. This approach is used in
  20870. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20871. Java 5 with the addition of autoboxing.
  20872. \item[Type passing] uses the unboxed representation in both
  20873. monomorphic and generic code. Each generic function is compiled to a
  20874. single function with extra parameters that describe the type
  20875. arguments. The type information is used by the generated code to
  20876. determine how to access the unboxed values at runtime. This approach is
  20877. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20878. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20879. compilation and first-class generics and maintains the
  20880. efficiency for monomorphic code. There is runtime overhead in
  20881. polymorphic code from dispatching on type information.
  20882. \end{description}
  20883. In this chapter we use the mixed representation approach, partly
  20884. because of its favorable attributes and partly because it is
  20885. straightforward to implement using the tools that we have already
  20886. built to support gradual typing. The work of compiling generic
  20887. functions is performed in two passes, \code{resolve} and
  20888. \code{erase\_types}, that we discuss next. The output of
  20889. \code{erase\_types} is \LangCast{}
  20890. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20891. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20892. \section{Resolve Instantiation}
  20893. \label{sec:generic-resolve}
  20894. Recall that the type checker for \LangPoly{} deduces the type
  20895. arguments at call sites to a generic function. The purpose of the
  20896. \code{resolve} pass is to turn this implicit instantiation into an
  20897. explicit one, by adding \code{inst} nodes to the syntax of the
  20898. intermediate language. An \code{inst} node records the mapping of
  20899. type parameters to type arguments. The semantics of the \code{inst}
  20900. node is to instantiate the result of its first argument, a generic
  20901. function, to produce a monomorphic function. However, because the
  20902. interpreter never analyzes type annotations, instantiation can be a
  20903. no-op and simply return the generic function.
  20904. %
  20905. The output language of the \code{resolve} pass is \LangInst{},
  20906. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20907. \if\edition\racketEd
  20908. The \code{resolve} pass combines the type declaration and polymorphic
  20909. function into a single definition, using the \code{Poly} form, to make
  20910. polymorphic functions more convenient to process in the next pass of the
  20911. compiler.
  20912. \fi
  20913. \newcommand{\LinstASTRacket}{
  20914. \begin{array}{lcl}
  20915. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20916. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20917. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20918. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20919. \end{array}
  20920. }
  20921. \newcommand{\LinstASTPython}{
  20922. \begin{array}{lcl}
  20923. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20924. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20925. \end{array}
  20926. }
  20927. \begin{figure}[tp]
  20928. \centering
  20929. \begin{tcolorbox}[colback=white]
  20930. \small
  20931. \if\edition\racketEd
  20932. \[
  20933. \begin{array}{l}
  20934. \gray{\LintOpAST} \\ \hline
  20935. \gray{\LvarASTRacket{}} \\ \hline
  20936. \gray{\LifASTRacket{}} \\ \hline
  20937. \gray{\LwhileASTRacket{}} \\ \hline
  20938. \gray{\LtupASTRacket{}} \\ \hline
  20939. \gray{\LfunASTRacket} \\ \hline
  20940. \gray{\LlambdaASTRacket} \\ \hline
  20941. \LinstASTRacket \\
  20942. \begin{array}{lcl}
  20943. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20944. \end{array}
  20945. \end{array}
  20946. \]
  20947. \fi
  20948. \if\edition\pythonEd
  20949. \[
  20950. \begin{array}{l}
  20951. \gray{\LintASTPython} \\ \hline
  20952. \gray{\LvarASTPython{}} \\ \hline
  20953. \gray{\LifASTPython{}} \\ \hline
  20954. \gray{\LwhileASTPython{}} \\ \hline
  20955. \gray{\LtupASTPython{}} \\ \hline
  20956. \gray{\LfunASTPython} \\ \hline
  20957. \gray{\LlambdaASTPython} \\ \hline
  20958. \LinstASTPython \\
  20959. \begin{array}{lcl}
  20960. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20961. \end{array}
  20962. \end{array}
  20963. \]
  20964. \fi
  20965. \end{tcolorbox}
  20966. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20967. (figure~\ref{fig:Llam-syntax}).}
  20968. \label{fig:Lpoly-prime-syntax}
  20969. \end{figure}
  20970. The output of the \code{resolve} pass on the generic \code{map}
  20971. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20972. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20973. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20974. \begin{figure}[tbp]
  20975. % poly_test_2.rkt
  20976. \begin{tcolorbox}[colback=white]
  20977. \if\edition\racketEd
  20978. \begin{lstlisting}
  20979. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20980. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20981. (define (inc [x : Integer]) : Integer (+ x 1))
  20982. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20983. (Integer))
  20984. inc (vector 0 41)) 1)
  20985. \end{lstlisting}
  20986. \fi
  20987. \if\edition\pythonEd
  20988. \begin{lstlisting}
  20989. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20990. return (f(tup[0]), f(tup[1]))
  20991. def add1(x : int) -> int:
  20992. return x + 1
  20993. t = inst(map, {T: int})(add1, (0, 41))
  20994. print(t[1])
  20995. \end{lstlisting}
  20996. \fi
  20997. \end{tcolorbox}
  20998. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20999. \label{fig:map-resolve}
  21000. \end{figure}
  21001. \section{Erase Generic Types}
  21002. \label{sec:erase_types}
  21003. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21004. represent type variables. For example, figure~\ref{fig:map-erase}
  21005. shows the output of the \code{erase\_types} pass on the generic
  21006. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21007. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  21008. \code{All} types are removed from the type of \code{map}.
  21009. \begin{figure}[tbp]
  21010. \begin{tcolorbox}[colback=white]
  21011. \if\edition\racketEd
  21012. \begin{lstlisting}
  21013. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21014. : (Vector Any Any)
  21015. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21016. (define (inc [x : Integer]) : Integer (+ x 1))
  21017. (vector-ref ((cast map
  21018. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21019. ((Integer -> Integer) (Vector Integer Integer)
  21020. -> (Vector Integer Integer)))
  21021. inc (vector 0 41)) 1)
  21022. \end{lstlisting}
  21023. \fi
  21024. \if\edition\pythonEd
  21025. \begin{lstlisting}
  21026. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21027. return (f(tup[0]), f(tup[1]))
  21028. def add1(x : int) -> int:
  21029. return (x + 1)
  21030. def main() -> int:
  21031. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21032. print(t[1])
  21033. return 0
  21034. \end{lstlisting}
  21035. {\small
  21036. where\\
  21037. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21038. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21039. }
  21040. \fi
  21041. \end{tcolorbox}
  21042. \caption{The generic \code{map} example after type erasure.}
  21043. \label{fig:map-erase}
  21044. \end{figure}
  21045. This process of type erasure creates a challenge at points of
  21046. instantiation. For example, consider the instantiation of
  21047. \code{map} shown in figure~\ref{fig:map-resolve}.
  21048. The type of \code{map} is
  21049. %
  21050. \if\edition\racketEd
  21051. \begin{lstlisting}
  21052. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21053. \end{lstlisting}
  21054. \fi
  21055. \if\edition\pythonEd
  21056. \begin{lstlisting}
  21057. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21058. \end{lstlisting}
  21059. \fi
  21060. %
  21061. and it is instantiated to
  21062. %
  21063. \if\edition\racketEd
  21064. \begin{lstlisting}
  21065. ((Integer -> Integer) (Vector Integer Integer)
  21066. -> (Vector Integer Integer))
  21067. \end{lstlisting}
  21068. \fi
  21069. \if\edition\pythonEd
  21070. \begin{lstlisting}
  21071. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21072. \end{lstlisting}
  21073. \fi
  21074. %
  21075. After erasure, the type of \code{map} is
  21076. %
  21077. \if\edition\racketEd
  21078. \begin{lstlisting}
  21079. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21080. \end{lstlisting}
  21081. \fi
  21082. \if\edition\pythonEd
  21083. \begin{lstlisting}
  21084. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21085. \end{lstlisting}
  21086. \fi
  21087. %
  21088. but we need to convert it to the instantiated type. This is easy to
  21089. do in the language \LangCast{} with a single \code{cast}. In the
  21090. example shown in figure~\ref{fig:map-erase}, the instantiation of
  21091. \code{map} has been compiled to a \code{cast} from the type of
  21092. \code{map} to the instantiated type. The source and the target type of a
  21093. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  21094. the case because both the source and target are obtained from the same
  21095. generic type of \code{map}, replacing the type parameters with
  21096. \CANYTY{} in the former and with the deduced type arguments in the
  21097. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21098. To implement the \code{erase\_types} pass, we first recommend defining
  21099. a recursive function that translates types, named
  21100. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21101. follows.
  21102. %
  21103. \if\edition\racketEd
  21104. \begin{lstlisting}
  21105. |$T$|
  21106. |$\Rightarrow$|
  21107. Any
  21108. \end{lstlisting}
  21109. \fi
  21110. \if\edition\pythonEd
  21111. \begin{lstlisting}
  21112. GenericVar(|$T$|)
  21113. |$\Rightarrow$|
  21114. Any
  21115. \end{lstlisting}
  21116. \fi
  21117. %
  21118. \noindent The \code{erase\_type} function also removes the generic
  21119. \code{All} types.
  21120. %
  21121. \if\edition\racketEd
  21122. \begin{lstlisting}
  21123. (All |$xs$| |$T_1$|)
  21124. |$\Rightarrow$|
  21125. |$T'_1$|
  21126. \end{lstlisting}
  21127. \fi
  21128. \if\edition\pythonEd
  21129. \begin{lstlisting}
  21130. AllType(|$xs$|, |$T_1$|)
  21131. |$\Rightarrow$|
  21132. |$T'_1$|
  21133. \end{lstlisting}
  21134. \fi
  21135. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  21136. %
  21137. In this compiler pass, apply the \code{erase\_type} function to all
  21138. the type annotations in the program.
  21139. Regarding the translation of expressions, the case for \code{Inst} is
  21140. the interesting one. We translate it into a \code{Cast}, as shown
  21141. next.
  21142. The type of the subexpression $e$ is a generic type of the form
  21143. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  21144. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  21145. cast is the erasure of $T$, the type $T_s$.
  21146. %
  21147. \if\edition\racketEd
  21148. %
  21149. The target type $T_t$ is the result of substituting the argument types
  21150. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  21151. erasure.
  21152. %
  21153. \begin{lstlisting}
  21154. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21155. |$\Rightarrow$|
  21156. (Cast |$e'$| |$T_s$| |$T_t$|)
  21157. \end{lstlisting}
  21158. %
  21159. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21160. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21161. \fi
  21162. \if\edition\pythonEd
  21163. %
  21164. The target type $T_t$ is the result of substituting the deduced
  21165. argument types $d$ in $T$ followed by doing type erasure.
  21166. %
  21167. \begin{lstlisting}
  21168. Inst(|$e$|, |$d$|)
  21169. |$\Rightarrow$|
  21170. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21171. \end{lstlisting}
  21172. %
  21173. where
  21174. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21175. \fi
  21176. Finally, each generic function is translated to a regular
  21177. function in which type erasure has been applied to all the type
  21178. annotations and the body.
  21179. %% \begin{lstlisting}
  21180. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21181. %% |$\Rightarrow$|
  21182. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21183. %% \end{lstlisting}
  21184. \begin{exercise}\normalfont\normalsize
  21185. Implement a compiler for the polymorphic language \LangPoly{} by
  21186. extending and adapting your compiler for \LangGrad{}. Create six new
  21187. test programs that use polymorphic functions. Some of them should
  21188. make use of first-class generics.
  21189. \end{exercise}
  21190. \begin{figure}[tbp]
  21191. \begin{tcolorbox}[colback=white]
  21192. \if\edition\racketEd
  21193. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21194. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21195. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21196. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21197. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21198. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21199. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21200. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21201. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21202. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21203. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21204. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21205. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21206. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21207. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21208. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21209. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21210. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21211. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21212. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21213. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21214. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21215. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21216. \path[->,bend left=15] (Lpoly) edge [above] node
  21217. {\ttfamily\footnotesize resolve} (Lpolyp);
  21218. \path[->,bend left=15] (Lpolyp) edge [above] node
  21219. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21220. \path[->,bend left=15] (Lgradualp) edge [above] node
  21221. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21222. \path[->,bend left=15] (Llambdapp) edge [left] node
  21223. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21224. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21225. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21226. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21227. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21228. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21229. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21230. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21231. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21232. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21233. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21234. \path[->,bend left=15] (F1-1) edge [above] node
  21235. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21236. \path[->,bend left=15] (F1-2) edge [above] node
  21237. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21238. \path[->,bend left=15] (F1-3) edge [left] node
  21239. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21240. \path[->,bend left=15] (F1-4) edge [below] node
  21241. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21242. \path[->,bend right=15] (F1-5) edge [above] node
  21243. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21244. \path[->,bend right=15] (F1-6) edge [above] node
  21245. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21246. \path[->,bend right=15] (C3-2) edge [right] node
  21247. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21248. \path[->,bend right=15] (x86-2) edge [right] node
  21249. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21250. \path[->,bend right=15] (x86-2-1) edge [below] node
  21251. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21252. \path[->,bend right=15] (x86-2-2) edge [right] node
  21253. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21254. \path[->,bend left=15] (x86-3) edge [above] node
  21255. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21256. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21257. \end{tikzpicture}
  21258. \fi
  21259. \if\edition\pythonEd
  21260. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21261. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21262. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21263. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21264. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21265. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21266. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21267. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21268. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21269. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21270. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21271. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21272. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21273. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21274. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21275. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21276. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21277. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21278. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21279. \path[->,bend left=15] (Lgradual) edge [above] node
  21280. {\ttfamily\footnotesize shrink} (Lgradual2);
  21281. \path[->,bend left=15] (Lgradual2) edge [above] node
  21282. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21283. \path[->,bend left=15] (Lgradual3) edge [above] node
  21284. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21285. \path[->,bend left=15] (Lgradual4) edge [left] node
  21286. {\ttfamily\footnotesize resolve} (Lgradualr);
  21287. \path[->,bend left=15] (Lgradualr) edge [below] node
  21288. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21289. \path[->,bend right=15] (Llambdapp) edge [above] node
  21290. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21291. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21292. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21293. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21294. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21295. \path[->,bend right=15] (F1-1) edge [below] node
  21296. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21297. \path[->,bend right=15] (F1-2) edge [below] node
  21298. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21299. \path[->,bend left=15] (F1-3) edge [above] node
  21300. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21301. \path[->,bend left=15] (F1-5) edge [left] node
  21302. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21303. \path[->,bend left=5] (F1-6) edge [below] node
  21304. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21305. \path[->,bend right=15] (C3-2) edge [right] node
  21306. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21307. \path[->,bend right=15] (x86-2) edge [below] node
  21308. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21309. \path[->,bend right=15] (x86-3) edge [below] node
  21310. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21311. \path[->,bend left=15] (x86-4) edge [above] node
  21312. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21313. \end{tikzpicture}
  21314. \fi
  21315. \end{tcolorbox}
  21316. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21317. \label{fig:Lpoly-passes}
  21318. \end{figure}
  21319. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21320. needed to compile \LangPoly{}.
  21321. % TODO: challenge problem: specialization of instantiations
  21322. % Further Reading
  21323. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21324. \clearpage
  21325. \appendix
  21326. \chapter{Appendix}
  21327. \setcounter{footnote}{0}
  21328. \if\edition\racketEd
  21329. \section{Interpreters}
  21330. \label{appendix:interp}
  21331. \index{subject}{interpreter}
  21332. We provide interpreters for each of the source languages \LangInt{},
  21333. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21334. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21335. intermediate languages \LangCVar{} and \LangCIf{} are in
  21336. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21337. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21338. \key{interp.rkt} file.
  21339. \section{Utility Functions}
  21340. \label{appendix:utilities}
  21341. The utility functions described in this section are in the
  21342. \key{utilities.rkt} file of the support code.
  21343. \paragraph{\code{interp-tests}}
  21344. This function runs the compiler passes and the interpreters on each of
  21345. the specified tests to check whether each pass is correct. The
  21346. \key{interp-tests} function has the following parameters:
  21347. \begin{description}
  21348. \item[name (a string)] A name to identify the compiler,
  21349. \item[typechecker] A function of exactly one argument that either
  21350. raises an error using the \code{error} function when it encounters a
  21351. type error or returns \code{\#f} when it encounters a type
  21352. error. If there is no type error, the type checker returns the
  21353. program.
  21354. \item[passes] A list with one entry per pass. An entry is a list
  21355. consisting of four things:
  21356. \begin{enumerate}
  21357. \item a string giving the name of the pass;
  21358. \item the function that implements the pass (a translator from AST
  21359. to AST);
  21360. \item a function that implements the interpreter (a function from
  21361. AST to result value) for the output language; and,
  21362. \item a type checker for the output language. Type checkers for
  21363. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21364. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21365. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21366. type checker entry is optional. The support code does not provide
  21367. type checkers for the x86 languages.
  21368. \end{enumerate}
  21369. \item[source-interp] An interpreter for the source language. The
  21370. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21371. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21372. \item[tests] A list of test numbers that specifies which tests to
  21373. run (explained next).
  21374. \end{description}
  21375. %
  21376. The \key{interp-tests} function assumes that the subdirectory
  21377. \key{tests} has a collection of Racket programs whose names all start
  21378. with the family name, followed by an underscore and then the test
  21379. number, and ending with the file extension \key{.rkt}. Also, for each test
  21380. program that calls \code{read} one or more times, there is a file with
  21381. the same name except that the file extension is \key{.in}, which
  21382. provides the input for the Racket program. If the test program is
  21383. expected to fail type checking, then there should be an empty file of
  21384. the same name with extension \key{.tyerr}.
  21385. \paragraph{\code{compiler-tests}}
  21386. This function runs the compiler passes to generate x86 (a \key{.s}
  21387. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21388. It runs the machine code and checks that the output is $42$. The
  21389. parameters to the \code{compiler-tests} function are similar to those
  21390. of the \code{interp-tests} function, and they consist of
  21391. \begin{itemize}
  21392. \item a compiler name (a string),
  21393. \item a type checker,
  21394. \item description of the passes,
  21395. \item name of a test-family, and
  21396. \item a list of test numbers.
  21397. \end{itemize}
  21398. \paragraph{\code{compile-file}}
  21399. This function takes a description of the compiler passes (see the
  21400. comment for \key{interp-tests}) and returns a function that, given a
  21401. program file name (a string ending in \key{.rkt}), applies all the
  21402. passes and writes the output to a file whose name is the same as the
  21403. program file name with extension \key{.rkt} replaced by \key{.s}.
  21404. \paragraph{\code{read-program}}
  21405. This function takes a file path and parses that file (it must be a
  21406. Racket program) into an abstract syntax tree.
  21407. \paragraph{\code{parse-program}}
  21408. This function takes an S-expression representation of an abstract
  21409. syntax tree and converts it into the struct-based representation.
  21410. \paragraph{\code{assert}}
  21411. This function takes two parameters, a string (\code{msg}) and Boolean
  21412. (\code{bool}), and displays the message \key{msg} if the Boolean
  21413. \key{bool} is false.
  21414. \paragraph{\code{lookup}}
  21415. % remove discussion of lookup? -Jeremy
  21416. This function takes a key and an alist and returns the first value that is
  21417. associated with the given key, if there is one. If not, an error is
  21418. triggered. The alist may contain both immutable pairs (built with
  21419. \key{cons}) and mutable pairs (built with \key{mcons}).
  21420. %The \key{map2} function ...
  21421. \fi %\racketEd
  21422. \section{x86 Instruction Set Quick Reference}
  21423. \label{sec:x86-quick-reference}
  21424. \index{subject}{x86}
  21425. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21426. do. We write $A \to B$ to mean that the value of $A$ is written into
  21427. location $B$. Address offsets are given in bytes. The instruction
  21428. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21429. registers (such as \code{\%rax}), or memory references (such as
  21430. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21431. reference per instruction. Other operands must be immediates or
  21432. registers.
  21433. \begin{table}[tbp]
  21434. \centering
  21435. \begin{tabular}{l|l}
  21436. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21437. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21438. \texttt{negq} $A$ & $- A \to A$ \\
  21439. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21440. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  21441. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  21442. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21443. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  21444. \texttt{retq} & Pops the return address and jumps to it \\
  21445. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  21446. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  21447. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  21448. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21449. be an immediate) \\
  21450. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21451. matches the condition code of the instruction; otherwise go to the
  21452. next instructions. The condition codes are \key{e} for \emph{equal},
  21453. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21454. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21455. \texttt{jl} $L$ & \\
  21456. \texttt{jle} $L$ & \\
  21457. \texttt{jg} $L$ & \\
  21458. \texttt{jge} $L$ & \\
  21459. \texttt{jmp} $L$ & Jump to label $L$ \\
  21460. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21461. \texttt{movzbq} $A$, $B$ &
  21462. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21463. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21464. and the extra bytes of $B$ are set to zero.} \\
  21465. & \\
  21466. & \\
  21467. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  21468. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  21469. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  21470. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21471. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21472. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21473. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21474. description of the condition codes. $A$ must be a single byte register
  21475. (e.g., \texttt{al} or \texttt{cl}).} \\
  21476. \texttt{setl} $A$ & \\
  21477. \texttt{setle} $A$ & \\
  21478. \texttt{setg} $A$ & \\
  21479. \texttt{setge} $A$ &
  21480. \end{tabular}
  21481. \vspace{5pt}
  21482. \caption{Quick reference for the x86 instructions used in this book.}
  21483. \label{tab:x86-instr}
  21484. \end{table}
  21485. %% \if\edition\racketEd
  21486. %% \cleardoublepage
  21487. %% \section{Concrete Syntax for Intermediate Languages}
  21488. %% The concrete syntax of \LangAny{} is defined in
  21489. %% figure~\ref{fig:Lany-concrete-syntax}.
  21490. %% \begin{figure}[tp]
  21491. %% \centering
  21492. %% \fbox{
  21493. %% \begin{minipage}{0.97\textwidth}\small
  21494. %% \[
  21495. %% \begin{array}{lcl}
  21496. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  21497. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  21498. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  21499. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  21500. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  21501. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  21502. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  21503. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  21504. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  21505. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  21506. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  21507. %% \MID \LP\key{void?}\;\Exp\RP \\
  21508. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  21509. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  21510. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  21511. %% \end{array}
  21512. %% \]
  21513. %% \end{minipage}
  21514. %% }
  21515. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  21516. %% (figure~\ref{fig:Llam-syntax}).}
  21517. %% \label{fig:Lany-concrete-syntax}
  21518. %% \end{figure}
  21519. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  21520. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  21521. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  21522. %% \ref{fig:c3-concrete-syntax}, respectively.
  21523. %% \begin{figure}[tbp]
  21524. %% \fbox{
  21525. %% \begin{minipage}{0.96\textwidth}
  21526. %% \small
  21527. %% \[
  21528. %% \begin{array}{lcl}
  21529. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  21530. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21531. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  21532. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  21533. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  21534. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  21535. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  21536. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  21537. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  21538. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  21539. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  21540. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  21541. %% \end{array}
  21542. %% \]
  21543. %% \end{minipage}
  21544. %% }
  21545. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  21546. %% \label{fig:c2-concrete-syntax}
  21547. %% \end{figure}
  21548. %% \begin{figure}[tp]
  21549. %% \fbox{
  21550. %% \begin{minipage}{0.96\textwidth}
  21551. %% \small
  21552. %% \[
  21553. %% \begin{array}{lcl}
  21554. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  21555. %% \\
  21556. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  21557. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  21558. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  21559. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  21560. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  21561. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  21562. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  21563. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  21564. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  21565. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  21566. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  21567. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  21568. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  21569. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  21570. %% \LangCFunM{} & ::= & \Def\ldots
  21571. %% \end{array}
  21572. %% \]
  21573. %% \end{minipage}
  21574. %% }
  21575. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  21576. %% \label{fig:c3-concrete-syntax}
  21577. %% \end{figure}
  21578. %% \fi % racketEd
  21579. \backmatter
  21580. \addtocontents{toc}{\vspace{11pt}}
  21581. %% \addtocontents{toc}{\vspace{11pt}}
  21582. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  21583. \nocite{*}\let\bibname\refname
  21584. \addcontentsline{toc}{fmbm}{\refname}
  21585. \printbibliography
  21586. %\printindex{authors}{Author Index}
  21587. \printindex{subject}{Index}
  21588. \end{document}
  21589. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21590. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21591. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21592. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21593. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21594. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21595. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21596. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21597. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21598. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21599. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21600. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21601. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21602. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21603. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21604. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21605. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21606. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21607. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21608. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21609. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21610. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  21611. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21612. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21613. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21614. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21615. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21616. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21617. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21618. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21619. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21620. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21621. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21622. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21623. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21624. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21625. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21626. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21627. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21628. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21629. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21630. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21631. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21632. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21633. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21634. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21635. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21636. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21637. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21638. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21639. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21640. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21641. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21642. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21643. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21644. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21645. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21646. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21647. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21648. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21649. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21650. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21651. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21652. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21653. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21654. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21655. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21656. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21657. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21658. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21659. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21660. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21661. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21662. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21663. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21664. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21665. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21666. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21667. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21668. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21669. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21670. % LocalWords: pseudocode underapproximation underapproximations LALR
  21671. % LocalWords: semilattices overapproximate incrementing Earley docs
  21672. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21673. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21674. % LocalWords: subparses