book.tex 789 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. % material that is specific to the Python edition of the book
  31. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  32. %% For multiple indices:
  33. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  34. \makeindex{subject}
  35. %\makeindex{authors}
  36. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  37. \if\edition\racketEd
  38. \lstset{%
  39. language=Lisp,
  40. basicstyle=\ttfamily\small,
  41. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  42. deletekeywords={read,mapping,vector},
  43. escapechar=|,
  44. columns=flexible,
  45. %moredelim=[is][\color{red}]{~}{~},
  46. showstringspaces=false
  47. }
  48. \fi
  49. \if\edition\pythonEd
  50. \lstset{%
  51. language=Python,
  52. basicstyle=\ttfamily\small,
  53. morekeywords={match,case,bool,int,let},
  54. deletekeywords={},
  55. escapechar=|,
  56. columns=flexible,
  57. %moredelim=[is][\color{red}]{~}{~},
  58. showstringspaces=false
  59. }
  60. \fi
  61. %%% Any shortcut own defined macros place here
  62. %% sample of author macro:
  63. \input{defs}
  64. \newtheorem{exercise}[theorem]{Exercise}
  65. \numberwithin{theorem}{chapter}
  66. \numberwithin{definition}{chapter}
  67. \numberwithin{equation}{chapter}
  68. % Adjusted settings
  69. \setlength{\columnsep}{4pt}
  70. %% \begingroup
  71. %% \setlength{\intextsep}{0pt}%
  72. %% \setlength{\columnsep}{0pt}%
  73. %% \begin{wrapfigure}{r}{0.5\textwidth}
  74. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  75. %% \caption{Basic layout}
  76. %% \end{wrapfigure}
  77. %% \lipsum[1]
  78. %% \endgroup
  79. \newbox\oiintbox
  80. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  81. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  82. \def\oiint{\copy\oiintbox}
  83. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  84. %\usepackage{showframe}
  85. \def\ShowFrameLinethickness{0.125pt}
  86. \addbibresource{book.bib}
  87. \if\edition\pythonEd
  88. \addbibresource{python.bib}
  89. \fi
  90. \begin{document}
  91. \frontmatter
  92. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  93. \HalfTitle{Essentials of Compilation}
  94. \halftitlepage
  95. \clearemptydoublepage
  96. \Title{Essentials of Compilation}
  97. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  98. %\edition{First Edition}
  99. \BookAuthor{Jeremy G. Siek}
  100. \imprint{The MIT Press\\
  101. Cambridge, Massachusetts\\
  102. London, England}
  103. \begin{copyrightpage}
  104. \textcopyright\ 2023 Massachusetts Institute of Technology \\[2ex]
  105. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  106. Subject to such license, all rights are reserved. \\[2ex]
  107. \includegraphics{CCBY-logo}
  108. The MIT Press would like to thank the anonymous peer reviewers who
  109. provided comments on drafts of this book. The generous work of
  110. academic experts is essential for establishing the authority and
  111. quality of our publications. We acknowledge with gratitude the
  112. contributions of these otherwise uncredited readers.
  113. This book was set in Times LT Std Roman by the author. Printed and
  114. bound in the United States of America.
  115. Library of Congress Cataloging-in-Publication Data is available.
  116. ISBN:
  117. 10 9 8 7 6 5 4 3 2 1
  118. %% Jeremy G. Siek. Available for free viewing
  119. %% or personal downloading under the
  120. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  121. %% license.
  122. %% Copyright in this monograph has been licensed exclusively to The MIT
  123. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  124. %% version to the public in 2022. All inquiries regarding rights should
  125. %% be addressed to The MIT Press, Rights and Permissions Department.
  126. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  127. %% All rights reserved. No part of this book may be reproduced in any
  128. %% form by any electronic or mechanical means (including photocopying,
  129. %% recording, or information storage and retrieval) without permission in
  130. %% writing from the publisher.
  131. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  132. %% United States of America.
  133. %% Library of Congress Cataloging-in-Publication Data is available.
  134. %% ISBN:
  135. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  136. \end{copyrightpage}
  137. \dedication{This book is dedicated to Katie, my partner in everything,
  138. my children, who grew up during the writing of this book, and the
  139. programming language students at Indiana University, whose
  140. thoughtful questions made this a better book.}
  141. %% \begin{epigraphpage}
  142. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  143. %% \textit{Book Name if any}}
  144. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  145. %% \end{epigraphpage}
  146. \tableofcontents
  147. %\listoffigures
  148. %\listoftables
  149. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  150. \chapter*{Preface}
  151. \addcontentsline{toc}{fmbm}{Preface}
  152. There is a magical moment when a programmer presses the run button
  153. and the software begins to execute. Somehow a program written in a
  154. high-level language is running on a computer that is capable only of
  155. shuffling bits. Here we reveal the wizardry that makes that moment
  156. possible. Beginning with the groundbreaking work of Backus and
  157. colleagues in the 1950s, computer scientists developed techniques for
  158. constructing programs called \emph{compilers} that automatically
  159. translate high-level programs into machine code.
  160. We take you on a journey through constructing your own compiler for a
  161. small but powerful language. Along the way we explain the essential
  162. concepts, algorithms, and data structures that underlie compilers. We
  163. develop your understanding of how programs are mapped onto computer
  164. hardware, which is helpful in reasoning about properties at the
  165. junction of hardware and software, such as execution time, software
  166. errors, and security vulnerabilities. For those interested in
  167. pursuing compiler construction as a career, our goal is to provide a
  168. stepping-stone to advanced topics such as just-in-time compilation,
  169. program analysis, and program optimization. For those interested in
  170. designing and implementing programming languages, we connect language
  171. design choices to their impact on the compiler and the generated code.
  172. A compiler is typically organized as a sequence of stages that
  173. progressively translate a program to the code that runs on
  174. hardware. We take this approach to the extreme by partitioning our
  175. compiler into a large number of \emph{nanopasses}, each of which
  176. performs a single task. This enables the testing of each pass in
  177. isolation and focuses our attention, making the compiler far easier to
  178. understand.
  179. The most familiar approach to describing compilers is to dedicate each
  180. chapter to one pass. The problem with that approach is that it
  181. obfuscates how language features motivate design choices in a
  182. compiler. We instead take an \emph{incremental} approach in which we
  183. build a complete compiler in each chapter, starting with a small input
  184. language that includes only arithmetic and variables. We add new
  185. language features in subsequent chapters, extending the compiler as
  186. necessary.
  187. Our choice of language features is designed to elicit fundamental
  188. concepts and algorithms used in compilers.
  189. \begin{itemize}
  190. \item We begin with integer arithmetic and local variables in
  191. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  192. the fundamental tools of compiler construction: \emph{abstract
  193. syntax trees} and \emph{recursive functions}.
  194. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  195. \emph{graph coloring} to assign variables to machine registers.
  196. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  197. motivates an elegant recursive algorithm for translating them into
  198. conditional \code{goto} statements.
  199. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  200. variables}. This elicits the need for \emph{dataflow
  201. analysis} in the register allocator.
  202. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  203. \emph{garbage collection}.
  204. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  205. without lexical scoping, similar to functions in the C programming
  206. language~\citep{Kernighan:1988nx}. The reader learns about the
  207. procedure call stack and \emph{calling conventions} and how they interact
  208. with register allocation and garbage collection. The chapter also
  209. describes how to generate efficient tail calls.
  210. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  211. scoping, that is, \emph{lambda} expressions. The reader learns about
  212. \emph{closure conversion}, in which lambdas are translated into a
  213. combination of functions and tuples.
  214. % Chapter about classes and objects?
  215. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  216. point the input languages are statically typed. The reader extends
  217. the statically typed language with an \code{Any} type that serves
  218. as a target for compiling the dynamically typed language.
  219. %% {\if\edition\pythonEd
  220. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  221. %% \emph{classes}.
  222. %% \fi}
  223. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  224. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  225. in which different regions of a program may be static or dynamically
  226. typed. The reader implements runtime support for \emph{proxies} that
  227. allow values to safely move between regions.
  228. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  229. leveraging the \code{Any} type and type casts developed in chapters
  230. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  231. \end{itemize}
  232. There are many language features that we do not include. Our choices
  233. balance the incidental complexity of a feature versus the fundamental
  234. concepts that it exposes. For example, we include tuples and not
  235. records because although they both elicit the study of heap allocation and
  236. garbage collection, records come with more incidental complexity.
  237. Since 2009, drafts of this book have served as the textbook for
  238. sixteen week compiler courses for upper-level undergraduates and
  239. first-year graduate students at the University of Colorado and Indiana
  240. University.
  241. %
  242. Students come into the course having learned the basics of
  243. programming, data structures and algorithms, and discrete
  244. mathematics.
  245. %
  246. At the beginning of the course, students form groups of two to four
  247. people. The groups complete one chapter every two weeks, starting
  248. with chapter~\ref{ch:Lvar} and finishing with
  249. chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  250. that we assign to the graduate students. The last two weeks of the
  251. course involve a final project in which students design and implement
  252. a compiler extension of their choosing. The last few chapters can be
  253. used in support of these projects. For compiler courses at
  254. universities on the quarter system (about ten weeks in length), we
  255. recommend completing the course through chapter~\ref{ch:Lvec} or
  256. chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  257. students for each compiler pass.
  258. %
  259. The course can be adapted to emphasize functional languages by
  260. skipping chapter~\ref{ch:Lwhile} (loops) and including
  261. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  262. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  263. %
  264. %% \python{A course that emphasizes object-oriented languages would
  265. %% include Chapter~\ref{ch:Lobject}.}
  266. %
  267. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  268. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  269. chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  270. tail calls.
  271. This book has been used in compiler courses at California Polytechnic
  272. State University, Portland State University, Rose–Hulman Institute of
  273. Technology, University of Freiburg, University of Massachusetts
  274. Lowell, and the University of Vermont.
  275. \begin{figure}[tp]
  276. \begin{tcolorbox}[colback=white]
  277. {\if\edition\racketEd
  278. \begin{tikzpicture}[baseline=(current bounding box.center)]
  279. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  280. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  281. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  282. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  283. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  284. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  285. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  286. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  287. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  288. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  289. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  290. \path[->] (C1) edge [above] node {} (C2);
  291. \path[->] (C2) edge [above] node {} (C3);
  292. \path[->] (C3) edge [above] node {} (C4);
  293. \path[->] (C4) edge [above] node {} (C5);
  294. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  295. \path[->] (C5) edge [above] node {} (C7);
  296. \path[->] (C6) edge [above] node {} (C7);
  297. \path[->] (C4) edge [above] node {} (C8);
  298. \path[->] (C4) edge [above] node {} (C9);
  299. \path[->] (C7) edge [above] node {} (C10);
  300. \path[->] (C8) edge [above] node {} (C10);
  301. \path[->] (C10) edge [above] node {} (C11);
  302. \end{tikzpicture}
  303. \fi}
  304. {\if\edition\pythonEd
  305. \begin{tikzpicture}[baseline=(current bounding box.center)]
  306. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  307. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  308. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  309. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  310. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  311. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  312. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  313. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  314. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  315. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  316. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  317. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  318. \path[->] (C1) edge [above] node {} (C2);
  319. \path[->] (C2) edge [above] node {} (C3);
  320. \path[->] (C3) edge [above] node {} (C4);
  321. \path[->] (C4) edge [above] node {} (C5);
  322. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  323. \path[->] (C5) edge [above] node {} (C7);
  324. \path[->] (C6) edge [above] node {} (C7);
  325. \path[->] (C4) edge [above] node {} (C8);
  326. \path[->] (C4) edge [above] node {} (C9);
  327. \path[->] (C7) edge [above] node {} (C10);
  328. \path[->] (C8) edge [above] node {} (C10);
  329. % \path[->] (C8) edge [above] node {} (CO);
  330. \path[->] (C10) edge [above] node {} (C11);
  331. \end{tikzpicture}
  332. \fi}
  333. \end{tcolorbox}
  334. \caption{Diagram of chapter dependencies.}
  335. \label{fig:chapter-dependences}
  336. \end{figure}
  337. \racket{
  338. We use the \href{https://racket-lang.org/}{Racket} language both for
  339. the implementation of the compiler and for the input language, so the
  340. reader should be proficient with Racket or Scheme. There are many
  341. excellent resources for learning Scheme and
  342. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  343. }
  344. \python{
  345. This edition of the book uses \href{https://www.python.org/}{Python}
  346. both for the implementation of the compiler and for the input language, so the
  347. reader should be proficient with Python. There are many
  348. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  349. }
  350. The support code for this book is in the GitHub repository at
  351. the following location:
  352. \begin{center}\small\texttt
  353. https://github.com/IUCompilerCourse/
  354. \end{center}
  355. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  356. is helpful but not necessary for the reader to have taken a computer
  357. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  358. assembly language that are needed in the compiler.
  359. %
  360. We follow the System V calling
  361. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  362. that we generate works with the runtime system (written in C) when it
  363. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  364. operating systems on Intel hardware.
  365. %
  366. On the Windows operating system, \code{gcc} uses the Microsoft x64
  367. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  368. assembly code that we generate does \emph{not} work with the runtime
  369. system on Windows. One workaround is to use a virtual machine with
  370. Linux as the guest operating system.
  371. \section*{Acknowledgments}
  372. The tradition of compiler construction at Indiana University goes back
  373. to research and courses on programming languages by Daniel Friedman in
  374. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  375. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  376. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  377. the compiler course and continued the development of Chez Scheme.
  378. %
  379. The compiler course evolved to incorporate novel pedagogical ideas
  380. while also including elements of real-world compilers. One of
  381. Friedman's ideas was to split the compiler into many small
  382. passes. Another idea, called ``the game,'' was to test the code
  383. generated by each pass using interpreters.
  384. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  385. developed infrastructure to support this approach and evolved the
  386. course to use even smaller
  387. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  388. design decisions in this book are inspired by the assignment
  389. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  390. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  391. organization of the course made it difficult for students to
  392. understand the rationale for the compiler design. Ghuloum proposed the
  393. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  394. based.
  395. We thank the many students who served as teaching assistants for the
  396. compiler course at IU, including Carl Factora, Ryan Scott, Cameron
  397. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  398. garbage collector and x86 interpreter, Michael Vollmer for work on
  399. efficient tail calls, and Michael Vitousek for help with the first
  400. offering of the incremental compiler course at IU.
  401. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  402. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  403. Michael Wollowski for teaching courses based on drafts of this book
  404. and for their feedback. We thank the National Science Foundation for
  405. the grants that helped to support this work: Grant Numbers 1518844,
  406. 1763922, and 1814460.
  407. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  408. course in the early 2000s and especially for finding the bug that
  409. sent our garbage collector on a wild goose chase!
  410. \mbox{}\\
  411. \noindent Jeremy G. Siek \\
  412. Bloomington, Indiana
  413. \mainmatter
  414. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  415. \chapter{Preliminaries}
  416. \label{ch:trees-recur}
  417. \setcounter{footnote}{0}
  418. In this chapter we review the basic tools needed to implement a
  419. compiler. Programs are typically input by a programmer as text, that
  420. is, a sequence of characters. The program-as-text representation is
  421. called \emph{concrete syntax}. We use concrete syntax to concisely
  422. write down and talk about programs. Inside the compiler, we use
  423. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  424. that efficiently supports the operations that the compiler needs to
  425. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  426. syntax}\index{subject}{abstract syntax
  427. tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse}
  428. The process of translating from concrete syntax to abstract syntax is
  429. called \emph{parsing}~\citep{Aho:2006wb}\python{ and is studied in
  430. chapter~\ref{ch:parsing-Lvar}}.
  431. \racket{This book does not cover the theory and implementation of parsing.}%
  432. %
  433. \racket{A parser is provided in the support code for translating from
  434. concrete to abstract syntax.}%
  435. %
  436. \python{For now we use Python's \code{ast} module to translate from concrete
  437. to abstract syntax.}
  438. ASTs can be represented inside the compiler in many different ways,
  439. depending on the programming language used to write the compiler.
  440. %
  441. \racket{We use Racket's
  442. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  443. feature to represent ASTs (section~\ref{sec:ast}).}
  444. %
  445. \python{We use Python classes and objects to represent ASTs, especially the
  446. classes defined in the standard \code{ast} module for the Python
  447. source language.}
  448. %
  449. We use grammars to define the abstract syntax of programming languages
  450. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  451. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  452. recursive functions to construct and deconstruct ASTs
  453. (section~\ref{sec:recursion}). This chapter provides a brief
  454. introduction to these components.
  455. \racket{\index{subject}{struct}}
  456. \python{\index{subject}{class}\index{subject}{object}}
  457. \section{Abstract Syntax Trees}
  458. \label{sec:ast}
  459. Compilers use abstract syntax trees to represent programs because they
  460. often need to ask questions such as, for a given part of a program,
  461. what kind of language feature is it? What are its subparts? Consider
  462. the program on the left and the diagram of its AST on the
  463. right~\eqref{eq:arith-prog}. This program is an addition operation
  464. that has two subparts, a \racket{read}\python{input} operation and a
  465. negation. The negation has another subpart, the integer constant
  466. \code{8}. By using a tree to represent the program, we can easily
  467. follow the links to go from one part of a program to its subparts.
  468. \begin{center}
  469. \begin{minipage}{0.4\textwidth}
  470. \if\edition\racketEd
  471. \begin{lstlisting}
  472. (+ (read) (- 8))
  473. \end{lstlisting}
  474. \fi
  475. \if\edition\pythonEd
  476. \begin{lstlisting}
  477. input_int() + -8
  478. \end{lstlisting}
  479. \fi
  480. \end{minipage}
  481. \begin{minipage}{0.4\textwidth}
  482. \begin{equation}
  483. \begin{tikzpicture}
  484. \node[draw] (plus) at (0 , 0) {\key{+}};
  485. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  486. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  487. \node[draw] (8) at (1 , -3) {\key{8}};
  488. \draw[->] (plus) to (read);
  489. \draw[->] (plus) to (minus);
  490. \draw[->] (minus) to (8);
  491. \end{tikzpicture}
  492. \label{eq:arith-prog}
  493. \end{equation}
  494. \end{minipage}
  495. \end{center}
  496. We use the standard terminology for trees to describe ASTs: each
  497. rectangle above is called a \emph{node}. The arrows connect a node to its
  498. \emph{children}, which are also nodes. The top-most node is the
  499. \emph{root}. Every node except for the root has a \emph{parent} (the
  500. node of which it is the child). If a node has no children, it is a
  501. \emph{leaf} node; otherwise it is an \emph{internal} node.
  502. \index{subject}{node}
  503. \index{subject}{children}
  504. \index{subject}{root}
  505. \index{subject}{parent}
  506. \index{subject}{leaf}
  507. \index{subject}{internal node}
  508. %% Recall that an \emph{symbolic expression} (S-expression) is either
  509. %% \begin{enumerate}
  510. %% \item an atom, or
  511. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  512. %% where $e_1$ and $e_2$ are each an S-expression.
  513. %% \end{enumerate}
  514. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  515. %% null value \code{'()}, etc. We can create an S-expression in Racket
  516. %% simply by writing a backquote (called a quasi-quote in Racket)
  517. %% followed by the textual representation of the S-expression. It is
  518. %% quite common to use S-expressions to represent a list, such as $a, b
  519. %% ,c$ in the following way:
  520. %% \begin{lstlisting}
  521. %% `(a . (b . (c . ())))
  522. %% \end{lstlisting}
  523. %% Each element of the list is in the first slot of a pair, and the
  524. %% second slot is either the rest of the list or the null value, to mark
  525. %% the end of the list. Such lists are so common that Racket provides
  526. %% special notation for them that removes the need for the periods
  527. %% and so many parenthesis:
  528. %% \begin{lstlisting}
  529. %% `(a b c)
  530. %% \end{lstlisting}
  531. %% The following expression creates an S-expression that represents AST
  532. %% \eqref{eq:arith-prog}.
  533. %% \begin{lstlisting}
  534. %% `(+ (read) (- 8))
  535. %% \end{lstlisting}
  536. %% When using S-expressions to represent ASTs, the convention is to
  537. %% represent each AST node as a list and to put the operation symbol at
  538. %% the front of the list. The rest of the list contains the children. So
  539. %% in the above case, the root AST node has operation \code{`+} and its
  540. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  541. %% diagram \eqref{eq:arith-prog}.
  542. %% To build larger S-expressions one often needs to splice together
  543. %% several smaller S-expressions. Racket provides the comma operator to
  544. %% splice an S-expression into a larger one. For example, instead of
  545. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  546. %% we could have first created an S-expression for AST
  547. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  548. %% S-expression.
  549. %% \begin{lstlisting}
  550. %% (define ast1.4 `(- 8))
  551. %% (define ast1_1 `(+ (read) ,ast1.4))
  552. %% \end{lstlisting}
  553. %% In general, the Racket expression that follows the comma (splice)
  554. %% can be any expression that produces an S-expression.
  555. {\if\edition\racketEd
  556. We define a Racket \code{struct} for each kind of node. For this
  557. chapter we require just two kinds of nodes: one for integer constants
  558. and one for primitive operations. The following is the \code{struct}
  559. definition for integer constants.\footnote{All the AST structures are
  560. defined in the file \code{utilities.rkt} in the support code.}
  561. \begin{lstlisting}
  562. (struct Int (value))
  563. \end{lstlisting}
  564. An integer node contains just one thing: the integer value.
  565. We establish the convention that \code{struct} names, such
  566. as \code{Int}, are capitalized.
  567. To create an AST node for the integer $8$, we write \INT{8}.
  568. \begin{lstlisting}
  569. (define eight (Int 8))
  570. \end{lstlisting}
  571. We say that the value created by \INT{8} is an
  572. \emph{instance} of the
  573. \code{Int} structure.
  574. The following is the \code{struct} definition for primitive operations.
  575. \begin{lstlisting}
  576. (struct Prim (op args))
  577. \end{lstlisting}
  578. A primitive operation node includes an operator symbol \code{op} and a
  579. list of child arguments called \code{args}. For example, to create an
  580. AST that negates the number $8$, we write the following.
  581. \begin{lstlisting}
  582. (define neg-eight (Prim '- (list eight)))
  583. \end{lstlisting}
  584. Primitive operations may have zero or more children. The \code{read}
  585. operator has zero:
  586. \begin{lstlisting}
  587. (define rd (Prim 'read '()))
  588. \end{lstlisting}
  589. The addition operator has two children:
  590. \begin{lstlisting}
  591. (define ast1_1 (Prim '+ (list rd neg-eight)))
  592. \end{lstlisting}
  593. We have made a design choice regarding the \code{Prim} structure.
  594. Instead of using one structure for many different operations
  595. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  596. structure for each operation, as follows:
  597. \begin{lstlisting}
  598. (struct Read ())
  599. (struct Add (left right))
  600. (struct Neg (value))
  601. \end{lstlisting}
  602. The reason that we choose to use just one structure is that many parts
  603. of the compiler can use the same code for the different primitive
  604. operators, so we might as well just write that code once by using a
  605. single structure.
  606. %
  607. \fi}
  608. {\if\edition\pythonEd
  609. We use a Python \code{class} for each kind of node.
  610. The following is the class definition for
  611. constants from the Python \code{ast} module.
  612. \begin{lstlisting}
  613. class Constant:
  614. def __init__(self, value):
  615. self.value = value
  616. \end{lstlisting}
  617. An integer constant node includes just one thing: the integer value.
  618. To create an AST node for the integer $8$, we write \INT{8}.
  619. \begin{lstlisting}
  620. eight = Constant(8)
  621. \end{lstlisting}
  622. We say that the value created by \INT{8} is an
  623. \emph{instance} of the \code{Constant} class.
  624. The following is the class definition for unary operators.
  625. \begin{lstlisting}
  626. class UnaryOp:
  627. def __init__(self, op, operand):
  628. self.op = op
  629. self.operand = operand
  630. \end{lstlisting}
  631. The specific operation is specified by the \code{op} parameter. For
  632. example, the class \code{USub} is for unary subtraction.
  633. (More unary operators are introduced in later chapters.) To create an AST that
  634. negates the number $8$, we write the following.
  635. \begin{lstlisting}
  636. neg_eight = UnaryOp(USub(), eight)
  637. \end{lstlisting}
  638. The call to the \code{input\_int} function is represented by the
  639. \code{Call} and \code{Name} classes.
  640. \begin{lstlisting}
  641. class Call:
  642. def __init__(self, func, args):
  643. self.func = func
  644. self.args = args
  645. class Name:
  646. def __init__(self, id):
  647. self.id = id
  648. \end{lstlisting}
  649. To create an AST node that calls \code{input\_int}, we write
  650. \begin{lstlisting}
  651. read = Call(Name('input_int'), [])
  652. \end{lstlisting}
  653. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  654. the \code{BinOp} class for binary operators.
  655. \begin{lstlisting}
  656. class BinOp:
  657. def __init__(self, left, op, right):
  658. self.op = op
  659. self.left = left
  660. self.right = right
  661. \end{lstlisting}
  662. Similar to \code{UnaryOp}, the specific operation is specified by the
  663. \code{op} parameter, which for now is just an instance of the
  664. \code{Add} class. So to create the AST
  665. node that adds negative eight to some user input, we write the following.
  666. \begin{lstlisting}
  667. ast1_1 = BinOp(read, Add(), neg_eight)
  668. \end{lstlisting}
  669. \fi}
  670. To compile a program such as \eqref{eq:arith-prog}, we need to know
  671. that the operation associated with the root node is addition and we
  672. need to be able to access its two
  673. children. \racket{Racket}\python{Python} provides pattern matching to
  674. support these kinds of queries, as we see in
  675. section~\ref{sec:pattern-matching}.
  676. We often write down the concrete syntax of a program even when we
  677. actually have in mind the AST, because the concrete syntax is more
  678. concise. We recommend that you always think of programs as abstract
  679. syntax trees.
  680. \section{Grammars}
  681. \label{sec:grammar}
  682. \index{subject}{integer}
  683. \index{subject}{literal}
  684. %\index{subject}{constant}
  685. A programming language can be thought of as a \emph{set} of programs.
  686. The set is infinite (that is, one can always create larger programs),
  687. so one cannot simply describe a language by listing all the
  688. programs in the language. Instead we write down a set of rules, a
  689. \emph{grammar}, for building programs. Grammars are often used to
  690. define the concrete syntax of a language, but they can also be used to
  691. describe the abstract syntax. We write our rules in a variant of
  692. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  693. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  694. we describe a small language, named \LangInt{}, that consists of
  695. integers and arithmetic operations. \index{subject}{grammar}
  696. The first grammar rule for the abstract syntax of \LangInt{} says that an
  697. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  698. \begin{equation}
  699. \Exp ::= \INT{\Int} \label{eq:arith-int}
  700. \end{equation}
  701. %
  702. Each rule has a left-hand side and a right-hand side.
  703. If you have an AST node that matches the
  704. right-hand side, then you can categorize it according to the
  705. left-hand side.
  706. %
  707. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  708. are \emph{terminal} symbols and must literally appear in the program for the
  709. rule to be applicable.\index{subject}{terminal}
  710. %
  711. Our grammars do not mention \emph{white space}, that is, delimiter
  712. characters like spaces, tabs, and new lines. White space may be
  713. inserted between symbols for disambiguation and to improve
  714. readability. \index{subject}{white space}
  715. %
  716. A name such as $\Exp$ that is defined by the grammar rules is a
  717. \emph{nonterminal}. \index{subject}{nonterminal}
  718. %
  719. The name $\Int$ is also a nonterminal, but instead of defining it with
  720. a grammar rule, we define it with the following explanation. An
  721. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  722. $-$ (for negative integers), such that the sequence of decimals
  723. represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  724. enables the representation of integers using 63 bits, which simplifies
  725. several aspects of compilation.
  726. %
  727. \racket{Thus, these integers correspond to the Racket \texttt{fixnum}
  728. datatype on a 64-bit machine.}
  729. %
  730. \python{In contrast, integers in Python have unlimited precision, but
  731. the techniques needed to handle unlimited precision fall outside the
  732. scope of this book.}
  733. The second grammar rule is the \READOP{} operation, which receives an
  734. input integer from the user of the program.
  735. \begin{equation}
  736. \Exp ::= \READ{} \label{eq:arith-read}
  737. \end{equation}
  738. The third rule categorizes the negation of an $\Exp$ node as an
  739. $\Exp$.
  740. \begin{equation}
  741. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  742. \end{equation}
  743. We can apply these rules to categorize the ASTs that are in the
  744. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  745. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  746. following AST is an $\Exp$.
  747. \begin{center}
  748. \begin{minipage}{0.5\textwidth}
  749. \NEG{\INT{\code{8}}}
  750. \end{minipage}
  751. \begin{minipage}{0.25\textwidth}
  752. \begin{equation}
  753. \begin{tikzpicture}
  754. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  755. \node[draw, circle] (8) at (0, -1.2) {$8$};
  756. \draw[->] (minus) to (8);
  757. \end{tikzpicture}
  758. \label{eq:arith-neg8}
  759. \end{equation}
  760. \end{minipage}
  761. \end{center}
  762. The next two grammar rules are for addition and subtraction expressions:
  763. \begin{align}
  764. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  765. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  766. \end{align}
  767. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  768. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  769. \eqref{eq:arith-read}, and we have already categorized
  770. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  771. to show that
  772. \[
  773. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  774. \]
  775. is an $\Exp$ in the \LangInt{} language.
  776. If you have an AST for which these rules do not apply, then the
  777. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  778. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  779. because there is no rule for the \key{*} operator. Whenever we
  780. define a language with a grammar, the language includes only those
  781. programs that are justified by the grammar rules.
  782. {\if\edition\pythonEd
  783. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  784. There is a statement for printing the value of an expression
  785. \[
  786. \Stmt{} ::= \PRINT{\Exp}
  787. \]
  788. and a statement that evaluates an expression but ignores the result.
  789. \[
  790. \Stmt{} ::= \EXPR{\Exp}
  791. \]
  792. \fi}
  793. {\if\edition\racketEd
  794. The last grammar rule for \LangInt{} states that there is a
  795. \code{Program} node to mark the top of the whole program:
  796. \[
  797. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  798. \]
  799. The \code{Program} structure is defined as follows:
  800. \begin{lstlisting}
  801. (struct Program (info body))
  802. \end{lstlisting}
  803. where \code{body} is an expression. In further chapters, the \code{info}
  804. part is used to store auxiliary information, but for now it is
  805. just the empty list.
  806. \fi}
  807. {\if\edition\pythonEd
  808. The last grammar rule for \LangInt{} states that there is a
  809. \code{Module} node to mark the top of the whole program:
  810. \[
  811. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  812. \]
  813. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  814. this case, a list of statements.
  815. %
  816. The \code{Module} class is defined as follows
  817. \begin{lstlisting}
  818. class Module:
  819. def __init__(self, body):
  820. self.body = body
  821. \end{lstlisting}
  822. where \code{body} is a list of statements.
  823. \fi}
  824. It is common to have many grammar rules with the same left-hand side
  825. but different right-hand sides, such as the rules for $\Exp$ in the
  826. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  827. combine several right-hand sides into a single rule.
  828. The concrete syntax for \LangInt{} is shown in
  829. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  830. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.
  831. \racket{The \code{read-program} function provided in
  832. \code{utilities.rkt} of the support code reads a program from a file
  833. (the sequence of characters in the concrete syntax of Racket) and
  834. parses it into an abstract syntax tree. Refer to the description of
  835. \code{read-program} in appendix~\ref{appendix:utilities} for more
  836. details.}
  837. \python{The \code{parse} function in Python's \code{ast} module
  838. converts the concrete syntax (represented as a string) into an
  839. abstract syntax tree.}
  840. \newcommand{\LintGrammarRacket}{
  841. \begin{array}{rcl}
  842. \Type &::=& \key{Integer} \\
  843. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  844. \MID \CSUB{\Exp}{\Exp}
  845. \end{array}
  846. }
  847. \newcommand{\LintASTRacket}{
  848. \begin{array}{rcl}
  849. \Type &::=& \key{Integer} \\
  850. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  851. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  852. \end{array}
  853. }
  854. \newcommand{\LintGrammarPython}{
  855. \begin{array}{rcl}
  856. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  857. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  858. \end{array}
  859. }
  860. \newcommand{\LintASTPython}{
  861. \begin{array}{rcl}
  862. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  863. \itm{unaryop} &::= & \code{USub()} \\
  864. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  865. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  866. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  867. \end{array}
  868. }
  869. \begin{figure}[tp]
  870. \begin{tcolorbox}[colback=white]
  871. {\if\edition\racketEd
  872. \[
  873. \begin{array}{l}
  874. \LintGrammarRacket \\
  875. \begin{array}{rcl}
  876. \LangInt{} &::=& \Exp
  877. \end{array}
  878. \end{array}
  879. \]
  880. \fi}
  881. {\if\edition\pythonEd
  882. \[
  883. \begin{array}{l}
  884. \LintGrammarPython \\
  885. \begin{array}{rcl}
  886. \LangInt{} &::=& \Stmt^{*}
  887. \end{array}
  888. \end{array}
  889. \]
  890. \fi}
  891. \end{tcolorbox}
  892. \caption{The concrete syntax of \LangInt{}.}
  893. \label{fig:r0-concrete-syntax}
  894. \end{figure}
  895. \begin{figure}[tp]
  896. \begin{tcolorbox}[colback=white]
  897. {\if\edition\racketEd
  898. \[
  899. \begin{array}{l}
  900. \LintASTRacket{} \\
  901. \begin{array}{rcl}
  902. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  903. \end{array}
  904. \end{array}
  905. \]
  906. \fi}
  907. {\if\edition\pythonEd
  908. \[
  909. \begin{array}{l}
  910. \LintASTPython\\
  911. \begin{array}{rcl}
  912. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  913. \end{array}
  914. \end{array}
  915. \]
  916. \fi}
  917. \end{tcolorbox}
  918. \python{
  919. \index{subject}{Constant@\texttt{Constant}}
  920. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  921. \index{subject}{USub@\texttt{USub}}
  922. \index{subject}{inputint@\texttt{input\_int}}
  923. \index{subject}{Call@\texttt{Call}}
  924. \index{subject}{Name@\texttt{Name}}
  925. \index{subject}{BinOp@\texttt{BinOp}}
  926. \index{subject}{Add@\texttt{Add}}
  927. \index{subject}{Sub@\texttt{Sub}}
  928. \index{subject}{print@\texttt{print}}
  929. \index{subject}{Expr@\texttt{Expr}}
  930. \index{subject}{Module@\texttt{Module}}
  931. }
  932. \caption{The abstract syntax of \LangInt{}.}
  933. \label{fig:r0-syntax}
  934. \end{figure}
  935. \section{Pattern Matching}
  936. \label{sec:pattern-matching}
  937. As mentioned in section~\ref{sec:ast}, compilers often need to access
  938. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  939. provides the \texttt{match} feature to access the parts of a value.
  940. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  941. \begin{center}
  942. \begin{minipage}{0.5\textwidth}
  943. {\if\edition\racketEd
  944. \begin{lstlisting}
  945. (match ast1_1
  946. [(Prim op (list child1 child2))
  947. (print op)])
  948. \end{lstlisting}
  949. \fi}
  950. {\if\edition\pythonEd
  951. \begin{lstlisting}
  952. match ast1_1:
  953. case BinOp(child1, op, child2):
  954. print(op)
  955. \end{lstlisting}
  956. \fi}
  957. \end{minipage}
  958. \end{center}
  959. {\if\edition\racketEd
  960. %
  961. In this example, the \texttt{match} form checks whether the AST
  962. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  963. three pattern variables \texttt{op}, \texttt{child1}, and
  964. \texttt{child2}. In general, a match clause consists of a
  965. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  966. recursively defined to be a pattern variable, a structure name
  967. followed by a pattern for each of the structure's arguments, or an
  968. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  969. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  970. and chapter 9 of The Racket
  971. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  972. for complete descriptions of \code{match}.)
  973. %
  974. The body of a match clause may contain arbitrary Racket code. The
  975. pattern variables can be used in the scope of the body, such as
  976. \code{op} in \code{(print op)}.
  977. %
  978. \fi}
  979. %
  980. %
  981. {\if\edition\pythonEd
  982. %
  983. In the above example, the \texttt{match} form checks whether the AST
  984. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  985. three pattern variables \texttt{child1}, \texttt{op}, and
  986. \texttt{child2}, and then prints out the operator. In general, each
  987. \code{case} consists of a \emph{pattern} and a
  988. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  989. to be either a pattern variable, a class name followed by a pattern
  990. for each of its constructor's arguments, or other literals such as
  991. strings, lists, etc.
  992. %
  993. The body of each \code{case} may contain arbitrary Python code. The
  994. pattern variables can be used in the body, such as \code{op} in
  995. \code{print(op)}.
  996. %
  997. \fi}
  998. A \code{match} form may contain several clauses, as in the following
  999. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1000. the AST. The \code{match} proceeds through the clauses in order,
  1001. checking whether the pattern can match the input AST. The body of the
  1002. first clause that matches is executed. The output of \code{leaf} for
  1003. several ASTs is shown on the right side of the following:
  1004. \begin{center}
  1005. \begin{minipage}{0.6\textwidth}
  1006. {\if\edition\racketEd
  1007. \begin{lstlisting}
  1008. (define (leaf arith)
  1009. (match arith
  1010. [(Int n) #t]
  1011. [(Prim 'read '()) #t]
  1012. [(Prim '- (list e1)) #f]
  1013. [(Prim '+ (list e1 e2)) #f]
  1014. [(Prim '- (list e1 e2)) #f]))
  1015. (leaf (Prim 'read '()))
  1016. (leaf (Prim '- (list (Int 8))))
  1017. (leaf (Int 8))
  1018. \end{lstlisting}
  1019. \fi}
  1020. {\if\edition\pythonEd
  1021. \begin{lstlisting}
  1022. def leaf(arith):
  1023. match arith:
  1024. case Constant(n):
  1025. return True
  1026. case Call(Name('input_int'), []):
  1027. return True
  1028. case UnaryOp(USub(), e1):
  1029. return False
  1030. case BinOp(e1, Add(), e2):
  1031. return False
  1032. case BinOp(e1, Sub(), e2):
  1033. return False
  1034. print(leaf(Call(Name('input_int'), [])))
  1035. print(leaf(UnaryOp(USub(), eight)))
  1036. print(leaf(Constant(8)))
  1037. \end{lstlisting}
  1038. \fi}
  1039. \end{minipage}
  1040. \vrule
  1041. \begin{minipage}{0.25\textwidth}
  1042. {\if\edition\racketEd
  1043. \begin{lstlisting}
  1044. #t
  1045. #f
  1046. #t
  1047. \end{lstlisting}
  1048. \fi}
  1049. {\if\edition\pythonEd
  1050. \begin{lstlisting}
  1051. True
  1052. False
  1053. True
  1054. \end{lstlisting}
  1055. \fi}
  1056. \end{minipage}
  1057. \end{center}
  1058. When constructing a \code{match} expression, we refer to the grammar
  1059. definition to identify which nonterminal we are expecting to match
  1060. against, and then we make sure that (1) we have one
  1061. \racket{clause}\python{case} for each alternative of that nonterminal
  1062. and (2) the pattern in each \racket{clause}\python{case}
  1063. corresponds to the corresponding right-hand side of a grammar
  1064. rule. For the \code{match} in the \code{leaf} function, we refer to
  1065. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1066. nonterminal has four alternatives, so the \code{match} has four
  1067. \racket{clauses}\python{cases}. The pattern in each
  1068. \racket{clause}\python{case} corresponds to the right-hand side of a
  1069. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1070. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1071. translating from grammars to patterns, replace nonterminals such as
  1072. $\Exp$ with pattern variables of your choice (e.g., \code{e1} and
  1073. \code{e2}).
  1074. \section{Recursive Functions}
  1075. \label{sec:recursion}
  1076. \index{subject}{recursive function}
  1077. Programs are inherently recursive. For example, an expression is often
  1078. made of smaller expressions. Thus, the natural way to process an
  1079. entire program is to use a recursive function. As a first example of
  1080. such a recursive function, we define the function \code{is\_exp} as
  1081. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1082. value and determine whether or not it is an expression in \LangInt{}.
  1083. %
  1084. We say that a function is defined by \emph{structural recursion} if
  1085. it is defined using a sequence of match \racket{clauses}\python{cases}
  1086. that correspond to a grammar and the body of each
  1087. \racket{clause}\python{case} makes a recursive call on each child
  1088. node.\footnote{This principle of structuring code according to the
  1089. data definition is advocated in the book \emph{How to Design
  1090. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1091. second function, named \code{stmt}, that recognizes whether a value
  1092. is a \LangInt{} statement.} \python{Finally, }
  1093. Figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1094. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1095. In general, we can write one recursive function to handle each
  1096. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1097. two examples at the bottom of the figure, the first is in
  1098. \LangInt{} and the second is not.
  1099. \begin{figure}[tp]
  1100. \begin{tcolorbox}[colback=white]
  1101. {\if\edition\racketEd
  1102. \begin{lstlisting}
  1103. (define (is_exp ast)
  1104. (match ast
  1105. [(Int n) #t]
  1106. [(Prim 'read '()) #t]
  1107. [(Prim '- (list e)) (is_exp e)]
  1108. [(Prim '+ (list e1 e2))
  1109. (and (is_exp e1) (is_exp e2))]
  1110. [(Prim '- (list e1 e2))
  1111. (and (is_exp e1) (is_exp e2))]
  1112. [else #f]))
  1113. (define (is_Lint ast)
  1114. (match ast
  1115. [(Program '() e) (is_exp e)]
  1116. [else #f]))
  1117. (is_Lint (Program '() ast1_1)
  1118. (is_Lint (Program '()
  1119. (Prim '* (list (Prim 'read '())
  1120. (Prim '+ (list (Int 8)))))))
  1121. \end{lstlisting}
  1122. \fi}
  1123. {\if\edition\pythonEd
  1124. \begin{lstlisting}
  1125. def is_exp(e):
  1126. match e:
  1127. case Constant(n):
  1128. return True
  1129. case Call(Name('input_int'), []):
  1130. return True
  1131. case UnaryOp(USub(), e1):
  1132. return is_exp(e1)
  1133. case BinOp(e1, Add(), e2):
  1134. return is_exp(e1) and is_exp(e2)
  1135. case BinOp(e1, Sub(), e2):
  1136. return is_exp(e1) and is_exp(e2)
  1137. case _:
  1138. return False
  1139. def stmt(s):
  1140. match s:
  1141. case Expr(Call(Name('print'), [e])):
  1142. return is_exp(e)
  1143. case Expr(e):
  1144. return is_exp(e)
  1145. case _:
  1146. return False
  1147. def is_Lint(p):
  1148. match p:
  1149. case Module(body):
  1150. return all([stmt(s) for s in body])
  1151. case _:
  1152. return False
  1153. print(is_Lint(Module([Expr(ast1_1)])))
  1154. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1155. UnaryOp(Add(), Constant(8))))])))
  1156. \end{lstlisting}
  1157. \fi}
  1158. \end{tcolorbox}
  1159. \caption{Example of recursive functions for \LangInt{}. These functions
  1160. recognize whether an AST is in \LangInt{}.}
  1161. \label{fig:exp-predicate}
  1162. \end{figure}
  1163. %% You may be tempted to merge the two functions into one, like this:
  1164. %% \begin{center}
  1165. %% \begin{minipage}{0.5\textwidth}
  1166. %% \begin{lstlisting}
  1167. %% (define (Lint ast)
  1168. %% (match ast
  1169. %% [(Int n) #t]
  1170. %% [(Prim 'read '()) #t]
  1171. %% [(Prim '- (list e)) (Lint e)]
  1172. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1173. %% [(Program '() e) (Lint e)]
  1174. %% [else #f]))
  1175. %% \end{lstlisting}
  1176. %% \end{minipage}
  1177. %% \end{center}
  1178. %% %
  1179. %% Sometimes such a trick will save a few lines of code, especially when
  1180. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1181. %% \emph{not} recommended because it can get you into trouble.
  1182. %% %
  1183. %% For example, the above function is subtly wrong:
  1184. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1185. %% returns true when it should return false.
  1186. \section{Interpreters}
  1187. \label{sec:interp_Lint}
  1188. \index{subject}{interpreter}
  1189. The behavior of a program is defined by the specification of the
  1190. programming language.
  1191. %
  1192. \racket{For example, the Scheme language is defined in the report by
  1193. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1194. reference manual~\citep{plt-tr}.}
  1195. %
  1196. \python{For example, the Python language is defined in the Python
  1197. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1198. %
  1199. In this book we use interpreters to specify each language that we
  1200. consider. An interpreter that is designated as the definition of a
  1201. language is called a \emph{definitional
  1202. interpreter}~\citep{reynolds72:_def_interp}.
  1203. \index{subject}{definitional interpreter} We warm up by creating a
  1204. definitional interpreter for the \LangInt{} language. This interpreter
  1205. serves as a second example of structural recursion. The definition of the
  1206. \code{interp\_Lint} function is shown in
  1207. figure~\ref{fig:interp_Lint}.
  1208. %
  1209. \racket{The body of the function is a match on the input program
  1210. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1211. which in turn has one match clause per grammar rule for \LangInt{}
  1212. expressions.}
  1213. %
  1214. \python{The body of the function matches on the \code{Module} AST node
  1215. and then invokes \code{interp\_stmt} on each statement in the
  1216. module. The \code{interp\_stmt} function includes a case for each
  1217. grammar rule of the \Stmt{} nonterminal and it calls
  1218. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1219. function includes a case for each grammar rule of the \Exp{}
  1220. nonterminal.}
  1221. \begin{figure}[tp]
  1222. \begin{tcolorbox}[colback=white]
  1223. {\if\edition\racketEd
  1224. \begin{lstlisting}
  1225. (define (interp_exp e)
  1226. (match e
  1227. [(Int n) n]
  1228. [(Prim 'read '())
  1229. (define r (read))
  1230. (cond [(fixnum? r) r]
  1231. [else (error 'interp_exp "read expected an integer" r)])]
  1232. [(Prim '- (list e))
  1233. (define v (interp_exp e))
  1234. (fx- 0 v)]
  1235. [(Prim '+ (list e1 e2))
  1236. (define v1 (interp_exp e1))
  1237. (define v2 (interp_exp e2))
  1238. (fx+ v1 v2)]
  1239. [(Prim '- (list e1 e2))
  1240. (define v1 ((interp-exp env) e1))
  1241. (define v2 ((interp-exp env) e2))
  1242. (fx- v1 v2)]))
  1243. (define (interp_Lint p)
  1244. (match p
  1245. [(Program '() e) (interp_exp e)]))
  1246. \end{lstlisting}
  1247. \fi}
  1248. {\if\edition\pythonEd
  1249. \begin{lstlisting}
  1250. def interp_exp(e):
  1251. match e:
  1252. case BinOp(left, Add(), right):
  1253. l = interp_exp(left); r = interp_exp(right)
  1254. return l + r
  1255. case BinOp(left, Sub(), right):
  1256. l = interp_exp(left); r = interp_exp(right)
  1257. return l - r
  1258. case UnaryOp(USub(), v):
  1259. return - interp_exp(v)
  1260. case Constant(value):
  1261. return value
  1262. case Call(Name('input_int'), []):
  1263. return int(input())
  1264. def interp_stmt(s):
  1265. match s:
  1266. case Expr(Call(Name('print'), [arg])):
  1267. print(interp_exp(arg))
  1268. case Expr(value):
  1269. interp_exp(value)
  1270. def interp_Lint(p):
  1271. match p:
  1272. case Module(body):
  1273. for s in body:
  1274. interp_stmt(s)
  1275. \end{lstlisting}
  1276. \fi}
  1277. \end{tcolorbox}
  1278. \caption{Interpreter for the \LangInt{} language.}
  1279. \label{fig:interp_Lint}
  1280. \end{figure}
  1281. Let us consider the result of interpreting a few \LangInt{} programs. The
  1282. following program adds two integers:
  1283. {\if\edition\racketEd
  1284. \begin{lstlisting}
  1285. (+ 10 32)
  1286. \end{lstlisting}
  1287. \fi}
  1288. {\if\edition\pythonEd
  1289. \begin{lstlisting}
  1290. print(10 + 32)
  1291. \end{lstlisting}
  1292. \fi}
  1293. %
  1294. \noindent The result is \key{42}, the answer to life, the universe,
  1295. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1296. the Galaxy} by Douglas Adams.}
  1297. %
  1298. We wrote this program in concrete syntax, whereas the parsed
  1299. abstract syntax is
  1300. {\if\edition\racketEd
  1301. \begin{lstlisting}
  1302. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1303. \end{lstlisting}
  1304. \fi}
  1305. {\if\edition\pythonEd
  1306. \begin{lstlisting}
  1307. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1308. \end{lstlisting}
  1309. \fi}
  1310. The following program demonstrates that expressions may be nested within
  1311. each other, in this case nesting several additions and negations.
  1312. {\if\edition\racketEd
  1313. \begin{lstlisting}
  1314. (+ 10 (- (+ 12 20)))
  1315. \end{lstlisting}
  1316. \fi}
  1317. {\if\edition\pythonEd
  1318. \begin{lstlisting}
  1319. print(10 + -(12 + 20))
  1320. \end{lstlisting}
  1321. \fi}
  1322. %
  1323. \noindent What is the result of this program?
  1324. {\if\edition\racketEd
  1325. As mentioned previously, the \LangInt{} language does not support
  1326. arbitrarily large integers but only $63$-bit integers, so we
  1327. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1328. in Racket.
  1329. Suppose that
  1330. \[
  1331. n = 999999999999999999
  1332. \]
  1333. which indeed fits in $63$ bits. What happens when we run the
  1334. following program in our interpreter?
  1335. \begin{lstlisting}
  1336. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1337. \end{lstlisting}
  1338. It produces the following error:
  1339. \begin{lstlisting}
  1340. fx+: result is not a fixnum
  1341. \end{lstlisting}
  1342. We establish the convention that if running the definitional
  1343. interpreter on a program produces an error, then the meaning of that
  1344. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1345. error is a \code{trapped-error}. A compiler for the language is under
  1346. no obligation regarding programs with unspecified behavior; it does
  1347. not have to produce an executable, and if it does, that executable can
  1348. do anything. On the other hand, if the error is a
  1349. \code{trapped-error}, then the compiler must produce an executable and
  1350. it is required to report that an error occurred. To signal an error,
  1351. exit with a return code of \code{255}. The interpreters in chapters
  1352. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1353. \code{trapped-error}.
  1354. \fi}
  1355. % TODO: how to deal with too-large integers in the Python interpreter?
  1356. %% This convention applies to the languages defined in this
  1357. %% book, as a way to simplify the student's task of implementing them,
  1358. %% but this convention is not applicable to all programming languages.
  1359. %%
  1360. The last feature of the \LangInt{} language, the \READOP{} operation,
  1361. prompts the user of the program for an integer. Recall that program
  1362. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1363. \code{8}. So, if we run {\if\edition\racketEd
  1364. \begin{lstlisting}
  1365. (interp_Lint (Program '() ast1_1))
  1366. \end{lstlisting}
  1367. \fi}
  1368. {\if\edition\pythonEd
  1369. \begin{lstlisting}
  1370. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1371. \end{lstlisting}
  1372. \fi}
  1373. \noindent and if the input is \code{50}, the result is \code{42}.
  1374. We include the \READOP{} operation in \LangInt{} so that a clever
  1375. student cannot implement a compiler for \LangInt{} that simply runs
  1376. the interpreter during compilation to obtain the output and then
  1377. generates the trivial code to produce the output.\footnote{Yes, a
  1378. clever student did this in the first instance of this course!}
  1379. The job of a compiler is to translate a program in one language into a
  1380. program in another language so that the output program behaves the
  1381. same way as the input program. This idea is depicted in the
  1382. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1383. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1384. Given a compiler that translates from language $\mathcal{L}_1$ to
  1385. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1386. compiler must translate it into some program $P_2$ such that
  1387. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1388. same input $i$ yields the same output $o$.
  1389. \begin{equation} \label{eq:compile-correct}
  1390. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1391. \node (p1) at (0, 0) {$P_1$};
  1392. \node (p2) at (3, 0) {$P_2$};
  1393. \node (o) at (3, -2.5) {$o$};
  1394. \path[->] (p1) edge [above] node {compile} (p2);
  1395. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1396. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1397. \end{tikzpicture}
  1398. \end{equation}
  1399. In the next section we see our first example of a compiler.
  1400. \section{Example Compiler: A Partial Evaluator}
  1401. \label{sec:partial-evaluation}
  1402. In this section we consider a compiler that translates \LangInt{}
  1403. programs into \LangInt{} programs that may be more efficient. The
  1404. compiler eagerly computes the parts of the program that do not depend
  1405. on any inputs, a process known as \emph{partial
  1406. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1407. For example, given the following program
  1408. {\if\edition\racketEd
  1409. \begin{lstlisting}
  1410. (+ (read) (- (+ 5 3)))
  1411. \end{lstlisting}
  1412. \fi}
  1413. {\if\edition\pythonEd
  1414. \begin{lstlisting}
  1415. print(input_int() + -(5 + 3) )
  1416. \end{lstlisting}
  1417. \fi}
  1418. \noindent our compiler translates it into the program
  1419. {\if\edition\racketEd
  1420. \begin{lstlisting}
  1421. (+ (read) -8)
  1422. \end{lstlisting}
  1423. \fi}
  1424. {\if\edition\pythonEd
  1425. \begin{lstlisting}
  1426. print(input_int() + -8)
  1427. \end{lstlisting}
  1428. \fi}
  1429. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1430. evaluator for the \LangInt{} language. The output of the partial evaluator
  1431. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1432. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1433. whereas the code for partially evaluating the negation and addition
  1434. operations is factored into three auxiliary functions:
  1435. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1436. functions is the output of partially evaluating the children.
  1437. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1438. arguments are integers and if they are, perform the appropriate
  1439. arithmetic. Otherwise, they create an AST node for the arithmetic
  1440. operation.
  1441. \begin{figure}[tp]
  1442. \begin{tcolorbox}[colback=white]
  1443. {\if\edition\racketEd
  1444. \begin{lstlisting}
  1445. (define (pe_neg r)
  1446. (match r
  1447. [(Int n) (Int (fx- 0 n))]
  1448. [else (Prim '- (list r))]))
  1449. (define (pe_add r1 r2)
  1450. (match* (r1 r2)
  1451. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1452. [(_ _) (Prim '+ (list r1 r2))]))
  1453. (define (pe_sub r1 r2)
  1454. (match* (r1 r2)
  1455. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1456. [(_ _) (Prim '- (list r1 r2))]))
  1457. (define (pe_exp e)
  1458. (match e
  1459. [(Int n) (Int n)]
  1460. [(Prim 'read '()) (Prim 'read '())]
  1461. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1462. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1463. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1464. (define (pe_Lint p)
  1465. (match p
  1466. [(Program '() e) (Program '() (pe_exp e))]))
  1467. \end{lstlisting}
  1468. \fi}
  1469. {\if\edition\pythonEd
  1470. \begin{lstlisting}
  1471. def pe_neg(r):
  1472. match r:
  1473. case Constant(n):
  1474. return Constant(-n)
  1475. case _:
  1476. return UnaryOp(USub(), r)
  1477. def pe_add(r1, r2):
  1478. match (r1, r2):
  1479. case (Constant(n1), Constant(n2)):
  1480. return Constant(n1 + n2)
  1481. case _:
  1482. return BinOp(r1, Add(), r2)
  1483. def pe_sub(r1, r2):
  1484. match (r1, r2):
  1485. case (Constant(n1), Constant(n2)):
  1486. return Constant(n1 - n2)
  1487. case _:
  1488. return BinOp(r1, Sub(), r2)
  1489. def pe_exp(e):
  1490. match e:
  1491. case BinOp(left, Add(), right):
  1492. return pe_add(pe_exp(left), pe_exp(right))
  1493. case BinOp(left, Sub(), right):
  1494. return pe_sub(pe_exp(left), pe_exp(right))
  1495. case UnaryOp(USub(), v):
  1496. return pe_neg(pe_exp(v))
  1497. case Constant(value):
  1498. return e
  1499. case Call(Name('input_int'), []):
  1500. return e
  1501. def pe_stmt(s):
  1502. match s:
  1503. case Expr(Call(Name('print'), [arg])):
  1504. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1505. case Expr(value):
  1506. return Expr(pe_exp(value))
  1507. def pe_P_int(p):
  1508. match p:
  1509. case Module(body):
  1510. new_body = [pe_stmt(s) for s in body]
  1511. return Module(new_body)
  1512. \end{lstlisting}
  1513. \fi}
  1514. \end{tcolorbox}
  1515. \caption{A partial evaluator for \LangInt{}.}
  1516. \label{fig:pe-arith}
  1517. \end{figure}
  1518. To gain some confidence that the partial evaluator is correct, we can
  1519. test whether it produces programs that produce the same result as the
  1520. input programs. That is, we can test whether it satisfies the diagram
  1521. of \eqref{eq:compile-correct}.
  1522. %
  1523. {\if\edition\racketEd
  1524. The following code runs the partial evaluator on several examples and
  1525. tests the output program. The \texttt{parse-program} and
  1526. \texttt{assert} functions are defined in
  1527. appendix~\ref{appendix:utilities}.\\
  1528. \begin{minipage}{1.0\textwidth}
  1529. \begin{lstlisting}
  1530. (define (test_pe p)
  1531. (assert "testing pe_Lint"
  1532. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1533. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1534. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1535. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1536. \end{lstlisting}
  1537. \end{minipage}
  1538. \fi}
  1539. % TODO: python version of testing the PE
  1540. \begin{exercise}\normalfont\normalsize
  1541. Create three programs in the \LangInt{} language and test whether
  1542. partially evaluating them with \code{pe\_Lint} and then
  1543. interpreting them with \code{interp\_Lint} gives the same result
  1544. as directly interpreting them with \code{interp\_Lint}.
  1545. \end{exercise}
  1546. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1547. \chapter{Integers and Variables}
  1548. \label{ch:Lvar}
  1549. \setcounter{footnote}{0}
  1550. This chapter covers compiling a subset of
  1551. \racket{Racket}\python{Python} to x86-64 assembly
  1552. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1553. integer arithmetic and local variables. We often refer to x86-64
  1554. simply as x86. The chapter first describes the \LangVar{} language
  1555. (section~\ref{sec:s0}) and then introduces x86 assembly
  1556. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1557. discuss only the instructions needed for compiling \LangVar{}. We
  1558. introduce more x86 instructions in subsequent chapters. After
  1559. introducing \LangVar{} and x86, we reflect on their differences and
  1560. create a plan to break down the translation from \LangVar{} to x86
  1561. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1562. the chapter gives detailed hints regarding each step. We aim to give
  1563. enough hints that the well-prepared reader, together with a few
  1564. friends, can implement a compiler from \LangVar{} to x86 in a short
  1565. time. To suggest the scale of this first compiler, we note that the
  1566. instructor solution for the \LangVar{} compiler is approximately
  1567. \racket{500}\python{300} lines of code.
  1568. \section{The \LangVar{} Language}
  1569. \label{sec:s0}
  1570. \index{subject}{variable}
  1571. The \LangVar{} language extends the \LangInt{} language with
  1572. variables. The concrete syntax of the \LangVar{} language is defined
  1573. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax} and
  1574. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1575. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1576. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1577. \key{-} is a unary operator, and \key{+} is a binary operator.
  1578. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1579. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1580. the top of the program.
  1581. %% The $\itm{info}$
  1582. %% field of the \key{Program} structure contains an \emph{association
  1583. %% list} (a list of key-value pairs) that is used to communicate
  1584. %% auxiliary data from one compiler pass the next.
  1585. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1586. exhibit several compilation techniques.
  1587. \newcommand{\LvarGrammarRacket}{
  1588. \begin{array}{rcl}
  1589. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1590. \end{array}
  1591. }
  1592. \newcommand{\LvarASTRacket}{
  1593. \begin{array}{rcl}
  1594. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1595. \end{array}
  1596. }
  1597. \newcommand{\LvarGrammarPython}{
  1598. \begin{array}{rcl}
  1599. \Exp &::=& \Var{} \\
  1600. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1601. \end{array}
  1602. }
  1603. \newcommand{\LvarASTPython}{
  1604. \begin{array}{rcl}
  1605. \Exp{} &::=& \VAR{\Var{}} \\
  1606. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1607. \end{array}
  1608. }
  1609. \begin{figure}[tp]
  1610. \centering
  1611. \begin{tcolorbox}[colback=white]
  1612. {\if\edition\racketEd
  1613. \[
  1614. \begin{array}{l}
  1615. \gray{\LintGrammarRacket{}} \\ \hline
  1616. \LvarGrammarRacket{} \\
  1617. \begin{array}{rcl}
  1618. \LangVarM{} &::=& \Exp
  1619. \end{array}
  1620. \end{array}
  1621. \]
  1622. \fi}
  1623. {\if\edition\pythonEd
  1624. \[
  1625. \begin{array}{l}
  1626. \gray{\LintGrammarPython} \\ \hline
  1627. \LvarGrammarPython \\
  1628. \begin{array}{rcl}
  1629. \LangVarM{} &::=& \Stmt^{*}
  1630. \end{array}
  1631. \end{array}
  1632. \]
  1633. \fi}
  1634. \end{tcolorbox}
  1635. \caption{The concrete syntax of \LangVar{}.}
  1636. \label{fig:Lvar-concrete-syntax}
  1637. \end{figure}
  1638. \begin{figure}[tp]
  1639. \centering
  1640. \begin{tcolorbox}[colback=white]
  1641. {\if\edition\racketEd
  1642. \[
  1643. \begin{array}{l}
  1644. \gray{\LintASTRacket{}} \\ \hline
  1645. \LvarASTRacket \\
  1646. \begin{array}{rcl}
  1647. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1648. \end{array}
  1649. \end{array}
  1650. \]
  1651. \fi}
  1652. {\if\edition\pythonEd
  1653. \[
  1654. \begin{array}{l}
  1655. \gray{\LintASTPython}\\ \hline
  1656. \LvarASTPython \\
  1657. \begin{array}{rcl}
  1658. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1659. \end{array}
  1660. \end{array}
  1661. \]
  1662. \fi}
  1663. \end{tcolorbox}
  1664. \caption{The abstract syntax of \LangVar{}.}
  1665. \label{fig:Lvar-syntax}
  1666. \end{figure}
  1667. {\if\edition\racketEd
  1668. Let us dive further into the syntax and semantics of the \LangVar{}
  1669. language. The \key{let} feature defines a variable for use within its
  1670. body and initializes the variable with the value of an expression.
  1671. The abstract syntax for \key{let} is shown in
  1672. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1673. \begin{lstlisting}
  1674. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1675. \end{lstlisting}
  1676. For example, the following program initializes \code{x} to $32$ and then
  1677. evaluates the body \code{(+ 10 x)}, producing $42$.
  1678. \begin{lstlisting}
  1679. (let ([x (+ 12 20)]) (+ 10 x))
  1680. \end{lstlisting}
  1681. \fi}
  1682. %
  1683. {\if\edition\pythonEd
  1684. %
  1685. The \LangVar{} language includes assignment statements, which define a
  1686. variable for use in later statements and initializes the variable with
  1687. the value of an expression. The abstract syntax for assignment is
  1688. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1689. assignment is \index{subject}{Assign@\texttt{Assign}}
  1690. \begin{lstlisting}
  1691. |$\itm{var}$| = |$\itm{exp}$|
  1692. \end{lstlisting}
  1693. For example, the following program initializes the variable \code{x}
  1694. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1695. \begin{lstlisting}
  1696. x = 12 + 20
  1697. print(10 + x)
  1698. \end{lstlisting}
  1699. \fi}
  1700. {\if\edition\racketEd
  1701. %
  1702. When there are multiple \key{let}s for the same variable, the closest
  1703. enclosing \key{let} is used. That is, variable definitions overshadow
  1704. prior definitions. Consider the following program with two \key{let}s
  1705. that define two variables named \code{x}. Can you figure out the
  1706. result?
  1707. \begin{lstlisting}
  1708. (let ([x 32]) (+ (let ([x 10]) x) x))
  1709. \end{lstlisting}
  1710. For the purposes of depicting which variable occurrences correspond to
  1711. which definitions, the following shows the \code{x}'s annotated with
  1712. subscripts to distinguish them. Double check that your answer for the
  1713. previous program is the same as your answer for this annotated version
  1714. of the program.
  1715. \begin{lstlisting}
  1716. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1717. \end{lstlisting}
  1718. The initializing expression is always evaluated before the body of the
  1719. \key{let}, so in the following, the \key{read} for \code{x} is
  1720. performed before the \key{read} for \code{y}. Given the input
  1721. $52$ then $10$, the following produces $42$ (not $-42$).
  1722. \begin{lstlisting}
  1723. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1724. \end{lstlisting}
  1725. \fi}
  1726. \subsection{Extensible Interpreters via Method Overriding}
  1727. \label{sec:extensible-interp}
  1728. To prepare for discussing the interpreter of \LangVar{}, we explain
  1729. why we implement it in an object-oriented style. Throughout this book
  1730. we define many interpreters, one for each language that we
  1731. study. Because each language builds on the prior one, there is a lot
  1732. of commonality between these interpreters. We want to write down the
  1733. common parts just once instead of many times. A naive interpreter for
  1734. \LangVar{} would handle the \racket{cases for variables and
  1735. \code{let}} \python{case for variables} but dispatch to an
  1736. interpreter for \LangInt{} in the rest of the cases. The following
  1737. code sketches this idea. (We explain the \code{env} parameter in
  1738. section~\ref{sec:interp-Lvar}.)
  1739. \begin{center}
  1740. {\if\edition\racketEd
  1741. \begin{minipage}{0.45\textwidth}
  1742. \begin{lstlisting}
  1743. (define ((interp_Lint env) e)
  1744. (match e
  1745. [(Prim '- (list e1))
  1746. (fx- 0 ((interp_Lint env) e1))]
  1747. ...))
  1748. \end{lstlisting}
  1749. \end{minipage}
  1750. \begin{minipage}{0.45\textwidth}
  1751. \begin{lstlisting}
  1752. (define ((interp_Lvar env) e)
  1753. (match e
  1754. [(Var x)
  1755. (dict-ref env x)]
  1756. [(Let x e body)
  1757. (define v ((interp_exp env) e))
  1758. (define env^ (dict-set env x v))
  1759. ((interp_exp env^) body)]
  1760. [else ((interp_Lint env) e)]))
  1761. \end{lstlisting}
  1762. \end{minipage}
  1763. \fi}
  1764. {\if\edition\pythonEd
  1765. \begin{minipage}{0.45\textwidth}
  1766. \begin{lstlisting}
  1767. def interp_Lint(e, env):
  1768. match e:
  1769. case UnaryOp(USub(), e1):
  1770. return - interp_Lint(e1, env)
  1771. ...
  1772. \end{lstlisting}
  1773. \end{minipage}
  1774. \begin{minipage}{0.45\textwidth}
  1775. \begin{lstlisting}
  1776. def interp_Lvar(e, env):
  1777. match e:
  1778. case Name(id):
  1779. return env[id]
  1780. case _:
  1781. return interp_Lint(e, env)
  1782. \end{lstlisting}
  1783. \end{minipage}
  1784. \fi}
  1785. \end{center}
  1786. The problem with this naive approach is that it does not handle
  1787. situations in which an \LangVar{} feature, such as a variable, is
  1788. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1789. in the following program.
  1790. {\if\edition\racketEd
  1791. \begin{lstlisting}
  1792. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1793. \end{lstlisting}
  1794. \fi}
  1795. {\if\edition\pythonEd
  1796. \begin{minipage}{0.96\textwidth}
  1797. \begin{lstlisting}
  1798. y = 10
  1799. print(-y)
  1800. \end{lstlisting}
  1801. \end{minipage}
  1802. \fi}
  1803. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1804. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1805. then it recursively calls \code{interp\_Lint} again on its argument.
  1806. Because there is no case for \code{Var} in \code{interp\_Lint}, we get
  1807. an error!
  1808. To make our interpreters extensible we need something called
  1809. \emph{open recursion}\index{subject}{open recursion}, in which the
  1810. tying of the recursive knot is delayed until the functions are
  1811. composed. Object-oriented languages provide open recursion via method
  1812. overriding\index{subject}{method overriding}. The following code uses
  1813. method overriding to interpret \LangInt{} and \LangVar{} using
  1814. %
  1815. \racket{the
  1816. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1817. \index{subject}{class} feature of Racket.}
  1818. %
  1819. \python{a Python \code{class} definition.}
  1820. %
  1821. We define one class for each language and define a method for
  1822. interpreting expressions inside each class. The class for \LangVar{}
  1823. inherits from the class for \LangInt{}, and the method
  1824. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1825. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1826. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1827. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1828. \code{interp\_exp} in \LangInt{}.
  1829. \begin{center}
  1830. \hspace{-20pt}
  1831. {\if\edition\racketEd
  1832. \begin{minipage}{0.45\textwidth}
  1833. \begin{lstlisting}
  1834. (define interp-Lint-class
  1835. (class object%
  1836. (define/public ((interp_exp env) e)
  1837. (match e
  1838. [(Prim '- (list e))
  1839. (fx- 0 ((interp_exp env) e))]
  1840. ...))
  1841. ...))
  1842. \end{lstlisting}
  1843. \end{minipage}
  1844. \begin{minipage}{0.45\textwidth}
  1845. \begin{lstlisting}
  1846. (define interp-Lvar-class
  1847. (class interp-Lint-class
  1848. (define/override ((interp_exp env) e)
  1849. (match e
  1850. [(Var x)
  1851. (dict-ref env x)]
  1852. [(Let x e body)
  1853. (define v ((interp_exp env) e))
  1854. (define env^ (dict-set env x v))
  1855. ((interp_exp env^) body)]
  1856. [else
  1857. (super (interp_exp env) e)]))
  1858. ...
  1859. ))
  1860. \end{lstlisting}
  1861. \end{minipage}
  1862. \fi}
  1863. {\if\edition\pythonEd
  1864. \begin{minipage}{0.45\textwidth}
  1865. \begin{lstlisting}
  1866. class InterpLint:
  1867. def interp_exp(e):
  1868. match e:
  1869. case UnaryOp(USub(), e1):
  1870. return -self.interp_exp(e1)
  1871. ...
  1872. ...
  1873. \end{lstlisting}
  1874. \end{minipage}
  1875. \begin{minipage}{0.45\textwidth}
  1876. \begin{lstlisting}
  1877. def InterpLvar(InterpLint):
  1878. def interp_exp(e):
  1879. match e:
  1880. case Name(id):
  1881. return env[id]
  1882. case _:
  1883. return super().interp_exp(e)
  1884. ...
  1885. \end{lstlisting}
  1886. \end{minipage}
  1887. \fi}
  1888. \end{center}
  1889. Getting back to the troublesome example, repeated here
  1890. {\if\edition\racketEd
  1891. \begin{lstlisting}
  1892. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1893. \end{lstlisting}
  1894. \fi}
  1895. {\if\edition\pythonEd
  1896. \begin{lstlisting}
  1897. y = 10
  1898. print(-y)
  1899. \end{lstlisting}
  1900. \fi}
  1901. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1902. \racket{on this expression,}
  1903. \python{on the \code{-y} expression,}
  1904. %
  1905. which we call \code{e0}, by creating an object of the \LangVar{} class
  1906. and calling the \code{interp\_exp} method
  1907. {\if\edition\racketEd
  1908. \begin{lstlisting}
  1909. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1910. \end{lstlisting}
  1911. \fi}
  1912. {\if\edition\pythonEd
  1913. \begin{lstlisting}
  1914. InterpLvar().interp_exp(e0)
  1915. \end{lstlisting}
  1916. \fi}
  1917. \noindent To process the \code{-} operator, the default case of
  1918. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1919. method in \LangInt{}. But then for the recursive method call, it
  1920. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1921. \code{Var} node is handled correctly. Thus, method overriding gives us
  1922. the open recursion that we need to implement our interpreters in an
  1923. extensible way.
  1924. \subsection{Definitional Interpreter for \LangVar{}}
  1925. \label{sec:interp-Lvar}
  1926. Having justified the use of classes and methods to implement
  1927. interpreters, we revisit the definitional interpreter for \LangInt{}
  1928. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1929. create an interpreter for \LangVar{}, shown in figure~\ref{fig:interp-Lvar}.
  1930. The interpreter for \LangVar{} adds two new \key{match} cases for
  1931. variables and \racket{\key{let}}\python{assignment}. For
  1932. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  1933. value bound to a variable to all the uses of the variable. To
  1934. accomplish this, we maintain a mapping from variables to values called
  1935. an \emph{environment}\index{subject}{environment}.
  1936. %
  1937. We use
  1938. %
  1939. \racket{an association list (alist) }%
  1940. %
  1941. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1942. %
  1943. to represent the environment.
  1944. %
  1945. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1946. and the \code{racket/dict} package.}
  1947. %
  1948. The \code{interp\_exp} function takes the current environment,
  1949. \code{env}, as an extra parameter. When the interpreter encounters a
  1950. variable, it looks up the corresponding value in the dictionary.
  1951. %
  1952. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1953. initializing expression, extends the environment with the result
  1954. value bound to the variable, using \code{dict-set}, then evaluates
  1955. the body of the \key{Let}.}
  1956. %
  1957. \python{When the interpreter encounters an assignment, it evaluates
  1958. the initializing expression and then associates the resulting value
  1959. with the variable in the environment.}
  1960. \begin{figure}[tp]
  1961. \begin{tcolorbox}[colback=white]
  1962. {\if\edition\racketEd
  1963. \begin{lstlisting}
  1964. (define interp-Lint-class
  1965. (class object%
  1966. (super-new)
  1967. (define/public ((interp_exp env) e)
  1968. (match e
  1969. [(Int n) n]
  1970. [(Prim 'read '())
  1971. (define r (read))
  1972. (cond [(fixnum? r) r]
  1973. [else (error 'interp_exp "expected an integer" r)])]
  1974. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1975. [(Prim '+ (list e1 e2))
  1976. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1977. [(Prim '- (list e1 e2))
  1978. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1979. (define/public (interp_program p)
  1980. (match p
  1981. [(Program '() e) ((interp_exp '()) e)]))
  1982. ))
  1983. \end{lstlisting}
  1984. \fi}
  1985. {\if\edition\pythonEd
  1986. \begin{lstlisting}
  1987. class InterpLint:
  1988. def interp_exp(self, e, env):
  1989. match e:
  1990. case BinOp(left, Add(), right):
  1991. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1992. case BinOp(left, Sub(), right):
  1993. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1994. case UnaryOp(USub(), v):
  1995. return - self.interp_exp(v, env)
  1996. case Constant(value):
  1997. return value
  1998. case Call(Name('input_int'), []):
  1999. return int(input())
  2000. def interp_stmts(self, ss, env):
  2001. if len(ss) == 0:
  2002. return
  2003. match ss[0]:
  2004. case Expr(Call(Name('print'), [arg])):
  2005. print(self.interp_exp(arg, env), end='')
  2006. return self.interp_stmts(ss[1:], env)
  2007. case Expr(value):
  2008. self.interp_exp(value, env)
  2009. return self.interp_stmts(ss[1:], env)
  2010. def interp(self, p):
  2011. match p:
  2012. case Module(body):
  2013. self.interp_stmts(body, {})
  2014. def interp_Lint(p):
  2015. return InterpLint().interp(p)
  2016. \end{lstlisting}
  2017. \fi}
  2018. \end{tcolorbox}
  2019. \caption{Interpreter for \LangInt{} as a class.}
  2020. \label{fig:interp-Lint-class}
  2021. \end{figure}
  2022. \begin{figure}[tp]
  2023. \begin{tcolorbox}[colback=white]
  2024. {\if\edition\racketEd
  2025. \begin{lstlisting}
  2026. (define interp-Lvar-class
  2027. (class interp-Lint-class
  2028. (super-new)
  2029. (define/override ((interp_exp env) e)
  2030. (match e
  2031. [(Var x) (dict-ref env x)]
  2032. [(Let x e body)
  2033. (define new-env (dict-set env x ((interp_exp env) e)))
  2034. ((interp_exp new-env) body)]
  2035. [else ((super interp-exp env) e)]))
  2036. ))
  2037. (define (interp_Lvar p)
  2038. (send (new interp-Lvar-class) interp_program p))
  2039. \end{lstlisting}
  2040. \fi}
  2041. {\if\edition\pythonEd
  2042. \begin{lstlisting}
  2043. class InterpLvar(InterpLint):
  2044. def interp_exp(self, e, env):
  2045. match e:
  2046. case Name(id):
  2047. return env[id]
  2048. case _:
  2049. return super().interp_exp(e, env)
  2050. def interp_stmts(self, ss, env):
  2051. if len(ss) == 0:
  2052. return
  2053. match ss[0]:
  2054. case Assign([lhs], value):
  2055. env[lhs.id] = self.interp_exp(value, env)
  2056. return self.interp_stmts(ss[1:], env)
  2057. case _:
  2058. return super().interp_stmts(ss, env)
  2059. def interp_Lvar(p):
  2060. return InterpLvar().interp(p)
  2061. \end{lstlisting}
  2062. \fi}
  2063. \end{tcolorbox}
  2064. \caption{Interpreter for the \LangVar{} language.}
  2065. \label{fig:interp-Lvar}
  2066. \end{figure}
  2067. {\if\edition\racketEd
  2068. \begin{figure}[tp]
  2069. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2070. \small
  2071. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2072. An \emph{association list} (called an alist) is a list of key-value pairs.
  2073. For example, we can map people to their ages with an alist
  2074. \index{subject}{alist}\index{subject}{association list}
  2075. \begin{lstlisting}[basicstyle=\ttfamily]
  2076. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2077. \end{lstlisting}
  2078. The \emph{dictionary} interface is for mapping keys to values.
  2079. Every alist implements this interface. \index{subject}{dictionary}
  2080. The package
  2081. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2082. provides many functions for working with dictionaries, such as
  2083. \begin{description}
  2084. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2085. returns the value associated with the given $\itm{key}$.
  2086. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2087. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2088. and otherwise is the same as $\itm{dict}$.
  2089. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2090. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2091. of keys and values in $\itm{dict}$. For example, the following
  2092. creates a new alist in which the ages are incremented:
  2093. \end{description}
  2094. \vspace{-10pt}
  2095. \begin{lstlisting}[basicstyle=\ttfamily]
  2096. (for/list ([(k v) (in-dict ages)])
  2097. (cons k (add1 v)))
  2098. \end{lstlisting}
  2099. \end{tcolorbox}
  2100. %\end{wrapfigure}
  2101. \caption{Association lists implement the dictionary interface.}
  2102. \label{fig:alist}
  2103. \end{figure}
  2104. \fi}
  2105. The goal for this chapter is to implement a compiler that translates
  2106. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2107. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2108. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2109. That is, they output the same integer $n$. We depict this correctness
  2110. criteria in the following diagram:
  2111. \[
  2112. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2113. \node (p1) at (0, 0) {$P_1$};
  2114. \node (p2) at (4, 0) {$P_2$};
  2115. \node (o) at (4, -2) {$n$};
  2116. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2117. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2118. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2119. \end{tikzpicture}
  2120. \]
  2121. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2122. compiling \LangVar{}.
  2123. \section{The \LangXInt{} Assembly Language}
  2124. \label{sec:x86}
  2125. \index{subject}{x86}
  2126. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2127. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2128. assembler.
  2129. %
  2130. A program begins with a \code{main} label followed by a sequence of
  2131. instructions. The \key{globl} directive makes the \key{main} procedure
  2132. externally visible so that the operating system can call it.
  2133. %
  2134. An x86 program is stored in the computer's memory. For our purposes,
  2135. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2136. values. The computer has a \emph{program counter}
  2137. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2138. \code{rip} register that points to the address of the next instruction
  2139. to be executed. For most instructions, the program counter is
  2140. incremented after the instruction is executed so that it points to the
  2141. next instruction in memory. Most x86 instructions take two operands,
  2142. each of which is an integer constant (called an \emph{immediate
  2143. value}\index{subject}{immediate value}), a
  2144. \emph{register}\index{subject}{register}, or a memory location.
  2145. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2146. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2147. && \key{r8} \MID \key{r9} \MID \key{r10}
  2148. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2149. \MID \key{r14} \MID \key{r15}}
  2150. \newcommand{\GrammarXInt}{
  2151. \begin{array}{rcl}
  2152. \Reg &::=& \allregisters{} \\
  2153. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2154. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2155. \key{subq} \; \Arg\key{,} \Arg \MID
  2156. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2157. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2158. \key{callq} \; \mathit{label} \MID
  2159. \key{retq} \MID
  2160. \key{jmp}\,\itm{label} \MID \\
  2161. && \itm{label}\key{:}\; \Instr
  2162. \end{array}
  2163. }
  2164. \begin{figure}[tp]
  2165. \begin{tcolorbox}[colback=white]
  2166. {\if\edition\racketEd
  2167. \[
  2168. \begin{array}{l}
  2169. \GrammarXInt \\
  2170. \begin{array}{lcl}
  2171. \LangXIntM{} &::= & \key{.globl main}\\
  2172. & & \key{main:} \; \Instr\ldots
  2173. \end{array}
  2174. \end{array}
  2175. \]
  2176. \fi}
  2177. {\if\edition\pythonEd
  2178. \[
  2179. \begin{array}{lcl}
  2180. \Reg &::=& \allregisters{} \\
  2181. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2182. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2183. \key{subq} \; \Arg\key{,} \Arg \MID
  2184. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2185. && \key{callq} \; \mathit{label} \MID
  2186. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2187. \LangXIntM{} &::= & \key{.globl main}\\
  2188. & & \key{main:} \; \Instr^{*}
  2189. \end{array}
  2190. \]
  2191. \fi}
  2192. \end{tcolorbox}
  2193. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2194. \label{fig:x86-int-concrete}
  2195. \end{figure}
  2196. A register is a special kind of variable that holds a 64-bit
  2197. value. There are 16 general-purpose registers in the computer; their
  2198. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2199. written with a percent sign, \key{\%}, followed by the register name,
  2200. for example \key{\%rax}.
  2201. An immediate value is written using the notation \key{\$}$n$ where $n$
  2202. is an integer.
  2203. %
  2204. %
  2205. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2206. which obtains the address stored in register $r$ and then adds $n$
  2207. bytes to the address. The resulting address is used to load or to store
  2208. to memory depending on whether it occurs as a source or destination
  2209. argument of an instruction.
  2210. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2211. the source $s$ and destination $d$, applies the arithmetic operation,
  2212. and then writes the result to the destination $d$. \index{subject}{instruction}
  2213. %
  2214. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2215. stores the result in $d$.
  2216. %
  2217. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2218. specified by the label, and $\key{retq}$ returns from a procedure to
  2219. its caller.
  2220. %
  2221. We discuss procedure calls in more detail further in this chapter and
  2222. in chapter~\ref{ch:Lfun}.
  2223. %
  2224. The last letter \key{q} indicates that these instructions operate on
  2225. quadwords which are 64-bit values.
  2226. %
  2227. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2228. counter to the address of the instruction immediately after the
  2229. specified label.}
  2230. Appendix~\ref{sec:x86-quick-reference} contains a quick reference for
  2231. all the x86 instructions used in this book.
  2232. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2233. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2234. \lstinline{movq $10, %rax}
  2235. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2236. adds $32$ to the $10$ in \key{rax} and
  2237. puts the result, $42$, into \key{rax}.
  2238. %
  2239. The last instruction \key{retq} finishes the \key{main} function by
  2240. returning the integer in \key{rax} to the operating system. The
  2241. operating system interprets this integer as the program's exit
  2242. code. By convention, an exit code of 0 indicates that a program has
  2243. completed successfully, and all other exit codes indicate various
  2244. errors.
  2245. %
  2246. \racket{However, in this book we return the result of the program
  2247. as the exit code.}
  2248. \begin{figure}[tbp]
  2249. \begin{minipage}{0.45\textwidth}
  2250. \begin{tcolorbox}[colback=white]
  2251. \begin{lstlisting}
  2252. .globl main
  2253. main:
  2254. movq $10, %rax
  2255. addq $32, %rax
  2256. retq
  2257. \end{lstlisting}
  2258. \end{tcolorbox}
  2259. \end{minipage}
  2260. \caption{An x86 program that computes
  2261. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2262. \label{fig:p0-x86}
  2263. \end{figure}
  2264. We exhibit the use of memory for storing intermediate results in the
  2265. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2266. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2267. uses a region of memory called the \emph{procedure call stack}
  2268. (\emph{stack} for
  2269. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2270. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2271. for each procedure call. The memory layout for an individual frame is
  2272. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2273. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2274. address of the item at the top of the stack. In general, we use the
  2275. term \emph{pointer}\index{subject}{pointer} for something that
  2276. contains an address. The stack grows downward in memory, so we
  2277. increase the size of the stack by subtracting from the stack pointer.
  2278. In the context of a procedure call, the \emph{return
  2279. address}\index{subject}{return address} is the location of the
  2280. instruction that immediately follows the call instruction on the
  2281. caller side. The function call instruction, \code{callq}, pushes the
  2282. return address onto the stack prior to jumping to the procedure. The
  2283. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2284. pointer} and is used to access variables that are stored in the
  2285. frame of the current procedure call. The base pointer of the caller
  2286. is stored immediately after the return address.
  2287. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2288. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2289. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2290. $-16\key{(\%rbp)}$, and so on.
  2291. \begin{figure}[tbp]
  2292. \begin{minipage}{0.66\textwidth}
  2293. \begin{tcolorbox}[colback=white]
  2294. {\if\edition\racketEd
  2295. \begin{lstlisting}
  2296. start:
  2297. movq $10, -8(%rbp)
  2298. negq -8(%rbp)
  2299. movq -8(%rbp), %rax
  2300. addq $52, %rax
  2301. jmp conclusion
  2302. .globl main
  2303. main:
  2304. pushq %rbp
  2305. movq %rsp, %rbp
  2306. subq $16, %rsp
  2307. jmp start
  2308. conclusion:
  2309. addq $16, %rsp
  2310. popq %rbp
  2311. retq
  2312. \end{lstlisting}
  2313. \fi}
  2314. {\if\edition\pythonEd
  2315. \begin{lstlisting}
  2316. .globl main
  2317. main:
  2318. pushq %rbp
  2319. movq %rsp, %rbp
  2320. subq $16, %rsp
  2321. movq $10, -8(%rbp)
  2322. negq -8(%rbp)
  2323. movq -8(%rbp), %rax
  2324. addq $52, %rax
  2325. addq $16, %rsp
  2326. popq %rbp
  2327. retq
  2328. \end{lstlisting}
  2329. \fi}
  2330. \end{tcolorbox}
  2331. \end{minipage}
  2332. \caption{An x86 program that computes
  2333. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2334. \label{fig:p1-x86}
  2335. \end{figure}
  2336. \begin{figure}[tbp]
  2337. \begin{minipage}{0.66\textwidth}
  2338. \begin{tcolorbox}[colback=white]
  2339. \centering
  2340. \begin{tabular}{|r|l|} \hline
  2341. Position & Contents \\ \hline
  2342. $8$(\key{\%rbp}) & return address \\
  2343. $0$(\key{\%rbp}) & old \key{rbp} \\
  2344. $-8$(\key{\%rbp}) & variable $1$ \\
  2345. $-16$(\key{\%rbp}) & variable $2$ \\
  2346. \ldots & \ldots \\
  2347. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2348. \end{tabular}
  2349. \end{tcolorbox}
  2350. \end{minipage}
  2351. \caption{Memory layout of a frame.}
  2352. \label{fig:frame}
  2353. \end{figure}
  2354. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2355. is transferred from the operating system to the \code{main} function.
  2356. The operating system issues a \code{callq main} instruction that
  2357. pushes its return address on the stack and then jumps to
  2358. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2359. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2360. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2361. out of alignment (because the \code{callq} pushed the return address).
  2362. The first three instructions are the typical
  2363. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2364. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2365. pointer \code{rsp} and then saves the base pointer of the caller at
  2366. address \code{rsp} on the stack. The next instruction \code{movq
  2367. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2368. which is pointing to the location of the old base pointer. The
  2369. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2370. make enough room for storing variables. This program needs one
  2371. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2372. 16-byte-aligned, and then we are ready to make calls to other functions.
  2373. \racket{The last instruction of the prelude is \code{jmp start}, which
  2374. transfers control to the instructions that were generated from the
  2375. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2376. \racket{The first instruction under the \code{start} label is}
  2377. %
  2378. \python{The first instruction after the prelude is}
  2379. %
  2380. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2381. %
  2382. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2383. $1$ to $-10$.
  2384. %
  2385. The next instruction moves the $-10$ from variable $1$ into the
  2386. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2387. the value in \code{rax}, updating its contents to $42$.
  2388. \racket{The three instructions under the label \code{conclusion} are the
  2389. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2390. %
  2391. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2392. \code{main} function consists of the last three instructions.}
  2393. %
  2394. The first two restore the \code{rsp} and \code{rbp} registers to their
  2395. states at the beginning of the procedure. In particular,
  2396. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2397. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2398. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2399. \key{retq}, jumps back to the procedure that called this one and adds
  2400. $8$ to the stack pointer.
  2401. Our compiler needs a convenient representation for manipulating x86
  2402. programs, so we define an abstract syntax for x86, shown in
  2403. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2404. \LangXInt{}.
  2405. %
  2406. {\if\edition\pythonEd%
  2407. The main difference between this and the concrete syntax of \LangXInt{}
  2408. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2409. names, and register names are explicitly represented by strings.
  2410. \fi} %
  2411. {\if\edition\racketEd
  2412. The main difference between this and the concrete syntax of \LangXInt{}
  2413. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2414. front of every instruction. Instead instructions are grouped into
  2415. \emph{basic blocks}\index{subject}{basic block} with a
  2416. label associated with every basic block; this is why the \key{X86Program}
  2417. struct includes an alist mapping labels to basic blocks. The reason for this
  2418. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2419. introduce conditional branching. The \code{Block} structure includes
  2420. an $\itm{info}$ field that is not needed in this chapter but becomes
  2421. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2422. $\itm{info}$ field should contain an empty list.
  2423. \fi}
  2424. %
  2425. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2426. node includes an integer for representing the arity of the function,
  2427. that is, the number of arguments, which is helpful to know during
  2428. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2429. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2430. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2431. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2432. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2433. \MID \skey{r14} \MID \skey{r15}}
  2434. \newcommand{\ASTXIntRacket}{
  2435. \begin{array}{lcl}
  2436. \Reg &::=& \allregisters{} \\
  2437. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2438. \MID \DEREF{\Reg}{\Int} \\
  2439. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2440. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2441. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2442. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2443. &\MID& \PUSHQ{\Arg}
  2444. \MID \POPQ{\Arg} \\
  2445. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2446. \MID \RETQ{}
  2447. \MID \JMP{\itm{label}} \\
  2448. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2449. \end{array}
  2450. }
  2451. \begin{figure}[tp]
  2452. \begin{tcolorbox}[colback=white]
  2453. \small
  2454. {\if\edition\racketEd
  2455. \[\arraycolsep=3pt
  2456. \begin{array}{l}
  2457. \ASTXIntRacket \\
  2458. \begin{array}{lcl}
  2459. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2460. \end{array}
  2461. \end{array}
  2462. \]
  2463. \fi}
  2464. {\if\edition\pythonEd
  2465. \[
  2466. \begin{array}{lcl}
  2467. \Reg &::=& \allastregisters{} \\
  2468. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2469. \MID \DEREF{\Reg}{\Int} \\
  2470. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2471. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2472. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2473. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2474. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2475. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2476. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2477. \end{array}
  2478. \]
  2479. \fi}
  2480. \end{tcolorbox}
  2481. \caption{The abstract syntax of \LangXInt{} assembly.}
  2482. \label{fig:x86-int-ast}
  2483. \end{figure}
  2484. \section{Planning the Trip to x86}
  2485. \label{sec:plan-s0-x86}
  2486. To compile one language to another, it helps to focus on the
  2487. differences between the two languages because the compiler will need
  2488. to bridge those differences. What are the differences between \LangVar{}
  2489. and x86 assembly? Here are some of the most important ones:
  2490. \begin{enumerate}
  2491. \item x86 arithmetic instructions typically have two arguments and
  2492. update the second argument in place. In contrast, \LangVar{}
  2493. arithmetic operations take two arguments and produce a new value.
  2494. An x86 instruction may have at most one memory-accessing argument.
  2495. Furthermore, some x86 instructions place special restrictions on
  2496. their arguments.
  2497. \item An argument of an \LangVar{} operator can be a deeply nested
  2498. expression, whereas x86 instructions restrict their arguments to be
  2499. integer constants, registers, and memory locations.
  2500. {\if\edition\racketEd
  2501. \item The order of execution in x86 is explicit in the syntax, which
  2502. is a sequence of instructions and jumps to labeled positions,
  2503. whereas in \LangVar{} the order of evaluation is a left-to-right
  2504. depth-first traversal of the abstract syntax tree. \fi}
  2505. \item A program in \LangVar{} can have any number of variables,
  2506. whereas x86 has 16 registers and the procedure call stack.
  2507. {\if\edition\racketEd
  2508. \item Variables in \LangVar{} can shadow other variables with the
  2509. same name. In x86, registers have unique names, and memory locations
  2510. have unique addresses.
  2511. \fi}
  2512. \end{enumerate}
  2513. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2514. down the problem into several steps, which deal with these differences
  2515. one at a time. Each of these steps is called a \emph{pass} of the
  2516. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2517. %
  2518. This term indicates that each step passes over, or traverses, the AST
  2519. of the program.
  2520. %
  2521. Furthermore, we follow the nanopass approach, which means that we
  2522. strive for each pass to accomplish one clear objective rather than two
  2523. or three at the same time.
  2524. %
  2525. We begin by sketching how we might implement each pass and give each
  2526. pass a name. We then figure out an ordering of the passes and the
  2527. input/output language for each pass. The very first pass has
  2528. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2529. its output language. In between these two passes, we can choose
  2530. whichever language is most convenient for expressing the output of
  2531. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2532. \emph{intermediate languages} of our own design. Finally, to
  2533. implement each pass we write one recursive function per nonterminal in
  2534. the grammar of the input language of the pass.
  2535. \index{subject}{intermediate language}
  2536. Our compiler for \LangVar{} consists of the following passes:
  2537. %
  2538. \begin{description}
  2539. {\if\edition\racketEd
  2540. \item[\key{uniquify}] deals with the shadowing of variables by
  2541. renaming every variable to a unique name.
  2542. \fi}
  2543. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2544. of a primitive operation or function call is a variable or integer,
  2545. that is, an \emph{atomic} expression. We refer to nonatomic
  2546. expressions as \emph{complex}. This pass introduces temporary
  2547. variables to hold the results of complex
  2548. subexpressions.\index{subject}{atomic
  2549. expression}\index{subject}{complex expression}%
  2550. {\if\edition\racketEd
  2551. \item[\key{explicate\_control}] makes the execution order of the
  2552. program explicit. It converts the abstract syntax tree
  2553. representation into a graph in which each node is a labeled sequence
  2554. of statements and the edges are \code{goto} statements.
  2555. \fi}
  2556. \item[\key{select\_instructions}] handles the difference between
  2557. \LangVar{} operations and x86 instructions. This pass converts each
  2558. \LangVar{} operation to a short sequence of instructions that
  2559. accomplishes the same task.
  2560. \item[\key{assign\_homes}] replaces variables with registers or stack
  2561. locations.
  2562. \end{description}
  2563. %
  2564. {\if\edition\racketEd
  2565. %
  2566. Our treatment of \code{remove\_complex\_operands} and
  2567. \code{explicate\_control} as separate passes is an example of the
  2568. nanopass approach\footnote{For analogous decompositions of the
  2569. translation into continuation passing style, see the work of
  2570. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2571. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2572. %
  2573. \fi}
  2574. The next question is, in what order should we apply these passes? This
  2575. question can be challenging because it is difficult to know ahead of
  2576. time which orderings will be better (that is, will be easier to
  2577. implement, produce more efficient code, and so on), and therefore
  2578. ordering often involves trial and error. Nevertheless, we can plan
  2579. ahead and make educated choices regarding the ordering.
  2580. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2581. \key{uniquify}? The \key{uniquify} pass should come first because
  2582. \key{explicate\_control} changes all the \key{let}-bound variables to
  2583. become local variables whose scope is the entire program, which would
  2584. confuse variables with the same name.}
  2585. %
  2586. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2587. because the later removes the \key{let} form, but it is convenient to
  2588. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2589. %
  2590. \racket{The ordering of \key{uniquify} with respect to
  2591. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2592. \key{uniquify} to come first.}
  2593. The \key{select\_instructions} and \key{assign\_homes} passes are
  2594. intertwined.
  2595. %
  2596. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2597. passing arguments to functions and that it is preferable to assign
  2598. parameters to their corresponding registers. This suggests that it
  2599. would be better to start with the \key{select\_instructions} pass,
  2600. which generates the instructions for argument passing, before
  2601. performing register allocation.
  2602. %
  2603. On the other hand, by selecting instructions first we may run into a
  2604. dead end in \key{assign\_homes}. Recall that only one argument of an
  2605. x86 instruction may be a memory access, but \key{assign\_homes} might
  2606. be forced to assign both arguments to memory locations.
  2607. %
  2608. A sophisticated approach is to repeat the two passes until a solution
  2609. is found. However, to reduce implementation complexity we recommend
  2610. placing \key{select\_instructions} first, followed by the
  2611. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2612. that uses a reserved register to fix outstanding problems.
  2613. \begin{figure}[tbp]
  2614. \begin{tcolorbox}[colback=white]
  2615. {\if\edition\racketEd
  2616. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2617. \node (Lvar) at (0,2) {\large \LangVar{}};
  2618. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2619. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2620. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2621. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2622. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2623. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2624. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2625. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2626. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2627. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2628. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2629. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2630. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2631. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2632. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2633. \end{tikzpicture}
  2634. \fi}
  2635. {\if\edition\pythonEd
  2636. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2637. \node (Lvar) at (0,2) {\large \LangVar{}};
  2638. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2639. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2640. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2641. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2642. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2643. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2644. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  2645. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2646. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2647. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2648. \end{tikzpicture}
  2649. \fi}
  2650. \end{tcolorbox}
  2651. \caption{Diagram of the passes for compiling \LangVar{}. }
  2652. \label{fig:Lvar-passes}
  2653. \end{figure}
  2654. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2655. passes and identifies the input and output language of each pass.
  2656. %
  2657. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2658. language, which extends \LangXInt{} with an unbounded number of
  2659. program-scope variables and removes the restrictions regarding
  2660. instruction arguments.
  2661. %
  2662. The last pass, \key{prelude\_and\_conclusion}, places the program
  2663. instructions inside a \code{main} function with instructions for the
  2664. prelude and conclusion.
  2665. %
  2666. \racket{In the next section we discuss the \LangCVar{} intermediate
  2667. language that serves as the output of \code{explicate\_control}.}
  2668. %
  2669. The remainder of this chapter provides guidance on the implementation
  2670. of each of the compiler passes represented in
  2671. figure~\ref{fig:Lvar-passes}.
  2672. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2673. %% are programs that are still in the \LangVar{} language, though the
  2674. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2675. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2676. %% %
  2677. %% The output of \code{explicate\_control} is in an intermediate language
  2678. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2679. %% syntax, which we introduce in the next section. The
  2680. %% \key{select-instruction} pass translates from \LangCVar{} to
  2681. %% \LangXVar{}. The \key{assign-homes} and
  2682. %% \key{patch-instructions}
  2683. %% passes input and output variants of x86 assembly.
  2684. \newcommand{\CvarGrammarRacket}{
  2685. \begin{array}{lcl}
  2686. \Atm &::=& \Int \MID \Var \\
  2687. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2688. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2689. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2690. \end{array}
  2691. }
  2692. \newcommand{\CvarASTRacket}{
  2693. \begin{array}{lcl}
  2694. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2695. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2696. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2697. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2698. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2699. \end{array}
  2700. }
  2701. {\if\edition\racketEd
  2702. \subsection{The \LangCVar{} Intermediate Language}
  2703. The output of \code{explicate\_control} is similar to the C
  2704. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2705. categories for expressions and statements, so we name it \LangCVar{}.
  2706. This style of intermediate language is also known as
  2707. \emph{three-address code}, to emphasize that the typical form of a
  2708. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2709. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2710. The concrete syntax for \LangCVar{} is shown in
  2711. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2712. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2713. %
  2714. The \LangCVar{} language supports the same operators as \LangVar{} but
  2715. the arguments of operators are restricted to atomic
  2716. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2717. assignment statements that can be executed in sequence using the
  2718. \key{Seq} form. A sequence of statements always ends with
  2719. \key{Return}, a guarantee that is baked into the grammar rules for
  2720. \itm{tail}. The naming of this nonterminal comes from the term
  2721. \emph{tail position}\index{subject}{tail position}, which refers to an
  2722. expression that is the last one to execute within a function or
  2723. program.
  2724. A \LangCVar{} program consists of an alist mapping labels to
  2725. tails. This is more general than necessary for the present chapter, as
  2726. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2727. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2728. there is just one label, \key{start}, and the whole program is
  2729. its tail.
  2730. %
  2731. The $\itm{info}$ field of the \key{CProgram} form, after the
  2732. \code{explicate\_control} pass, contains an alist that associates the
  2733. symbol \key{locals} with a list of all the variables used in the
  2734. program. At the start of the program, these variables are
  2735. uninitialized; they become initialized on their first assignment.
  2736. \begin{figure}[tbp]
  2737. \begin{tcolorbox}[colback=white]
  2738. \[
  2739. \begin{array}{l}
  2740. \CvarGrammarRacket \\
  2741. \begin{array}{lcl}
  2742. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2743. \end{array}
  2744. \end{array}
  2745. \]
  2746. \end{tcolorbox}
  2747. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2748. \label{fig:c0-concrete-syntax}
  2749. \end{figure}
  2750. \begin{figure}[tbp]
  2751. \begin{tcolorbox}[colback=white]
  2752. \[
  2753. \begin{array}{l}
  2754. \CvarASTRacket \\
  2755. \begin{array}{lcl}
  2756. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2757. \end{array}
  2758. \end{array}
  2759. \]
  2760. \end{tcolorbox}
  2761. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2762. \label{fig:c0-syntax}
  2763. \end{figure}
  2764. The definitional interpreter for \LangCVar{} is in the support code,
  2765. in the file \code{interp-Cvar.rkt}.
  2766. \fi}
  2767. {\if\edition\racketEd
  2768. \section{Uniquify Variables}
  2769. \label{sec:uniquify-Lvar}
  2770. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2771. programs in which every \key{let} binds a unique variable name. For
  2772. example, the \code{uniquify} pass should translate the program on the
  2773. left into the program on the right.
  2774. \begin{transformation}
  2775. \begin{lstlisting}
  2776. (let ([x 32])
  2777. (+ (let ([x 10]) x) x))
  2778. \end{lstlisting}
  2779. \compilesto
  2780. \begin{lstlisting}
  2781. (let ([x.1 32])
  2782. (+ (let ([x.2 10]) x.2) x.1))
  2783. \end{lstlisting}
  2784. \end{transformation}
  2785. The following is another example translation, this time of a program
  2786. with a \key{let} nested inside the initializing expression of another
  2787. \key{let}.
  2788. \begin{transformation}
  2789. \begin{lstlisting}
  2790. (let ([x (let ([x 4])
  2791. (+ x 1))])
  2792. (+ x 2))
  2793. \end{lstlisting}
  2794. \compilesto
  2795. \begin{lstlisting}
  2796. (let ([x.2 (let ([x.1 4])
  2797. (+ x.1 1))])
  2798. (+ x.2 2))
  2799. \end{lstlisting}
  2800. \end{transformation}
  2801. We recommend implementing \code{uniquify} by creating a structurally
  2802. recursive function named \code{uniquify\_exp} that does little other
  2803. than copy an expression. However, when encountering a \key{let}, it
  2804. should generate a unique name for the variable and associate the old
  2805. name with the new name in an alist.\footnote{The Racket function
  2806. \code{gensym} is handy for generating unique variable names.} The
  2807. \code{uniquify\_exp} function needs to access this alist when it gets
  2808. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2809. for the alist.
  2810. The skeleton of the \code{uniquify\_exp} function is shown in
  2811. figure~\ref{fig:uniquify-Lvar}.
  2812. %% The function is curried so that it is
  2813. %% convenient to partially apply it to an alist and then apply it to
  2814. %% different expressions, as in the last case for primitive operations in
  2815. %% figure~\ref{fig:uniquify-Lvar}.
  2816. The
  2817. %
  2818. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2819. %
  2820. form of Racket is useful for transforming the element of a list to
  2821. produce a new list.\index{subject}{for/list}
  2822. \begin{figure}[tbp]
  2823. \begin{tcolorbox}[colback=white]
  2824. \begin{lstlisting}
  2825. (define (uniquify_exp env)
  2826. (lambda (e)
  2827. (match e
  2828. [(Var x) ___]
  2829. [(Int n) (Int n)]
  2830. [(Let x e body) ___]
  2831. [(Prim op es)
  2832. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2833. (define (uniquify p)
  2834. (match p
  2835. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2836. \end{lstlisting}
  2837. \end{tcolorbox}
  2838. \caption{Skeleton for the \key{uniquify} pass.}
  2839. \label{fig:uniquify-Lvar}
  2840. \end{figure}
  2841. \begin{exercise}
  2842. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2843. Complete the \code{uniquify} pass by filling in the blanks in
  2844. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2845. variables and for the \key{let} form in the file \code{compiler.rkt}
  2846. in the support code.
  2847. \end{exercise}
  2848. \begin{exercise}
  2849. \normalfont\normalsize
  2850. \label{ex:Lvar}
  2851. Create five \LangVar{} programs that exercise the most interesting
  2852. parts of the \key{uniquify} pass; that is, the programs should include
  2853. \key{let} forms, variables, and variables that shadow each other.
  2854. The five programs should be placed in the subdirectory named
  2855. \key{tests}, and the file names should start with \code{var\_test\_}
  2856. followed by a unique integer and end with the file extension
  2857. \key{.rkt}.
  2858. %
  2859. The \key{run-tests.rkt} script in the support code checks whether the
  2860. output programs produce the same result as the input programs. The
  2861. script uses the \key{interp-tests} function
  2862. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2863. your \key{uniquify} pass on the example programs. The \code{passes}
  2864. parameter of \key{interp-tests} is a list that should have one entry
  2865. for each pass in your compiler. For now, define \code{passes} to
  2866. contain just one entry for \code{uniquify} as follows:
  2867. \begin{lstlisting}
  2868. (define passes
  2869. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2870. \end{lstlisting}
  2871. Run the \key{run-tests.rkt} script in the support code to check
  2872. whether the output programs produce the same result as the input
  2873. programs.
  2874. \end{exercise}
  2875. \fi}
  2876. \section{Remove Complex Operands}
  2877. \label{sec:remove-complex-opera-Lvar}
  2878. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2879. into a restricted form in which the arguments of operations are atomic
  2880. expressions. Put another way, this pass removes complex
  2881. operands\index{subject}{complex operand}, such as the expression
  2882. \racket{\code{(- 10)}}\python{\code{-10}}
  2883. in the following program. This is accomplished by introducing a new
  2884. temporary variable, assigning the complex operand to the new
  2885. variable, and then using the new variable in place of the complex
  2886. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2887. right.
  2888. {\if\edition\racketEd
  2889. \begin{transformation}
  2890. % var_test_19.rkt
  2891. \begin{lstlisting}
  2892. (let ([x (+ 42 (- 10))])
  2893. (+ x 10))
  2894. \end{lstlisting}
  2895. \compilesto
  2896. \begin{lstlisting}
  2897. (let ([x (let ([tmp.1 (- 10)])
  2898. (+ 42 tmp.1))])
  2899. (+ x 10))
  2900. \end{lstlisting}
  2901. \end{transformation}
  2902. \fi}
  2903. {\if\edition\pythonEd
  2904. \begin{transformation}
  2905. \begin{lstlisting}
  2906. x = 42 + -10
  2907. print(x + 10)
  2908. \end{lstlisting}
  2909. \compilesto
  2910. \begin{lstlisting}
  2911. tmp_0 = -10
  2912. x = 42 + tmp_0
  2913. tmp_1 = x + 10
  2914. print(tmp_1)
  2915. \end{lstlisting}
  2916. \end{transformation}
  2917. \fi}
  2918. \newcommand{\LvarMonadASTRacket}{
  2919. \begin{array}{rcl}
  2920. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2921. \Exp &::=& \Atm \MID \READ{} \\
  2922. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2923. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2924. \end{array}
  2925. }
  2926. \newcommand{\LvarMonadASTPython}{
  2927. \begin{array}{rcl}
  2928. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2929. \Exp{} &::=& \Atm \MID \READ{} \\
  2930. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2931. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2932. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2933. \end{array}
  2934. }
  2935. \begin{figure}[tp]
  2936. \centering
  2937. \begin{tcolorbox}[colback=white]
  2938. {\if\edition\racketEd
  2939. \[
  2940. \begin{array}{l}
  2941. \LvarMonadASTRacket \\
  2942. \begin{array}{rcl}
  2943. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2944. \end{array}
  2945. \end{array}
  2946. \]
  2947. \fi}
  2948. {\if\edition\pythonEd
  2949. \[
  2950. \begin{array}{l}
  2951. \LvarMonadASTPython \\
  2952. \begin{array}{rcl}
  2953. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2954. \end{array}
  2955. \end{array}
  2956. \]
  2957. \fi}
  2958. \end{tcolorbox}
  2959. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2960. atomic expressions.}
  2961. \label{fig:Lvar-anf-syntax}
  2962. \end{figure}
  2963. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2964. of this pass, the language \LangVarANF{}. The only difference is that
  2965. operator arguments are restricted to be atomic expressions that are
  2966. defined by the \Atm{} nonterminal. In particular, integer constants
  2967. and variables are atomic.
  2968. The atomic expressions are pure (they do not cause or depend on side
  2969. effects) whereas complex expressions may have side effects, such as
  2970. \READ{}. A language with this separation between pure expression
  2971. versus expressions with side effects is said to be in monadic normal
  2972. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  2973. in the name \LangVarANF{}. An important invariant of the
  2974. \code{remove\_complex\_operands} pass is that the relative ordering
  2975. among complex expressions is not changed, but the relative ordering
  2976. between atomic expressions and complex expressions can change and
  2977. often does. The reason that these changes are behavior preserving is
  2978. that the atomic expressions are pure.
  2979. Another well-known form for intermediate languages is the
  2980. \emph{administrative normal form}
  2981. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2982. \index{subject}{administrative normal form} \index{subject}{ANF}
  2983. %
  2984. The \LangVarANF{} language is not quite in ANF because we allow the
  2985. right-hand side of a \code{let} to be a complex expression.
  2986. {\if\edition\racketEd
  2987. We recommend implementing this pass with two mutually recursive
  2988. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2989. \code{rco\_atom} to subexpressions that need to become atomic and to
  2990. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2991. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2992. returns an expression. The \code{rco\_atom} function returns two
  2993. things: an atomic expression and an alist mapping temporary variables to
  2994. complex subexpressions. You can return multiple things from a function
  2995. using Racket's \key{values} form, and you can receive multiple things
  2996. from a function call using the \key{define-values} form.
  2997. \fi}
  2998. %
  2999. {\if\edition\pythonEd
  3000. %
  3001. We recommend implementing this pass with an auxiliary method named
  3002. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3003. Boolean that specifies whether the expression needs to become atomic
  3004. or not. The \code{rco\_exp} method should return a pair consisting of
  3005. the new expression and a list of pairs, associating new temporary
  3006. variables with their initializing expressions.
  3007. %
  3008. \fi}
  3009. {\if\edition\racketEd
  3010. %
  3011. Returning to the example program with the expression \code{(+ 42 (-
  3012. 10))}, the subexpression \code{(- 10)} should be processed using the
  3013. \code{rco\_atom} function because it is an argument of the \code{+}
  3014. operator and therefore needs to become atomic. The output of
  3015. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3016. \begin{transformation}
  3017. \begin{lstlisting}
  3018. (- 10)
  3019. \end{lstlisting}
  3020. \compilesto
  3021. \begin{lstlisting}
  3022. tmp.1
  3023. ((tmp.1 . (- 10)))
  3024. \end{lstlisting}
  3025. \end{transformation}
  3026. \fi}
  3027. %
  3028. {\if\edition\pythonEd
  3029. %
  3030. Returning to the example program with the expression \code{42 + -10},
  3031. the subexpression \code{-10} should be processed using the
  3032. \code{rco\_exp} function with \code{True} as the second argument
  3033. because \code{-10} is an argument of the \code{+} operator and
  3034. therefore needs to become atomic. The output of \code{rco\_exp}
  3035. applied to \code{-10} is as follows.
  3036. \begin{transformation}
  3037. \begin{lstlisting}
  3038. -10
  3039. \end{lstlisting}
  3040. \compilesto
  3041. \begin{lstlisting}
  3042. tmp_1
  3043. [(tmp_1, -10)]
  3044. \end{lstlisting}
  3045. \end{transformation}
  3046. %
  3047. \fi}
  3048. Take special care of programs, such as the following, that
  3049. %
  3050. \racket{bind a variable to an atomic expression.}
  3051. %
  3052. \python{assign an atomic expression to a variable.}
  3053. %
  3054. You should leave such \racket{variable bindings}\python{assignments}
  3055. unchanged, as shown in the program on the right\\
  3056. %
  3057. {\if\edition\racketEd
  3058. \begin{transformation}
  3059. % var_test_20.rkt
  3060. \begin{lstlisting}
  3061. (let ([a 42])
  3062. (let ([b a])
  3063. b))
  3064. \end{lstlisting}
  3065. \compilesto
  3066. \begin{lstlisting}
  3067. (let ([a 42])
  3068. (let ([b a])
  3069. b))
  3070. \end{lstlisting}
  3071. \end{transformation}
  3072. \fi}
  3073. {\if\edition\pythonEd
  3074. \begin{transformation}
  3075. \begin{lstlisting}
  3076. a = 42
  3077. b = a
  3078. print(b)
  3079. \end{lstlisting}
  3080. \compilesto
  3081. \begin{lstlisting}
  3082. a = 42
  3083. b = a
  3084. print(b)
  3085. \end{lstlisting}
  3086. \end{transformation}
  3087. \fi}
  3088. %
  3089. \noindent A careless implementation might produce the following output with
  3090. unnecessary temporary variables.
  3091. \begin{center}
  3092. \begin{minipage}{0.4\textwidth}
  3093. {\if\edition\racketEd
  3094. \begin{lstlisting}
  3095. (let ([tmp.1 42])
  3096. (let ([a tmp.1])
  3097. (let ([tmp.2 a])
  3098. (let ([b tmp.2])
  3099. b))))
  3100. \end{lstlisting}
  3101. \fi}
  3102. {\if\edition\pythonEd
  3103. \begin{lstlisting}
  3104. tmp_1 = 42
  3105. a = tmp_1
  3106. tmp_2 = a
  3107. b = tmp_2
  3108. print(b)
  3109. \end{lstlisting}
  3110. \fi}
  3111. \end{minipage}
  3112. \end{center}
  3113. \begin{exercise}
  3114. \normalfont\normalsize
  3115. {\if\edition\racketEd
  3116. Implement the \code{remove\_complex\_operands} function in
  3117. \code{compiler.rkt}.
  3118. %
  3119. Create three new \LangVar{} programs that exercise the interesting
  3120. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3121. regarding file names described in exercise~\ref{ex:Lvar}.
  3122. %
  3123. In the \code{run-tests.rkt} script, add the following entry to the
  3124. list of \code{passes}, and then run the script to test your compiler.
  3125. \begin{lstlisting}
  3126. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3127. \end{lstlisting}
  3128. In debugging your compiler, it is often useful to see the intermediate
  3129. programs that are output from each pass. To print the intermediate
  3130. programs, place \lstinline{(debug-level 1)} before the call to
  3131. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3132. %
  3133. {\if\edition\pythonEd
  3134. Implement the \code{remove\_complex\_operands} pass in
  3135. \code{compiler.py}, creating auxiliary functions for each
  3136. nonterminal in the grammar, i.e., \code{rco\_exp}
  3137. and \code{rco\_stmt}. We recommend you use the function
  3138. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3139. \fi}
  3140. \end{exercise}
  3141. {\if\edition\pythonEd
  3142. \begin{exercise}
  3143. \normalfont\normalsize
  3144. \label{ex:Lvar}
  3145. Create five \LangVar{} programs that exercise the most interesting
  3146. parts of the \code{remove\_complex\_operands} pass. The five programs
  3147. should be placed in the subdirectory named \key{tests}, and the file
  3148. names should start with \code{var\_test\_} followed by a unique
  3149. integer and end with the file extension \key{.py}.
  3150. %% The \key{run-tests.rkt} script in the support code checks whether the
  3151. %% output programs produce the same result as the input programs. The
  3152. %% script uses the \key{interp-tests} function
  3153. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3154. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3155. %% parameter of \key{interp-tests} is a list that should have one entry
  3156. %% for each pass in your compiler. For now, define \code{passes} to
  3157. %% contain just one entry for \code{uniquify} as shown below.
  3158. %% \begin{lstlisting}
  3159. %% (define passes
  3160. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3161. %% \end{lstlisting}
  3162. Run the \key{run-tests.py} script in the support code to check
  3163. whether the output programs produce the same result as the input
  3164. programs.
  3165. \end{exercise}
  3166. \fi}
  3167. {\if\edition\racketEd
  3168. \section{Explicate Control}
  3169. \label{sec:explicate-control-Lvar}
  3170. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3171. programs that make the order of execution explicit in their
  3172. syntax. For now this amounts to flattening \key{let} constructs into a
  3173. sequence of assignment statements. For example, consider the following
  3174. \LangVar{} program:\\
  3175. % var_test_11.rkt
  3176. \begin{minipage}{0.96\textwidth}
  3177. \begin{lstlisting}
  3178. (let ([y (let ([x 20])
  3179. (+ x (let ([x 22]) x)))])
  3180. y)
  3181. \end{lstlisting}
  3182. \end{minipage}\\
  3183. %
  3184. The output of the previous pass is shown next, on the left, and the
  3185. output of \code{explicate\_control} is on the right. Recall that the
  3186. right-hand side of a \key{let} executes before its body, so that the order
  3187. of evaluation for this program is to assign \code{20} to \code{x.1},
  3188. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3189. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3190. this ordering explicit.
  3191. \begin{transformation}
  3192. \begin{lstlisting}
  3193. (let ([y (let ([x.1 20])
  3194. (let ([x.2 22])
  3195. (+ x.1 x.2)))])
  3196. y)
  3197. \end{lstlisting}
  3198. \compilesto
  3199. \begin{lstlisting}[language=C]
  3200. start:
  3201. x.1 = 20;
  3202. x.2 = 22;
  3203. y = (+ x.1 x.2);
  3204. return y;
  3205. \end{lstlisting}
  3206. \end{transformation}
  3207. \begin{figure}[tbp]
  3208. \begin{tcolorbox}[colback=white]
  3209. \begin{lstlisting}
  3210. (define (explicate_tail e)
  3211. (match e
  3212. [(Var x) ___]
  3213. [(Int n) (Return (Int n))]
  3214. [(Let x rhs body) ___]
  3215. [(Prim op es) ___]
  3216. [else (error "explicate_tail unhandled case" e)]))
  3217. (define (explicate_assign e x cont)
  3218. (match e
  3219. [(Var x) ___]
  3220. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3221. [(Let y rhs body) ___]
  3222. [(Prim op es) ___]
  3223. [else (error "explicate_assign unhandled case" e)]))
  3224. (define (explicate_control p)
  3225. (match p
  3226. [(Program info body) ___]))
  3227. \end{lstlisting}
  3228. \end{tcolorbox}
  3229. \caption{Skeleton for the \code{explicate\_control} pass.}
  3230. \label{fig:explicate-control-Lvar}
  3231. \end{figure}
  3232. The organization of this pass depends on the notion of tail position
  3233. to which we have alluded. Here is the definition.
  3234. \begin{definition}\normalfont
  3235. The following rules define when an expression is in \emph{tail
  3236. position}\index{subject}{tail position} for the language \LangVar{}.
  3237. \begin{enumerate}
  3238. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3239. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3240. \end{enumerate}
  3241. \end{definition}
  3242. We recommend implementing \code{explicate\_control} using two
  3243. recursive functions, \code{explicate\_tail} and
  3244. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3245. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3246. function should be applied to expressions in tail position, whereas the
  3247. \code{explicate\_assign} should be applied to expressions that occur on
  3248. the right-hand side of a \key{let}.
  3249. %
  3250. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3251. input and produces a \Tail{} in \LangCVar{} (see
  3252. figure~\ref{fig:c0-syntax}).
  3253. %
  3254. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3255. the variable to which it is to be assigned to, and a \Tail{} in
  3256. \LangCVar{} for the code that comes after the assignment. The
  3257. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3258. The \code{explicate\_assign} function is in accumulator-passing style:
  3259. the \code{cont} parameter is used for accumulating the output. This
  3260. accumulator-passing style plays an important role in the way that we
  3261. generate high-quality code for conditional expressions in
  3262. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3263. continuation because it contains the generated code that should come
  3264. after the current assignment. This code organization is also related
  3265. to continuation-passing style, except that \code{cont} is not what
  3266. happens next during compilation but is what happens next in the
  3267. generated code.
  3268. \begin{exercise}\normalfont\normalsize
  3269. %
  3270. Implement the \code{explicate\_control} function in
  3271. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3272. exercise the code in \code{explicate\_control}.
  3273. %
  3274. In the \code{run-tests.rkt} script, add the following entry to the
  3275. list of \code{passes} and then run the script to test your compiler.
  3276. \begin{lstlisting}
  3277. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3278. \end{lstlisting}
  3279. \end{exercise}
  3280. \fi}
  3281. \section{Select Instructions}
  3282. \label{sec:select-Lvar}
  3283. \index{subject}{instruction selection}
  3284. In the \code{select\_instructions} pass we begin the work of
  3285. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3286. language of this pass is a variant of x86 that still uses variables,
  3287. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3288. nonterminal of the \LangXInt{} abstract syntax
  3289. (figure~\ref{fig:x86-int-ast}).
  3290. \racket{We recommend implementing the
  3291. \code{select\_instructions} with three auxiliary functions, one for
  3292. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3293. $\Tail$.}
  3294. \python{We recommend implementing an auxiliary function
  3295. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3296. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3297. same and integer constants change to immediates; that is, $\INT{n}$
  3298. changes to $\IMM{n}$.}
  3299. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3300. arithmetic operations. For example, consider the following addition
  3301. operation, on the left side. There is an \key{addq} instruction in
  3302. x86, but it performs an in-place update. So, we could move $\Arg_1$
  3303. into the left-hand \itm{var} and then add $\Arg_2$ to \itm{var},
  3304. where $\Arg_1$ and $\Arg_2$ are the translations of $\Atm_1$ and
  3305. $\Atm_2$, respectively.
  3306. \begin{transformation}
  3307. {\if\edition\racketEd
  3308. \begin{lstlisting}
  3309. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3310. \end{lstlisting}
  3311. \fi}
  3312. {\if\edition\pythonEd
  3313. \begin{lstlisting}
  3314. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3315. \end{lstlisting}
  3316. \fi}
  3317. \compilesto
  3318. \begin{lstlisting}
  3319. movq |$\Arg_1$|, |$\itm{var}$|
  3320. addq |$\Arg_2$|, |$\itm{var}$|
  3321. \end{lstlisting}
  3322. \end{transformation}
  3323. There are also cases that require special care to avoid generating
  3324. needlessly complicated code. For example, if one of the arguments of
  3325. the addition is the same variable as the left-hand side of the
  3326. assignment, as shown next, then there is no need for the extra move
  3327. instruction. The assignment statement can be translated into a single
  3328. \key{addq} instruction, as follows.
  3329. \begin{transformation}
  3330. {\if\edition\racketEd
  3331. \begin{lstlisting}
  3332. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3333. \end{lstlisting}
  3334. \fi}
  3335. {\if\edition\pythonEd
  3336. \begin{lstlisting}
  3337. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3338. \end{lstlisting}
  3339. \fi}
  3340. \compilesto
  3341. \begin{lstlisting}
  3342. addq |$\Arg_1$|, |$\itm{var}$|
  3343. \end{lstlisting}
  3344. \end{transformation}
  3345. The \READOP{} operation does not have a direct counterpart in x86
  3346. assembly, so we provide this functionality with the function
  3347. \code{read\_int} in the file \code{runtime.c}, written in
  3348. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3349. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3350. system}, or simply the \emph{runtime} for short. When compiling your
  3351. generated x86 assembly code, you need to compile \code{runtime.c} to
  3352. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3353. \code{-c}) and link it into the executable. For our purposes of code
  3354. generation, all you need to do is translate an assignment of
  3355. \READOP{} into a call to the \code{read\_int} function followed by a
  3356. move from \code{rax} to the left-hand side variable. (Recall that the
  3357. return value of a function goes into \code{rax}.)
  3358. \begin{transformation}
  3359. {\if\edition\racketEd
  3360. \begin{lstlisting}
  3361. |$\itm{var}$| = (read);
  3362. \end{lstlisting}
  3363. \fi}
  3364. {\if\edition\pythonEd
  3365. \begin{lstlisting}
  3366. |$\itm{var}$| = input_int();
  3367. \end{lstlisting}
  3368. \fi}
  3369. \compilesto
  3370. \begin{lstlisting}
  3371. callq read_int
  3372. movq %rax, |$\itm{var}$|
  3373. \end{lstlisting}
  3374. \end{transformation}
  3375. {\if\edition\pythonEd
  3376. %
  3377. Similarly, we translate the \code{print} operation, shown below, into
  3378. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3379. In x86, the first six arguments to functions are passed in registers,
  3380. with the first argument passed in register \code{rdi}. So we move the
  3381. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3382. \code{callq} instruction.
  3383. \begin{transformation}
  3384. \begin{lstlisting}
  3385. print(|$\Atm$|)
  3386. \end{lstlisting}
  3387. \compilesto
  3388. \begin{lstlisting}
  3389. movq |$\Arg$|, %rdi
  3390. callq print_int
  3391. \end{lstlisting}
  3392. \end{transformation}
  3393. %
  3394. \fi}
  3395. {\if\edition\racketEd
  3396. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3397. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3398. assignment to the \key{rax} register followed by a jump to the
  3399. conclusion of the program (so the conclusion needs to be labeled).
  3400. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3401. recursively and then append the resulting instructions.
  3402. \fi}
  3403. {\if\edition\pythonEd
  3404. We recommend that you use the function \code{utils.label\_name()} to
  3405. transform a string into an label argument suitably suitable for, e.g.,
  3406. the target of the \code{callq} instruction. This practice makes your
  3407. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3408. all labels.
  3409. \fi}
  3410. \begin{exercise}
  3411. \normalfont\normalsize
  3412. {\if\edition\racketEd
  3413. Implement the \code{select\_instructions} pass in
  3414. \code{compiler.rkt}. Create three new example programs that are
  3415. designed to exercise all the interesting cases in this pass.
  3416. %
  3417. In the \code{run-tests.rkt} script, add the following entry to the
  3418. list of \code{passes} and then run the script to test your compiler.
  3419. \begin{lstlisting}
  3420. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3421. \end{lstlisting}
  3422. \fi}
  3423. {\if\edition\pythonEd
  3424. Implement the \key{select\_instructions} pass in
  3425. \code{compiler.py}. Create three new example programs that are
  3426. designed to exercise all the interesting cases in this pass.
  3427. Run the \code{run-tests.py} script to to check
  3428. whether the output programs produce the same result as the input
  3429. programs.
  3430. \fi}
  3431. \end{exercise}
  3432. \section{Assign Homes}
  3433. \label{sec:assign-Lvar}
  3434. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3435. \LangXVar{} programs that no longer use program variables. Thus, the
  3436. \code{assign\_homes} pass is responsible for placing all the program
  3437. variables in registers or on the stack. For runtime efficiency, it is
  3438. better to place variables in registers, but because there are only
  3439. sixteen registers, some programs must necessarily resort to placing
  3440. some variables on the stack. In this chapter we focus on the mechanics
  3441. of placing variables on the stack. We study an algorithm for placing
  3442. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3443. Consider again the following \LangVar{} program from
  3444. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3445. % var_test_20.rkt
  3446. \begin{minipage}{0.96\textwidth}
  3447. {\if\edition\racketEd
  3448. \begin{lstlisting}
  3449. (let ([a 42])
  3450. (let ([b a])
  3451. b))
  3452. \end{lstlisting}
  3453. \fi}
  3454. {\if\edition\pythonEd
  3455. \begin{lstlisting}
  3456. a = 42
  3457. b = a
  3458. print(b)
  3459. \end{lstlisting}
  3460. \fi}
  3461. \end{minipage}\\
  3462. %
  3463. The output of \code{select\_instructions} is shown next, on the left,
  3464. and the output of \code{assign\_homes} is on the right. In this
  3465. example, we assign variable \code{a} to stack location
  3466. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3467. \begin{transformation}
  3468. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3469. movq $42, a
  3470. movq a, b
  3471. movq b, %rax
  3472. \end{lstlisting}
  3473. \compilesto
  3474. %stack-space: 16
  3475. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3476. movq $42, -8(%rbp)
  3477. movq -8(%rbp), -16(%rbp)
  3478. movq -16(%rbp), %rax
  3479. \end{lstlisting}
  3480. \end{transformation}
  3481. \racket{
  3482. The \code{assign\_homes} pass should replace all variables
  3483. with stack locations.
  3484. The list of variables can be obtained from
  3485. the \code{locals-types} entry in the $\itm{info}$ of the
  3486. \code{X86Program} node. The \code{locals-types} entry is an alist
  3487. mapping all the variables in the program to their types
  3488. (for now, just \code{Integer}).
  3489. As an aside, the \code{locals-types} entry is
  3490. computed by \code{type-check-Cvar} in the support code, which
  3491. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3492. which you should propagate to the \code{X86Program} node.}
  3493. %
  3494. \python{The \code{assign\_homes} pass should replace all uses of
  3495. variables with stack locations.}
  3496. %
  3497. In the process of assigning variables to stack locations, it is
  3498. convenient for you to compute and store the size of the frame (in
  3499. bytes) in
  3500. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3501. %
  3502. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3503. %
  3504. which is needed later to generate the conclusion of the \code{main}
  3505. procedure. The x86-64 standard requires the frame size to be a
  3506. multiple of 16 bytes.\index{subject}{frame}
  3507. % TODO: store the number of variables instead? -Jeremy
  3508. \begin{exercise}\normalfont\normalsize
  3509. Implement the \code{assign\_homes} pass in
  3510. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3511. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3512. grammar. We recommend that the auxiliary functions take an extra
  3513. parameter that maps variable names to homes (stack locations for now).
  3514. %
  3515. {\if\edition\racketEd
  3516. In the \code{run-tests.rkt} script, add the following entry to the
  3517. list of \code{passes} and then run the script to test your compiler.
  3518. \begin{lstlisting}
  3519. (list "assign homes" assign-homes interp_x86-0)
  3520. \end{lstlisting}
  3521. \fi}
  3522. {\if\edition\pythonEd
  3523. Run the \code{run-tests.py} script to to check
  3524. whether the output programs produce the same result as the input
  3525. programs.
  3526. \fi}
  3527. \end{exercise}
  3528. \section{Patch Instructions}
  3529. \label{sec:patch-s0}
  3530. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3531. \LangXInt{} by making sure that each instruction adheres to the
  3532. restriction that at most one argument of an instruction may be a
  3533. memory reference.
  3534. We return to the following example.\\
  3535. \begin{minipage}{0.5\textwidth}
  3536. % var_test_20.rkt
  3537. {\if\edition\racketEd
  3538. \begin{lstlisting}
  3539. (let ([a 42])
  3540. (let ([b a])
  3541. b))
  3542. \end{lstlisting}
  3543. \fi}
  3544. {\if\edition\pythonEd
  3545. \begin{lstlisting}
  3546. a = 42
  3547. b = a
  3548. print(b)
  3549. \end{lstlisting}
  3550. \fi}
  3551. \end{minipage}\\
  3552. The \code{assign\_homes} pass produces the following translation. \\
  3553. \begin{minipage}{0.5\textwidth}
  3554. {\if\edition\racketEd
  3555. \begin{lstlisting}
  3556. movq $42, -8(%rbp)
  3557. movq -8(%rbp), -16(%rbp)
  3558. movq -16(%rbp), %rax
  3559. \end{lstlisting}
  3560. \fi}
  3561. {\if\edition\pythonEd
  3562. \begin{lstlisting}
  3563. movq 42, -8(%rbp)
  3564. movq -8(%rbp), -16(%rbp)
  3565. movq -16(%rbp), %rdi
  3566. callq print_int
  3567. \end{lstlisting}
  3568. \fi}
  3569. \end{minipage}\\
  3570. The second \key{movq} instruction is problematic because both
  3571. arguments are stack locations. We suggest fixing this problem by
  3572. moving from the source location to the register \key{rax} and then
  3573. from \key{rax} to the destination location, as follows.
  3574. \begin{lstlisting}
  3575. movq -8(%rbp), %rax
  3576. movq %rax, -16(%rbp)
  3577. \end{lstlisting}
  3578. \begin{exercise}
  3579. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3580. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3581. Create three new example programs that are
  3582. designed to exercise all the interesting cases in this pass.
  3583. %
  3584. {\if\edition\racketEd
  3585. In the \code{run-tests.rkt} script, add the following entry to the
  3586. list of \code{passes} and then run the script to test your compiler.
  3587. \begin{lstlisting}
  3588. (list "patch instructions" patch_instructions interp_x86-0)
  3589. \end{lstlisting}
  3590. \fi}
  3591. {\if\edition\pythonEd
  3592. Run the \code{run-tests.py} script to to check
  3593. whether the output programs produce the same result as the input
  3594. programs.
  3595. \fi}
  3596. \end{exercise}
  3597. \section{Generate Prelude and Conclusion}
  3598. \label{sec:print-x86}
  3599. \index{subject}{prelude}\index{subject}{conclusion}
  3600. The last step of the compiler from \LangVar{} to x86 is to generate
  3601. the \code{main} function with a prelude and conclusion wrapped around
  3602. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3603. discussed in section~\ref{sec:x86}.
  3604. When running on Mac OS X, your compiler should prefix an underscore to
  3605. all labels, e.g., changing \key{main} to \key{\_main}.
  3606. %
  3607. \racket{The Racket call \code{(system-type 'os)} is useful for
  3608. determining which operating system the compiler is running on. It
  3609. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3610. %
  3611. \python{The Python \code{platform} library includes a \code{system()}
  3612. function that returns \code{'Linux'}, \code{'Windows'}, or
  3613. \code{'Darwin'} (for Mac).}
  3614. \begin{exercise}\normalfont\normalsize
  3615. %
  3616. Implement the \key{prelude\_and\_conclusion} pass in
  3617. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3618. %
  3619. {\if\edition\racketEd
  3620. In the \code{run-tests.rkt} script, add the following entry to the
  3621. list of \code{passes} and then run the script to test your compiler.
  3622. \begin{lstlisting}
  3623. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3624. \end{lstlisting}
  3625. %
  3626. Uncomment the call to the \key{compiler-tests} function
  3627. (appendix~\ref{appendix:utilities}), which tests your complete
  3628. compiler by executing the generated x86 code. It translates the x86
  3629. AST that you produce into a string by invoking the \code{print-x86}
  3630. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3631. the provided \key{runtime.c} file to \key{runtime.o} using
  3632. \key{gcc}. Run the script to test your compiler.
  3633. %
  3634. \fi}
  3635. {\if\edition\pythonEd
  3636. %
  3637. Run the \code{run-tests.py} script to to check whether the output
  3638. programs produce the same result as the input programs. That script
  3639. translates the x86 AST that you produce into a string by invoking the
  3640. \code{repr} method that is implemented by the x86 AST classes in
  3641. \code{x86\_ast.py}.
  3642. %
  3643. \fi}
  3644. \end{exercise}
  3645. \section{Challenge: Partial Evaluator for \LangVar{}}
  3646. \label{sec:pe-Lvar}
  3647. \index{subject}{partial evaluation}
  3648. This section describes two optional challenge exercises that involve
  3649. adapting and improving the partial evaluator for \LangInt{} that was
  3650. introduced in section~\ref{sec:partial-evaluation}.
  3651. \begin{exercise}\label{ex:pe-Lvar}
  3652. \normalfont\normalsize
  3653. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3654. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3655. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3656. %
  3657. \racket{\key{let} binding}\python{assignment}
  3658. %
  3659. to the \LangInt{} language, so you will need to add cases for them in
  3660. the \code{pe\_exp}
  3661. %
  3662. \racket{function.}
  3663. %
  3664. \python{and \code{pe\_stmt} functions.}
  3665. %
  3666. Once complete, add the partial evaluation pass to the front of your
  3667. compiler, and make sure that your compiler still passes all the
  3668. tests.
  3669. \end{exercise}
  3670. \begin{exercise}
  3671. \normalfont\normalsize
  3672. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3673. \code{pe\_add} auxiliary functions with functions that know more about
  3674. arithmetic. For example, your partial evaluator should translate
  3675. {\if\edition\racketEd
  3676. \[
  3677. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3678. \code{(+ 2 (read))}
  3679. \]
  3680. \fi}
  3681. {\if\edition\pythonEd
  3682. \[
  3683. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3684. \code{2 + input\_int()}
  3685. \]
  3686. \fi}
  3687. %
  3688. To accomplish this, the \code{pe\_exp} function should produce output
  3689. in the form of the $\itm{residual}$ nonterminal of the following
  3690. grammar. The idea is that when processing an addition expression, we
  3691. can always produce one of the following: (1) an integer constant, (2)
  3692. an addition expression with an integer constant on the left-hand side
  3693. but not the right-hand side, or (3) an addition expression in which
  3694. neither subexpression is a constant.
  3695. %
  3696. {\if\edition\racketEd
  3697. \[
  3698. \begin{array}{lcl}
  3699. \itm{inert} &::=& \Var
  3700. \MID \LP\key{read}\RP
  3701. \MID \LP\key{-} ~\Var\RP
  3702. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3703. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3704. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3705. \itm{residual} &::=& \Int
  3706. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3707. \MID \itm{inert}
  3708. \end{array}
  3709. \]
  3710. \fi}
  3711. {\if\edition\pythonEd
  3712. \[
  3713. \begin{array}{lcl}
  3714. \itm{inert} &::=& \Var
  3715. \MID \key{input\_int}\LP\RP
  3716. \MID \key{-} \Var
  3717. \MID \key{-} \key{input\_int}\LP\RP
  3718. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3719. \itm{residual} &::=& \Int
  3720. \MID \Int ~ \key{+} ~ \itm{inert}
  3721. \MID \itm{inert}
  3722. \end{array}
  3723. \]
  3724. \fi}
  3725. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3726. inputs are $\itm{residual}$ expressions and they should return
  3727. $\itm{residual}$ expressions. Once the improvements are complete,
  3728. make sure that your compiler still passes all the tests. After
  3729. all, fast code is useless if it produces incorrect results!
  3730. \end{exercise}
  3731. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3732. \chapter{Parsing}
  3733. \label{ch:parsing-Lvar}
  3734. \setcounter{footnote}{0}
  3735. \index{subject}{parsing}
  3736. In this chapter we learn how to use the Lark parser generator to
  3737. translate the concrete syntax of \LangVar{} (a sequence of characters)
  3738. into an abstract syntax tree. A parser generator takes in a
  3739. specification of the concrete syntax and produces a parser. Even
  3740. though a parser generator does most of the work for us, using one
  3741. properly requires considerable knowledge about parsing algorithms. In
  3742. particular, we must learn about the specification languages used by
  3743. parser generators and we must learn how to deal with ambiguity in our
  3744. language specifications.
  3745. The process of parsing is traditionally subdivided into two phases:
  3746. \emph{lexical analysis} (also called scanning) and
  3747. \emph{parsing}. The lexical analysis phase translates the sequence of
  3748. characters into a sequence of \emph{tokens}, that is, words consisting
  3749. of several characters. The parsing phase organizes the tokens into a
  3750. \emph{parse tree} that captures how the tokens were matched by rules
  3751. in the grammar of the language. The reason for the subdivision into
  3752. two phases is to enable the use of a faster but less powerful
  3753. algorithm for lexical analysis and the use of a slower but more
  3754. powerful algorithm for parsing.
  3755. %
  3756. Likewise, parser generators typical come in pairs, with separate
  3757. generators for the lexical analyzer (or lexer for short) and for the
  3758. parser. A paricularly influential pair of generators were
  3759. \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3760. by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3761. written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3762. Compiler Compiler.
  3763. The Lark parse generator that we use in this chapter includes both a
  3764. lexical analyzer and a parser. The next section discusses lexical
  3765. analysis and the remainder of the chapter discusses parsing.
  3766. \section{Lexical analysis}
  3767. \label{sec:lex}
  3768. The lexical analyzers produced by Lark turn a sequence of characters
  3769. (a string) into a sequence of token objects. For example, converting the string
  3770. \begin{lstlisting}
  3771. 'print(1 + 3)'
  3772. \end{lstlisting}
  3773. \noindent into the following sequence of token objects
  3774. \begin{lstlisting}
  3775. Token('PRINT', 'print')
  3776. Token('LPAR', '(')
  3777. Token('INT', '1')
  3778. Token('PLUS', '+')
  3779. Token('INT', '3')
  3780. Token('RPAR', ')')
  3781. Token('NEWLINE', '\n')
  3782. \end{lstlisting}
  3783. Each token includes a field for its \code{type}, such as \code{'INT'},
  3784. and a field for its \code{value}, such as \code{'1'}.
  3785. Following in the tradition of \code{lex}, the specification language
  3786. for Lark's lexical analysis generator is one regular expression for
  3787. each type of the token. The term \emph{regular} comes from \emph{regular
  3788. languages}, which are the languages that can be recognized by a
  3789. finite automata. A \emph{regular expression} is a pattern formed of
  3790. the following core elements:\index{subject}{regular expression}
  3791. \begin{itemize}
  3792. \item A single character, e.g. \code{"a"}. The only string that matches this
  3793. regular expression is \code{'a'}.
  3794. \item Two regular expressions, one followed by the other
  3795. (concatenation), e.g. \code{"bc"}. The only string that matches
  3796. this regular expression is \code{'bc'}.
  3797. \item One regular expression or another (alternation), e.g.
  3798. \code{"a|bc"}. Both the string \code{'a'} and \code{'bc'} would
  3799. be matched by this pattern.
  3800. \item A regular expression repeated zero or more times (Kleene
  3801. closure), e.g. \code{"(a|bc)*"}. The string \code{'bcabcbc'}
  3802. would match this pattern, but not \code{'bccba'}.
  3803. \item The empty sequence.
  3804. \end{itemize}
  3805. Parentheses can be used to control the grouping within a regular
  3806. expression.
  3807. For our convenience, Lark also accepts an extended set of regular
  3808. expressions that are automatically translates into the core regular
  3809. expressions.
  3810. \begin{itemize}
  3811. \item Match one of a set of characters, for example, \code{[abc]}
  3812. is equivalent to \code{a|b|c}.
  3813. \item Match one of a range of characters, for example, \code{[a-z]}
  3814. matches any lowercase letter in the alphabet.
  3815. \item Repetition one or more times, for example, \code{[a-z]+}
  3816. will match any sequence of one or more lowercase letters,
  3817. such as \code{'b'} and \code{'bzca'}.
  3818. \item Zero or one matches, for example, \code{a? b} matches
  3819. both \code{'ab'} and \code{'b'}.
  3820. \item A string, such as \code{"hello"}, which matches itself,
  3821. that is, \code{'hello'}.
  3822. \end{itemize}
  3823. In a Lark grammar file, specify a name for each type of token followed
  3824. by a colon and then a regular expression surrounded by \code{/}
  3825. characters. For example, the \code{DIGIT}, \code{INT}, \code{NEWLINE},
  3826. and \code{PRINT} types of tokens are specified in the following way.
  3827. \begin{lstlisting}
  3828. DIGIT: /[0-9]/
  3829. INT: DIGIT+
  3830. NEWLINE: (/\r/? /\n/)+
  3831. PRINT: "print"
  3832. \end{lstlisting}
  3833. \noindent (In Lark, the regular expression operators can be used both
  3834. inside a regular expression, that is, between the \code{/} characters,
  3835. and they can be used to combine regular expressions, outside the
  3836. \code{/} characters.)
  3837. \section{Grammars and Parse Trees}
  3838. \label{sec:CFG}
  3839. In section~\ref{sec:grammar} we learned how to use grammar rules to
  3840. specify the abstract syntax of a language. We now use grammar rules to
  3841. specify the concrete syntax. Recall that each rule has a left-hand
  3842. side and a right-hand side. However, this time each right-hand side
  3843. expresses a pattern to match against a string, instead of matching
  3844. against an abstract syntax tree. In particular, each right-hand side
  3845. is a sequence of \emph{symbols}\index{subject}{symbol}, where a symbol
  3846. is either a terminal or nonterminal. A
  3847. \emph{terminal}\index{subject}{terminal} is either a string or the
  3848. name of a type of token. The nonterminals play the same role as
  3849. before, defining categories of syntax.
  3850. As an example, let us recall the \LangInt{} language, which included
  3851. the following rules for its abstract syntax.
  3852. \begin{align*}
  3853. \Exp &::= \INT{\Int}\\
  3854. \Exp &::= \ADD{\Exp}{\Exp}
  3855. \end{align*}
  3856. The corresponding rules for its concrete syntax are as follows.
  3857. \begin{align}
  3858. \Exp &::= \code{INT} \label{eq:parse-int}\\
  3859. \Exp &::= \Exp\; \code{"+"} \; \Exp \label{eq:parse-plus}
  3860. \end{align}
  3861. The rule \eqref{eq:parse-int} says that any string that matches the
  3862. regular expression for \code{INT} can also be categorized, that is, parsed
  3863. as an expression. The rule \eqref{eq:parse-plus} says that any string that
  3864. parses as an expression, followed by the \code{+} character, followed
  3865. by another expression, can itself be parsed as an expression.
  3866. For example, the string \code{'1+3'} is an \Exp{} because
  3867. \code{'1'} and \code{'3'} are both \Exp{} by rule \eqref{eq:parse-int},
  3868. and then rule \eqref{eq:parse-plus} applies to categorize
  3869. \code{'1+3'} as an \Exp{}. We can visualize the application of grammar
  3870. rules to categorize a string using a
  3871. \emph{parse tree}\index{subject}{parse tree}. Each internal node in the tree
  3872. is an application of a grammar rule and the leaf nodes are substrings of the
  3873. input program.
  3874. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3875. \chapter{Register Allocation}
  3876. \label{ch:register-allocation-Lvar}
  3877. \setcounter{footnote}{0}
  3878. \index{subject}{register allocation}
  3879. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  3880. storing variables on the procedure call stack. The CPU may require tens
  3881. to hundreds of cycles to access a location on the stack, whereas
  3882. accessing a register takes only a single cycle. In this chapter we
  3883. improve the efficiency of our generated code by storing some variables
  3884. in registers. The goal of register allocation is to fit as many
  3885. variables into registers as possible. Some programs have more
  3886. variables than registers, so we cannot always map each variable to a
  3887. different register. Fortunately, it is common for different variables
  3888. to be in use during different periods of time during program
  3889. execution, and in those cases we can map multiple variables to the
  3890. same register.
  3891. The program shown in figure~\ref{fig:reg-eg} serves as a running
  3892. example. The source program is on the left and the output of
  3893. instruction selection is on the right. The program is almost
  3894. completely in the x86 assembly language, but it still uses variables.
  3895. Consider variables \code{x} and \code{z}. After the variable \code{x}
  3896. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  3897. the other hand, is used only after this point, so \code{x} and
  3898. \code{z} could share the same register.
  3899. \begin{figure}
  3900. \begin{tcolorbox}[colback=white]
  3901. \begin{minipage}{0.45\textwidth}
  3902. Example \LangVar{} program:
  3903. % var_test_28.rkt
  3904. {\if\edition\racketEd
  3905. \begin{lstlisting}
  3906. (let ([v 1])
  3907. (let ([w 42])
  3908. (let ([x (+ v 7)])
  3909. (let ([y x])
  3910. (let ([z (+ x w)])
  3911. (+ z (- y)))))))
  3912. \end{lstlisting}
  3913. \fi}
  3914. {\if\edition\pythonEd
  3915. \begin{lstlisting}
  3916. v = 1
  3917. w = 42
  3918. x = v + 7
  3919. y = x
  3920. z = x + w
  3921. print(z + (- y))
  3922. \end{lstlisting}
  3923. \fi}
  3924. \end{minipage}
  3925. \begin{minipage}{0.45\textwidth}
  3926. After instruction selection:
  3927. {\if\edition\racketEd
  3928. \begin{lstlisting}
  3929. locals-types:
  3930. x : Integer, y : Integer,
  3931. z : Integer, t : Integer,
  3932. v : Integer, w : Integer
  3933. start:
  3934. movq $1, v
  3935. movq $42, w
  3936. movq v, x
  3937. addq $7, x
  3938. movq x, y
  3939. movq x, z
  3940. addq w, z
  3941. movq y, t
  3942. negq t
  3943. movq z, %rax
  3944. addq t, %rax
  3945. jmp conclusion
  3946. \end{lstlisting}
  3947. \fi}
  3948. {\if\edition\pythonEd
  3949. \begin{lstlisting}
  3950. movq $1, v
  3951. movq $42, w
  3952. movq v, x
  3953. addq $7, x
  3954. movq x, y
  3955. movq x, z
  3956. addq w, z
  3957. movq y, tmp_0
  3958. negq tmp_0
  3959. movq z, tmp_1
  3960. addq tmp_0, tmp_1
  3961. movq tmp_1, %rdi
  3962. callq print_int
  3963. \end{lstlisting}
  3964. \fi}
  3965. \end{minipage}
  3966. \end{tcolorbox}
  3967. \caption{A running example for register allocation.}
  3968. \label{fig:reg-eg}
  3969. \end{figure}
  3970. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  3971. compute where a variable is in use. Once we have that information, we
  3972. compute which variables are in use at the same time, i.e., which ones
  3973. \emph{interfere}\index{subject}{interfere} with each other, and
  3974. represent this relation as an undirected graph whose vertices are
  3975. variables and edges indicate when two variables interfere
  3976. (section~\ref{sec:build-interference}). We then model register
  3977. allocation as a graph coloring problem
  3978. (section~\ref{sec:graph-coloring}).
  3979. If we run out of registers despite these efforts, we place the
  3980. remaining variables on the stack, similarly to how we handled
  3981. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  3982. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3983. location. The decision to spill a variable is handled as part of the
  3984. graph coloring process.
  3985. We make the simplifying assumption that each variable is assigned to
  3986. one location (a register or stack address). A more sophisticated
  3987. approach is to assign a variable to one or more locations in different
  3988. regions of the program. For example, if a variable is used many times
  3989. in short sequence and then used again only after many other
  3990. instructions, it could be more efficient to assign the variable to a
  3991. register during the initial sequence and then move it to the stack for
  3992. the rest of its lifetime. We refer the interested reader to
  3993. \citet{Cooper:2011aa} (chapter 13) for more information about that
  3994. approach.
  3995. % discuss prioritizing variables based on how much they are used.
  3996. \section{Registers and Calling Conventions}
  3997. \label{sec:calling-conventions}
  3998. \index{subject}{calling conventions}
  3999. As we perform register allocation, we must be aware of the
  4000. \emph{calling conventions} \index{subject}{calling conventions} that
  4001. govern how functions calls are performed in x86.
  4002. %
  4003. Even though \LangVar{} does not include programmer-defined functions,
  4004. our generated code includes a \code{main} function that is called by
  4005. the operating system and our generated code contains calls to the
  4006. \code{read\_int} function.
  4007. Function calls require coordination between two pieces of code that
  4008. may be written by different programmers or generated by different
  4009. compilers. Here we follow the System V calling conventions that are
  4010. used by the GNU C compiler on Linux and
  4011. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4012. %
  4013. The calling conventions include rules about how functions share the
  4014. use of registers. In particular, the caller is responsible for freeing
  4015. some registers prior to the function call for use by the callee.
  4016. These are called the \emph{caller-saved registers}
  4017. \index{subject}{caller-saved registers}
  4018. and they are
  4019. \begin{lstlisting}
  4020. rax rcx rdx rsi rdi r8 r9 r10 r11
  4021. \end{lstlisting}
  4022. On the other hand, the callee is responsible for preserving the values
  4023. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4024. which are
  4025. \begin{lstlisting}
  4026. rsp rbp rbx r12 r13 r14 r15
  4027. \end{lstlisting}
  4028. We can think about this caller/callee convention from two points of
  4029. view, the caller view and the callee view, as follows:
  4030. \begin{itemize}
  4031. \item The caller should assume that all the caller-saved registers get
  4032. overwritten with arbitrary values by the callee. On the other hand,
  4033. the caller can safely assume that all the callee-saved registers
  4034. retain their original values.
  4035. \item The callee can freely use any of the caller-saved registers.
  4036. However, if the callee wants to use a callee-saved register, the
  4037. callee must arrange to put the original value back in the register
  4038. prior to returning to the caller. This can be accomplished by saving
  4039. the value to the stack in the prelude of the function and restoring
  4040. the value in the conclusion of the function.
  4041. \end{itemize}
  4042. In x86, registers are also used for passing arguments to a function
  4043. and for the return value. In particular, the first six arguments of a
  4044. function are passed in the following six registers, in this order.
  4045. \index{subject}{argument-passing registers}
  4046. \index{subject}{parameter-passing registers}
  4047. \begin{lstlisting}
  4048. rdi rsi rdx rcx r8 r9
  4049. \end{lstlisting}
  4050. If there are more than six arguments, the convention is to use
  4051. space on the frame of the caller for the rest of the
  4052. arguments. However, in chapter~\ref{ch:Lfun} we arrange never to
  4053. need more than six arguments.
  4054. %
  4055. \racket{For now, the only function we care about is \code{read\_int},
  4056. which takes zero arguments.}
  4057. %
  4058. \python{For now, the only functions we care about are \code{read\_int}
  4059. and \code{print\_int}, which take zero and one argument, respectively.}
  4060. %
  4061. The register \code{rax} is used for the return value of a function.
  4062. The next question is how these calling conventions impact register
  4063. allocation. Consider the \LangVar{} program presented in
  4064. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4065. example from the caller point of view and then from the callee point
  4066. of view. We refer to a variable that is in use during a function call
  4067. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4068. The program makes two calls to \READOP{}. The variable \code{x} is
  4069. call-live because it is in use during the second call to \READOP{}; we
  4070. must ensure that the value in \code{x} does not get overwritten during
  4071. the call to \READOP{}. One obvious approach is to save all the values
  4072. that reside in caller-saved registers to the stack prior to each
  4073. function call and to restore them after each call. That way, if the
  4074. register allocator chooses to assign \code{x} to a caller-saved
  4075. register, its value will be preserved across the call to \READOP{}.
  4076. However, saving and restoring to the stack is relatively slow. If
  4077. \code{x} is not used many times, it may be better to assign \code{x}
  4078. to a stack location in the first place. Or better yet, if we can
  4079. arrange for \code{x} to be placed in a callee-saved register, then it
  4080. won't need to be saved and restored during function calls.
  4081. The approach that we recommend for call-live variables is either to
  4082. assign them to callee-saved registers or to spill them to the
  4083. stack. On the other hand, for variables that are not call-live, we try
  4084. the following alternatives in order: (1) look for an available
  4085. caller-saved register (to leave room for other variables in the
  4086. callee-saved register), (2) look for a callee-saved register, and (3)
  4087. spill the variable to the stack.
  4088. It is straightforward to implement this approach in a graph coloring
  4089. register allocator. First, we know which variables are call-live
  4090. because we already need to compute which variables are in use at every
  4091. instruction (section~\ref{sec:liveness-analysis-Lvar}). Second, when
  4092. we build the interference graph
  4093. (section~\ref{sec:build-interference}), we can place an edge between
  4094. each of the call-live variables and the caller-saved registers in the
  4095. interference graph. This will prevent the graph coloring algorithm
  4096. from assigning them to caller-saved registers.
  4097. Returning to the example in
  4098. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4099. generated x86 code on the right-hand side. Notice that variable
  4100. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  4101. is already in a safe place during the second call to
  4102. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  4103. \code{rcx}, a caller-saved register, because \code{y} is not a
  4104. call-live variable.
  4105. Next we analyze the example from the callee point of view, focusing on
  4106. the prelude and conclusion of the \code{main} function. As usual, the
  4107. prelude begins with saving the \code{rbp} register to the stack and
  4108. setting the \code{rbp} to the current stack pointer. We now know why
  4109. it is necessary to save the \code{rbp}: it is a callee-saved register.
  4110. The prelude then pushes \code{rbx} to the stack because (1) \code{rbx}
  4111. is a callee-saved register and (2) \code{rbx} is assigned to a variable
  4112. (\code{x}). The other callee-saved registers are not saved in the
  4113. prelude because they are not used. The prelude subtracts 8 bytes from
  4114. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4115. conclusion, we see that \code{rbx} is restored from the stack with a
  4116. \code{popq} instruction.
  4117. \index{subject}{prelude}\index{subject}{conclusion}
  4118. \begin{figure}[tp]
  4119. \begin{tcolorbox}[colback=white]
  4120. \begin{minipage}{0.45\textwidth}
  4121. Example \LangVar{} program:
  4122. %var_test_14.rkt
  4123. {\if\edition\racketEd
  4124. \begin{lstlisting}
  4125. (let ([x (read)])
  4126. (let ([y (read)])
  4127. (+ (+ x y) 42)))
  4128. \end{lstlisting}
  4129. \fi}
  4130. {\if\edition\pythonEd
  4131. \begin{lstlisting}
  4132. x = input_int()
  4133. y = input_int()
  4134. print((x + y) + 42)
  4135. \end{lstlisting}
  4136. \fi}
  4137. \end{minipage}
  4138. \begin{minipage}{0.45\textwidth}
  4139. Generated x86 assembly:
  4140. {\if\edition\racketEd
  4141. \begin{lstlisting}
  4142. start:
  4143. callq read_int
  4144. movq %rax, %rbx
  4145. callq read_int
  4146. movq %rax, %rcx
  4147. addq %rcx, %rbx
  4148. movq %rbx, %rax
  4149. addq $42, %rax
  4150. jmp _conclusion
  4151. .globl main
  4152. main:
  4153. pushq %rbp
  4154. movq %rsp, %rbp
  4155. pushq %rbx
  4156. subq $8, %rsp
  4157. jmp start
  4158. conclusion:
  4159. addq $8, %rsp
  4160. popq %rbx
  4161. popq %rbp
  4162. retq
  4163. \end{lstlisting}
  4164. \fi}
  4165. {\if\edition\pythonEd
  4166. \begin{lstlisting}
  4167. .globl main
  4168. main:
  4169. pushq %rbp
  4170. movq %rsp, %rbp
  4171. pushq %rbx
  4172. subq $8, %rsp
  4173. callq read_int
  4174. movq %rax, %rbx
  4175. callq read_int
  4176. movq %rax, %rcx
  4177. movq %rbx, %rdx
  4178. addq %rcx, %rdx
  4179. movq %rdx, %rcx
  4180. addq $42, %rcx
  4181. movq %rcx, %rdi
  4182. callq print_int
  4183. addq $8, %rsp
  4184. popq %rbx
  4185. popq %rbp
  4186. retq
  4187. \end{lstlisting}
  4188. \fi}
  4189. \end{minipage}
  4190. \end{tcolorbox}
  4191. \caption{An example with function calls.}
  4192. \label{fig:example-calling-conventions}
  4193. \end{figure}
  4194. %\clearpage
  4195. \section{Liveness Analysis}
  4196. \label{sec:liveness-analysis-Lvar}
  4197. \index{subject}{liveness analysis}
  4198. The \code{uncover\_live} \racket{pass}\python{function} performs
  4199. \emph{liveness analysis}; that is, it discovers which variables are
  4200. in use in different regions of a program.
  4201. %
  4202. A variable or register is \emph{live} at a program point if its
  4203. current value is used at some later point in the program. We refer to
  4204. variables, stack locations, and registers collectively as
  4205. \emph{locations}.
  4206. %
  4207. Consider the following code fragment in which there are two writes to
  4208. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4209. time?
  4210. \begin{center}
  4211. \begin{minipage}{0.96\textwidth}
  4212. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4213. movq $5, a
  4214. movq $30, b
  4215. movq a, c
  4216. movq $10, b
  4217. addq b, c
  4218. \end{lstlisting}
  4219. \end{minipage}
  4220. \end{center}
  4221. The answer is no, because \code{a} is live from line 1 to 3 and
  4222. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4223. line 2 is never used because it is overwritten (line 4) before the
  4224. next read (line 5).
  4225. The live locations for each instruction can be computed by traversing
  4226. the instruction sequence back to front (i.e., backward in execution
  4227. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4228. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4229. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  4230. locations before instruction $I_k$. \racket{We recommend representing
  4231. these sets with the Racket \code{set} data structure described in
  4232. figure~\ref{fig:set}.} \python{We recommend representing these sets
  4233. with the Python
  4234. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4235. data structure.}
  4236. {\if\edition\racketEd
  4237. \begin{figure}[tp]
  4238. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4239. \small
  4240. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4241. A \emph{set} is an unordered collection of elements without duplicates.
  4242. Here are some of the operations defined on sets.
  4243. \index{subject}{set}
  4244. \begin{description}
  4245. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4246. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4247. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4248. difference of the two sets.
  4249. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4250. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4251. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4252. \end{description}
  4253. \end{tcolorbox}
  4254. %\end{wrapfigure}
  4255. \caption{The \code{set} data structure.}
  4256. \label{fig:set}
  4257. \end{figure}
  4258. \fi}
  4259. The live locations after an instruction are always the same as the
  4260. live locations before the next instruction.
  4261. \index{subject}{live-after} \index{subject}{live-before}
  4262. \begin{equation} \label{eq:live-after-before-next}
  4263. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4264. \end{equation}
  4265. To start things off, there are no live locations after the last
  4266. instruction, so
  4267. \begin{equation}\label{eq:live-last-empty}
  4268. L_{\mathsf{after}}(n) = \emptyset
  4269. \end{equation}
  4270. We then apply the following rule repeatedly, traversing the
  4271. instruction sequence back to front.
  4272. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4273. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4274. \end{equation}
  4275. where $W(k)$ are the locations written to by instruction $I_k$, and
  4276. $R(k)$ are the locations read by instruction $I_k$.
  4277. {\if\edition\racketEd
  4278. %
  4279. There is a special case for \code{jmp} instructions. The locations
  4280. that are live before a \code{jmp} should be the locations in
  4281. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  4282. maintaining an alist named \code{label->live} that maps each label to
  4283. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  4284. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4285. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  4286. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4287. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4288. %
  4289. \fi}
  4290. Let us walk through the previous example, applying these formulas
  4291. starting with the instruction on line 5 of the code fragment. We
  4292. collect the answers in figure~\ref{fig:liveness-example-0}. The
  4293. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  4294. $\emptyset$ because it is the last instruction
  4295. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  4296. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  4297. variables \code{b} and \code{c}
  4298. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads})
  4299. \[
  4300. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4301. \]
  4302. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4303. the live-before set from line 5 to be the live-after set for this
  4304. instruction (formula~\eqref{eq:live-after-before-next}).
  4305. \[
  4306. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4307. \]
  4308. This move instruction writes to \code{b} and does not read from any
  4309. variables, so we have the following live-before set
  4310. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  4311. \[
  4312. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4313. \]
  4314. The live-before for instruction \code{movq a, c}
  4315. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4316. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  4317. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4318. variable that is not live and does not read from a variable.
  4319. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4320. because it writes to variable \code{a}.
  4321. \begin{figure}[tbp]
  4322. \centering
  4323. \begin{tcolorbox}[colback=white]
  4324. \hspace{10pt}
  4325. \begin{minipage}{0.4\textwidth}
  4326. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4327. movq $5, a
  4328. movq $30, b
  4329. movq a, c
  4330. movq $10, b
  4331. addq b, c
  4332. \end{lstlisting}
  4333. \end{minipage}
  4334. \vrule\hspace{10pt}
  4335. \begin{minipage}{0.45\textwidth}
  4336. \begin{align*}
  4337. L_{\mathsf{before}}(1)= \emptyset,
  4338. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4339. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4340. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4341. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4342. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4343. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4344. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4345. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4346. L_{\mathsf{after}}(5)= \emptyset
  4347. \end{align*}
  4348. \end{minipage}
  4349. \end{tcolorbox}
  4350. \caption{Example output of liveness analysis on a short example.}
  4351. \label{fig:liveness-example-0}
  4352. \end{figure}
  4353. \begin{exercise}\normalfont\normalsize
  4354. Perform liveness analysis by hand on the running example in
  4355. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4356. sets for each instruction. Compare your answers to the solution
  4357. shown in figure~\ref{fig:live-eg}.
  4358. \end{exercise}
  4359. \begin{figure}[tp]
  4360. \hspace{20pt}
  4361. \begin{minipage}{0.55\textwidth}
  4362. \begin{tcolorbox}[colback=white]
  4363. {\if\edition\racketEd
  4364. \begin{lstlisting}
  4365. |$\{\ttm{rsp}\}$|
  4366. movq $1, v
  4367. |$\{\ttm{v},\ttm{rsp}\}$|
  4368. movq $42, w
  4369. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4370. movq v, x
  4371. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4372. addq $7, x
  4373. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4374. movq x, y
  4375. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4376. movq x, z
  4377. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4378. addq w, z
  4379. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4380. movq y, t
  4381. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4382. negq t
  4383. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4384. movq z, %rax
  4385. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4386. addq t, %rax
  4387. |$\{\ttm{rax},\ttm{rsp}\}$|
  4388. jmp conclusion
  4389. \end{lstlisting}
  4390. \fi}
  4391. {\if\edition\pythonEd
  4392. \begin{lstlisting}
  4393. movq $1, v
  4394. |$\{\ttm{v}\}$|
  4395. movq $42, w
  4396. |$\{\ttm{w}, \ttm{v}\}$|
  4397. movq v, x
  4398. |$\{\ttm{w}, \ttm{x}\}$|
  4399. addq $7, x
  4400. |$\{\ttm{w}, \ttm{x}\}$|
  4401. movq x, y
  4402. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4403. movq x, z
  4404. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4405. addq w, z
  4406. |$\{\ttm{y}, \ttm{z}\}$|
  4407. movq y, tmp_0
  4408. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4409. negq tmp_0
  4410. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4411. movq z, tmp_1
  4412. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4413. addq tmp_0, tmp_1
  4414. |$\{\ttm{tmp\_1}\}$|
  4415. movq tmp_1, %rdi
  4416. |$\{\ttm{rdi}\}$|
  4417. callq print_int
  4418. |$\{\}$|
  4419. \end{lstlisting}
  4420. \fi}
  4421. \end{tcolorbox}
  4422. \end{minipage}
  4423. \caption{The running example annotated with live-after sets.}
  4424. \label{fig:live-eg}
  4425. \end{figure}
  4426. \begin{exercise}\normalfont\normalsize
  4427. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4428. %
  4429. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4430. field of the \code{Block} structure.}
  4431. %
  4432. \python{Return a dictionary that maps each instruction to its
  4433. live-after set.}
  4434. %
  4435. \racket{We recommend creating an auxiliary function that takes a list
  4436. of instructions and an initial live-after set (typically empty) and
  4437. returns the list of live-after sets.}
  4438. %
  4439. We recommend creating auxiliary functions to (1) compute the set
  4440. of locations that appear in an \Arg{}, (2) compute the locations read
  4441. by an instruction (the $R$ function), and (3) the locations written by
  4442. an instruction (the $W$ function). The \code{callq} instruction should
  4443. include all the caller-saved registers in its write set $W$ because
  4444. the calling convention says that those registers may be written to
  4445. during the function call. Likewise, the \code{callq} instruction
  4446. should include the appropriate argument-passing registers in its
  4447. read set $R$, depending on the arity of the function being
  4448. called. (This is why the abstract syntax for \code{callq} includes the
  4449. arity.)
  4450. \end{exercise}
  4451. %\clearpage
  4452. \section{Build the Interference Graph}
  4453. \label{sec:build-interference}
  4454. {\if\edition\racketEd
  4455. \begin{figure}[tp]
  4456. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4457. \small
  4458. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4459. A \emph{graph} is a collection of vertices and edges where each
  4460. edge connects two vertices. A graph is \emph{directed} if each
  4461. edge points from a source to a target. Otherwise the graph is
  4462. \emph{undirected}.
  4463. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4464. \begin{description}
  4465. %% We currently don't use directed graphs. We instead use
  4466. %% directed multi-graphs. -Jeremy
  4467. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4468. directed graph from a list of edges. Each edge is a list
  4469. containing the source and target vertex.
  4470. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4471. undirected graph from a list of edges. Each edge is represented by
  4472. a list containing two vertices.
  4473. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4474. inserts a vertex into the graph.
  4475. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4476. inserts an edge between the two vertices.
  4477. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4478. returns a sequence of vertices adjacent to the vertex.
  4479. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4480. returns a sequence of all vertices in the graph.
  4481. \end{description}
  4482. \end{tcolorbox}
  4483. %\end{wrapfigure}
  4484. \caption{The Racket \code{graph} package.}
  4485. \label{fig:graph}
  4486. \end{figure}
  4487. \fi}
  4488. On the basis of the liveness analysis, we know where each location is
  4489. live. However, during register allocation, we need to answer
  4490. questions of the specific form: are locations $u$ and $v$ live at the
  4491. same time? (If so, they cannot be assigned to the same register.) To
  4492. make this question more efficient to answer, we create an explicit
  4493. data structure, an \emph{interference
  4494. graph}\index{subject}{interference graph}. An interference graph is
  4495. an undirected graph that has an edge between two locations if they are
  4496. live at the same time, that is, if they interfere with each other.
  4497. %
  4498. \racket{We recommend using the Racket \code{graph} package
  4499. (figure~\ref{fig:graph}) to represent the interference graph.}
  4500. %
  4501. \python{We provide implementations of directed and undirected graph
  4502. data structures in the file \code{graph.py} of the support code.}
  4503. A straightforward way to compute the interference graph is to look at
  4504. the set of live locations between each instruction and add an edge to
  4505. the graph for every pair of variables in the same set. This approach
  4506. is less than ideal for two reasons. First, it can be expensive because
  4507. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4508. locations. Second, in the special case in which two locations hold the
  4509. same value (because one was assigned to the other), they can be live
  4510. at the same time without interfering with each other.
  4511. A better way to compute the interference graph is to focus on
  4512. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4513. must not overwrite something in a live location. So for each
  4514. instruction, we create an edge between the locations being written to
  4515. and the live locations. (However, a location never interferes with
  4516. itself.) For the \key{callq} instruction, we consider all the
  4517. caller-saved registers to have been written to, so an edge is added
  4518. between every live variable and every caller-saved register. Also, for
  4519. \key{movq} there is the special case of two variables holding the same
  4520. value. If a live variable $v$ is the same as the source of the
  4521. \key{movq}, then there is no need to add an edge between $v$ and the
  4522. destination, because they both hold the same value.
  4523. %
  4524. Hence we have the following two rules:
  4525. \begin{enumerate}
  4526. \item If instruction $I_k$ is a move instruction of the form
  4527. \key{movq} $s$\key{,} $d$, then for every $v \in
  4528. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4529. $(d,v)$.
  4530. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4531. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4532. $(d,v)$.
  4533. \end{enumerate}
  4534. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  4535. these rules to each instruction. We highlight a few of the
  4536. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  4537. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4538. so \code{v} interferes with \code{rsp}.}
  4539. %
  4540. \python{The first instruction is \lstinline{movq $1, v}, and the
  4541. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4542. no interference because $\ttm{v}$ is the destination of the move.}
  4543. %
  4544. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  4545. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4546. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4547. %
  4548. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  4549. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4550. $\ttm{x}$ interferes with \ttm{w}.}
  4551. %
  4552. \racket{The next instruction is \lstinline{movq x, y}, and the
  4553. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4554. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4555. \ttm{x} because \ttm{x} is the source of the move and therefore
  4556. \ttm{x} and \ttm{y} hold the same value.}
  4557. %
  4558. \python{The next instruction is \lstinline{movq x, y}, and the
  4559. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4560. applies, so \ttm{y} interferes with \ttm{w} but not
  4561. \ttm{x}, because \ttm{x} is the source of the move and therefore
  4562. \ttm{x} and \ttm{y} hold the same value.}
  4563. %
  4564. Figure~\ref{fig:interference-results} lists the interference results
  4565. for all the instructions, and the resulting interference graph is
  4566. shown in figure~\ref{fig:interfere}.
  4567. \begin{figure}[tbp]
  4568. \begin{tcolorbox}[colback=white]
  4569. \begin{quote}
  4570. {\if\edition\racketEd
  4571. \begin{tabular}{ll}
  4572. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4573. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4574. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4575. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4576. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4577. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4578. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4579. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4580. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4581. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4582. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4583. \lstinline!jmp conclusion!& no interference.
  4584. \end{tabular}
  4585. \fi}
  4586. {\if\edition\pythonEd
  4587. \begin{tabular}{ll}
  4588. \lstinline!movq $1, v!& no interference\\
  4589. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4590. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4591. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4592. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4593. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4594. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4595. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4596. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4597. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4598. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4599. \lstinline!movq tmp_1, %rdi! & no interference \\
  4600. \lstinline!callq print_int!& no interference.
  4601. \end{tabular}
  4602. \fi}
  4603. \end{quote}
  4604. \end{tcolorbox}
  4605. \caption{Interference results for the running example.}
  4606. \label{fig:interference-results}
  4607. \end{figure}
  4608. \begin{figure}[tbp]
  4609. \begin{tcolorbox}[colback=white]
  4610. \large
  4611. {\if\edition\racketEd
  4612. \[
  4613. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4614. \node (rax) at (0,0) {$\ttm{rax}$};
  4615. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4616. \node (t1) at (0,2) {$\ttm{t}$};
  4617. \node (z) at (3,2) {$\ttm{z}$};
  4618. \node (x) at (6,2) {$\ttm{x}$};
  4619. \node (y) at (3,0) {$\ttm{y}$};
  4620. \node (w) at (6,0) {$\ttm{w}$};
  4621. \node (v) at (9,0) {$\ttm{v}$};
  4622. \draw (t1) to (rax);
  4623. \draw (t1) to (z);
  4624. \draw (z) to (y);
  4625. \draw (z) to (w);
  4626. \draw (x) to (w);
  4627. \draw (y) to (w);
  4628. \draw (v) to (w);
  4629. \draw (v) to (rsp);
  4630. \draw (w) to (rsp);
  4631. \draw (x) to (rsp);
  4632. \draw (y) to (rsp);
  4633. \path[-.,bend left=15] (z) edge node {} (rsp);
  4634. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4635. \draw (rax) to (rsp);
  4636. \end{tikzpicture}
  4637. \]
  4638. \fi}
  4639. {\if\edition\pythonEd
  4640. \[
  4641. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4642. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4643. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4644. \node (z) at (3,2) {$\ttm{z}$};
  4645. \node (x) at (6,2) {$\ttm{x}$};
  4646. \node (y) at (3,0) {$\ttm{y}$};
  4647. \node (w) at (6,0) {$\ttm{w}$};
  4648. \node (v) at (9,0) {$\ttm{v}$};
  4649. \draw (t0) to (t1);
  4650. \draw (t0) to (z);
  4651. \draw (z) to (y);
  4652. \draw (z) to (w);
  4653. \draw (x) to (w);
  4654. \draw (y) to (w);
  4655. \draw (v) to (w);
  4656. \end{tikzpicture}
  4657. \]
  4658. \fi}
  4659. \end{tcolorbox}
  4660. \caption{The interference graph of the example program.}
  4661. \label{fig:interfere}
  4662. \end{figure}
  4663. %% Our next concern is to choose a data structure for representing the
  4664. %% interference graph. There are many choices for how to represent a
  4665. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4666. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4667. %% data structure is to study the algorithm that uses the data structure,
  4668. %% determine what operations need to be performed, and then choose the
  4669. %% data structure that provide the most efficient implementations of
  4670. %% those operations. Often times the choice of data structure can have an
  4671. %% effect on the time complexity of the algorithm, as it does here. If
  4672. %% you skim the next section, you will see that the register allocation
  4673. %% algorithm needs to ask the graph for all its vertices and, given a
  4674. %% vertex, it needs to known all the adjacent vertices. Thus, the
  4675. %% correct choice of graph representation is that of an adjacency
  4676. %% list. There are helper functions in \code{utilities.rkt} for
  4677. %% representing graphs using the adjacency list representation:
  4678. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4679. %% (Appendix~\ref{appendix:utilities}).
  4680. %% %
  4681. %% \margincomment{\footnotesize To do: change to use the
  4682. %% Racket graph library. \\ --Jeremy}
  4683. %% %
  4684. %% In particular, those functions use a hash table to map each vertex to
  4685. %% the set of adjacent vertices, and the sets are represented using
  4686. %% Racket's \key{set}, which is also a hash table.
  4687. \begin{exercise}\normalfont\normalsize
  4688. \racket{Implement the compiler pass named \code{build\_interference} according
  4689. to the algorithm suggested here. We recommend using the Racket
  4690. \code{graph} package to create and inspect the interference graph.
  4691. The output graph of this pass should be stored in the $\itm{info}$ field of
  4692. the program, under the key \code{conflicts}.}
  4693. %
  4694. \python{Implement a function named \code{build\_interference}
  4695. according to the algorithm suggested above that
  4696. returns the interference graph.}
  4697. \end{exercise}
  4698. \section{Graph Coloring via Sudoku}
  4699. \label{sec:graph-coloring}
  4700. \index{subject}{graph coloring}
  4701. \index{subject}{sudoku}
  4702. \index{subject}{color}
  4703. We come to the main event discussed in this chapter, mapping variables
  4704. to registers and stack locations. Variables that interfere with each
  4705. other must be mapped to different locations. In terms of the
  4706. interference graph, this means that adjacent vertices must be mapped
  4707. to different locations. If we think of locations as colors, the
  4708. register allocation problem becomes the graph coloring
  4709. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4710. The reader may be more familiar with the graph coloring problem than he
  4711. or she realizes; the popular game of sudoku is an instance of the
  4712. graph coloring problem. The following describes how to build a graph
  4713. out of an initial sudoku board.
  4714. \begin{itemize}
  4715. \item There is one vertex in the graph for each sudoku square.
  4716. \item There is an edge between two vertices if the corresponding squares
  4717. are in the same row, in the same column, or in the same $3\times 3$ region.
  4718. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4719. \item On the basis of the initial assignment of numbers to squares on the
  4720. sudoku board, assign the corresponding colors to the corresponding
  4721. vertices in the graph.
  4722. \end{itemize}
  4723. If you can color the remaining vertices in the graph with the nine
  4724. colors, then you have also solved the corresponding game of sudoku.
  4725. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  4726. the corresponding graph with colored vertices. Here we use a
  4727. monochrome representation of colors, mapping the sudoku number 1 to
  4728. black, 2 to white, and 3 to gray. We show edges for only a sampling
  4729. of the vertices (the colored ones) because showing edges for all the
  4730. vertices would make the graph unreadable.
  4731. \begin{figure}[tbp]
  4732. \begin{tcolorbox}[colback=white]
  4733. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  4734. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4735. \end{tcolorbox}
  4736. \caption{A sudoku game board and the corresponding colored graph.}
  4737. \label{fig:sudoku-graph}
  4738. \end{figure}
  4739. Some techniques for playing sudoku correspond to heuristics used in
  4740. graph coloring algorithms. For example, one of the basic techniques
  4741. for sudoku is called Pencil Marks. The idea is to use a process of
  4742. elimination to determine what numbers are no longer available for a
  4743. square and to write those numbers in the square (writing very
  4744. small). For example, if the number $1$ is assigned to a square, then
  4745. write the pencil mark $1$ in all the squares in the same row, column,
  4746. and region to indicate that $1$ is no longer an option for those other
  4747. squares.
  4748. %
  4749. The Pencil Marks technique corresponds to the notion of
  4750. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  4751. saturation of a vertex, in sudoku terms, is the set of numbers that
  4752. are no longer available. In graph terminology, we have the following
  4753. definition:
  4754. \begin{equation*}
  4755. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4756. \text{ and } \mathrm{color}(v) = c \}
  4757. \end{equation*}
  4758. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4759. edge with $u$.
  4760. The Pencil Marks technique leads to a simple strategy for filling in
  4761. numbers: if there is a square with only one possible number left, then
  4762. choose that number! But what if there are no squares with only one
  4763. possibility left? One brute-force approach is to try them all: choose
  4764. the first one, and if that ultimately leads to a solution, great. If
  4765. not, backtrack and choose the next possibility. One good thing about
  4766. Pencil Marks is that it reduces the degree of branching in the search
  4767. tree. Nevertheless, backtracking can be terribly time consuming. One
  4768. way to reduce the amount of backtracking is to use the
  4769. most-constrained-first heuristic (aka minimum remaining
  4770. values)~\citep{Russell2003}. That is, in choosing a square, always
  4771. choose one with the fewest possibilities left (the vertex with the
  4772. highest saturation). The idea is that choosing highly constrained
  4773. squares earlier rather than later is better, because later on there may
  4774. not be any possibilities left in the highly saturated squares.
  4775. However, register allocation is easier than sudoku, because the
  4776. register allocator can fall back to assigning variables to stack
  4777. locations when the registers run out. Thus, it makes sense to replace
  4778. backtracking with greedy search: make the best choice at the time and
  4779. keep going. We still wish to minimize the number of colors needed, so
  4780. we use the most-constrained-first heuristic in the greedy search.
  4781. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  4782. algorithm for register allocation based on saturation and the
  4783. most-constrained-first heuristic. It is roughly equivalent to the
  4784. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4785. Just as in sudoku, the algorithm represents colors with integers. The
  4786. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4787. for register allocation. The integers $k$ and larger correspond to
  4788. stack locations. The registers that are not used for register
  4789. allocation, such as \code{rax}, are assigned to negative integers. In
  4790. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4791. %% One might wonder why we include registers at all in the liveness
  4792. %% analysis and interference graph. For example, we never allocate a
  4793. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4794. %% leave them out. As we see in chapter~\ref{ch:Lvec}, when we begin
  4795. %% to use register for passing arguments to functions, it will be
  4796. %% necessary for those registers to appear in the interference graph
  4797. %% because those registers will also be assigned to variables, and we
  4798. %% don't want those two uses to encroach on each other. Regarding
  4799. %% registers such as \code{rax} and \code{rsp} that are not used for
  4800. %% variables, we could omit them from the interference graph but that
  4801. %% would require adding special cases to our algorithm, which would
  4802. %% complicate the logic for little gain.
  4803. \begin{figure}[btp]
  4804. \begin{tcolorbox}[colback=white]
  4805. \centering
  4806. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4807. Algorithm: DSATUR
  4808. Input: A graph |$G$|
  4809. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4810. |$W \gets \mathrm{vertices}(G)$|
  4811. while |$W \neq \emptyset$| do
  4812. pick a vertex |$u$| from |$W$| with the highest saturation,
  4813. breaking ties randomly
  4814. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4815. |$\mathrm{color}[u] \gets c$|
  4816. |$W \gets W - \{u\}$|
  4817. \end{lstlisting}
  4818. \end{tcolorbox}
  4819. \caption{The saturation-based greedy graph coloring algorithm.}
  4820. \label{fig:satur-algo}
  4821. \end{figure}
  4822. {\if\edition\racketEd
  4823. With the DSATUR algorithm in hand, let us return to the running
  4824. example and consider how to color the interference graph shown in
  4825. figure~\ref{fig:interfere}.
  4826. %
  4827. We start by assigning each register node to its own color. For
  4828. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4829. assigned $-2$. The variables are not yet colored, so they are
  4830. annotated with a dash. We then update the saturation for vertices that
  4831. are adjacent to a register, obtaining the following annotated
  4832. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4833. it interferes with both \code{rax} and \code{rsp}.
  4834. \[
  4835. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4836. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4837. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4838. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4839. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4840. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4841. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4842. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4843. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4844. \draw (t1) to (rax);
  4845. \draw (t1) to (z);
  4846. \draw (z) to (y);
  4847. \draw (z) to (w);
  4848. \draw (x) to (w);
  4849. \draw (y) to (w);
  4850. \draw (v) to (w);
  4851. \draw (v) to (rsp);
  4852. \draw (w) to (rsp);
  4853. \draw (x) to (rsp);
  4854. \draw (y) to (rsp);
  4855. \path[-.,bend left=15] (z) edge node {} (rsp);
  4856. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4857. \draw (rax) to (rsp);
  4858. \end{tikzpicture}
  4859. \]
  4860. The algorithm says to select a maximally saturated vertex. So, we pick
  4861. $\ttm{t}$ and color it with the first available integer, which is
  4862. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4863. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4864. \[
  4865. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4866. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4867. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4868. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4869. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4870. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4871. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4872. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4873. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4874. \draw (t1) to (rax);
  4875. \draw (t1) to (z);
  4876. \draw (z) to (y);
  4877. \draw (z) to (w);
  4878. \draw (x) to (w);
  4879. \draw (y) to (w);
  4880. \draw (v) to (w);
  4881. \draw (v) to (rsp);
  4882. \draw (w) to (rsp);
  4883. \draw (x) to (rsp);
  4884. \draw (y) to (rsp);
  4885. \path[-.,bend left=15] (z) edge node {} (rsp);
  4886. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4887. \draw (rax) to (rsp);
  4888. \end{tikzpicture}
  4889. \]
  4890. We repeat the process, selecting a maximally saturated vertex,
  4891. choosing \code{z}, and coloring it with the first available number, which
  4892. is $1$. We add $1$ to the saturation for the neighboring vertices
  4893. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4894. \[
  4895. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4896. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4897. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4898. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4899. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4900. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4901. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4902. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4903. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4904. \draw (t1) to (rax);
  4905. \draw (t1) to (z);
  4906. \draw (z) to (y);
  4907. \draw (z) to (w);
  4908. \draw (x) to (w);
  4909. \draw (y) to (w);
  4910. \draw (v) to (w);
  4911. \draw (v) to (rsp);
  4912. \draw (w) to (rsp);
  4913. \draw (x) to (rsp);
  4914. \draw (y) to (rsp);
  4915. \path[-.,bend left=15] (z) edge node {} (rsp);
  4916. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4917. \draw (rax) to (rsp);
  4918. \end{tikzpicture}
  4919. \]
  4920. The most saturated vertices are now \code{w} and \code{y}. We color
  4921. \code{w} with the first available color, which is $0$.
  4922. \[
  4923. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4924. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4925. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4926. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4927. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4928. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4929. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4930. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4931. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4932. \draw (t1) to (rax);
  4933. \draw (t1) to (z);
  4934. \draw (z) to (y);
  4935. \draw (z) to (w);
  4936. \draw (x) to (w);
  4937. \draw (y) to (w);
  4938. \draw (v) to (w);
  4939. \draw (v) to (rsp);
  4940. \draw (w) to (rsp);
  4941. \draw (x) to (rsp);
  4942. \draw (y) to (rsp);
  4943. \path[-.,bend left=15] (z) edge node {} (rsp);
  4944. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4945. \draw (rax) to (rsp);
  4946. \end{tikzpicture}
  4947. \]
  4948. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4949. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4950. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4951. and \code{z}, whose colors are $0$ and $1$ respectively.
  4952. \[
  4953. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4954. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4955. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4956. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4957. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4958. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4959. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4960. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4961. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4962. \draw (t1) to (rax);
  4963. \draw (t1) to (z);
  4964. \draw (z) to (y);
  4965. \draw (z) to (w);
  4966. \draw (x) to (w);
  4967. \draw (y) to (w);
  4968. \draw (v) to (w);
  4969. \draw (v) to (rsp);
  4970. \draw (w) to (rsp);
  4971. \draw (x) to (rsp);
  4972. \draw (y) to (rsp);
  4973. \path[-.,bend left=15] (z) edge node {} (rsp);
  4974. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4975. \draw (rax) to (rsp);
  4976. \end{tikzpicture}
  4977. \]
  4978. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4979. \[
  4980. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4981. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4982. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4983. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4984. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4985. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4986. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4987. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4988. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4989. \draw (t1) to (rax);
  4990. \draw (t1) to (z);
  4991. \draw (z) to (y);
  4992. \draw (z) to (w);
  4993. \draw (x) to (w);
  4994. \draw (y) to (w);
  4995. \draw (v) to (w);
  4996. \draw (v) to (rsp);
  4997. \draw (w) to (rsp);
  4998. \draw (x) to (rsp);
  4999. \draw (y) to (rsp);
  5000. \path[-.,bend left=15] (z) edge node {} (rsp);
  5001. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5002. \draw (rax) to (rsp);
  5003. \end{tikzpicture}
  5004. \]
  5005. In the last step of the algorithm, we color \code{x} with $1$.
  5006. \[
  5007. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5008. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5009. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5010. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5011. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5012. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5013. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5014. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5015. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5016. \draw (t1) to (rax);
  5017. \draw (t1) to (z);
  5018. \draw (z) to (y);
  5019. \draw (z) to (w);
  5020. \draw (x) to (w);
  5021. \draw (y) to (w);
  5022. \draw (v) to (w);
  5023. \draw (v) to (rsp);
  5024. \draw (w) to (rsp);
  5025. \draw (x) to (rsp);
  5026. \draw (y) to (rsp);
  5027. \path[-.,bend left=15] (z) edge node {} (rsp);
  5028. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5029. \draw (rax) to (rsp);
  5030. \end{tikzpicture}
  5031. \]
  5032. So, we obtain the following coloring:
  5033. \[
  5034. \{
  5035. \ttm{rax} \mapsto -1,
  5036. \ttm{rsp} \mapsto -2,
  5037. \ttm{t} \mapsto 0,
  5038. \ttm{z} \mapsto 1,
  5039. \ttm{x} \mapsto 1,
  5040. \ttm{y} \mapsto 2,
  5041. \ttm{w} \mapsto 0,
  5042. \ttm{v} \mapsto 1
  5043. \}
  5044. \]
  5045. \fi}
  5046. %
  5047. {\if\edition\pythonEd
  5048. %
  5049. With the DSATUR algorithm in hand, let us return to the running
  5050. example and consider how to color the interference graph in
  5051. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5052. to indicate that it has not yet been assigned a color. The saturation
  5053. sets are also shown for each node; all of them start as the empty set.
  5054. (We do not include the register nodes in the graph below because there
  5055. were no interference edges involving registers in this program, but in
  5056. general there can be.)
  5057. %
  5058. \[
  5059. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5060. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5061. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5062. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5063. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5064. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5065. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5066. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5067. \draw (t0) to (t1);
  5068. \draw (t0) to (z);
  5069. \draw (z) to (y);
  5070. \draw (z) to (w);
  5071. \draw (x) to (w);
  5072. \draw (y) to (w);
  5073. \draw (v) to (w);
  5074. \end{tikzpicture}
  5075. \]
  5076. The algorithm says to select a maximally saturated vertex, but they
  5077. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5078. then color it with the first available integer, which is $0$. We mark
  5079. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5080. they interfere with $\ttm{tmp\_0}$.
  5081. \[
  5082. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5083. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5084. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5085. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5086. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5087. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5088. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5089. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5090. \draw (t0) to (t1);
  5091. \draw (t0) to (z);
  5092. \draw (z) to (y);
  5093. \draw (z) to (w);
  5094. \draw (x) to (w);
  5095. \draw (y) to (w);
  5096. \draw (v) to (w);
  5097. \end{tikzpicture}
  5098. \]
  5099. We repeat the process. The most saturated vertices are \code{z} and
  5100. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5101. available number, which is $1$. We add $1$ to the saturation for the
  5102. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5103. \[
  5104. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5105. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5106. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5107. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5108. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5109. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5110. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5111. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5112. \draw (t0) to (t1);
  5113. \draw (t0) to (z);
  5114. \draw (z) to (y);
  5115. \draw (z) to (w);
  5116. \draw (x) to (w);
  5117. \draw (y) to (w);
  5118. \draw (v) to (w);
  5119. \end{tikzpicture}
  5120. \]
  5121. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5122. \code{y}. We color \code{w} with the first available color, which
  5123. is $0$.
  5124. \[
  5125. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5126. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5127. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5128. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5129. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5130. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5131. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5132. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5133. \draw (t0) to (t1);
  5134. \draw (t0) to (z);
  5135. \draw (z) to (y);
  5136. \draw (z) to (w);
  5137. \draw (x) to (w);
  5138. \draw (y) to (w);
  5139. \draw (v) to (w);
  5140. \end{tikzpicture}
  5141. \]
  5142. Now \code{y} is the most saturated, so we color it with $2$.
  5143. \[
  5144. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5145. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5146. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5147. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5148. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5149. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5150. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5151. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5152. \draw (t0) to (t1);
  5153. \draw (t0) to (z);
  5154. \draw (z) to (y);
  5155. \draw (z) to (w);
  5156. \draw (x) to (w);
  5157. \draw (y) to (w);
  5158. \draw (v) to (w);
  5159. \end{tikzpicture}
  5160. \]
  5161. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5162. We choose to color \code{v} with $1$.
  5163. \[
  5164. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5165. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5166. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5167. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5168. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5169. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5170. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5171. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5172. \draw (t0) to (t1);
  5173. \draw (t0) to (z);
  5174. \draw (z) to (y);
  5175. \draw (z) to (w);
  5176. \draw (x) to (w);
  5177. \draw (y) to (w);
  5178. \draw (v) to (w);
  5179. \end{tikzpicture}
  5180. \]
  5181. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5182. \[
  5183. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5184. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5185. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5186. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5187. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5188. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5189. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5190. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5191. \draw (t0) to (t1);
  5192. \draw (t0) to (z);
  5193. \draw (z) to (y);
  5194. \draw (z) to (w);
  5195. \draw (x) to (w);
  5196. \draw (y) to (w);
  5197. \draw (v) to (w);
  5198. \end{tikzpicture}
  5199. \]
  5200. So, we obtain the following coloring:
  5201. \[
  5202. \{ \ttm{tmp\_0} \mapsto 0,
  5203. \ttm{tmp\_1} \mapsto 1,
  5204. \ttm{z} \mapsto 1,
  5205. \ttm{x} \mapsto 1,
  5206. \ttm{y} \mapsto 2,
  5207. \ttm{w} \mapsto 0,
  5208. \ttm{v} \mapsto 1 \}
  5209. \]
  5210. \fi}
  5211. We recommend creating an auxiliary function named \code{color\_graph}
  5212. that takes an interference graph and a list of all the variables in
  5213. the program. This function should return a mapping of variables to
  5214. their colors (represented as natural numbers). By creating this helper
  5215. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5216. when we add support for functions.
  5217. To prioritize the processing of highly saturated nodes inside the
  5218. \code{color\_graph} function, we recommend using the priority queue
  5219. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5220. addition, you will need to maintain a mapping from variables to their
  5221. handles in the priority queue so that you can notify the priority
  5222. queue when their saturation changes.}
  5223. {\if\edition\racketEd
  5224. \begin{figure}[tp]
  5225. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5226. \small
  5227. \begin{tcolorbox}[title=Priority Queue]
  5228. A \emph{priority queue} is a collection of items in which the
  5229. removal of items is governed by priority. In a min queue,
  5230. lower priority items are removed first. An implementation is in
  5231. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5232. queue} \index{subject}{minimum priority queue}
  5233. \begin{description}
  5234. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5235. priority queue that uses the $\itm{cmp}$ predicate to determine
  5236. whether its first argument has lower or equal priority to its
  5237. second argument.
  5238. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5239. items in the queue.
  5240. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5241. the item into the queue and returns a handle for the item in the
  5242. queue.
  5243. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5244. the lowest priority.
  5245. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5246. notifies the queue that the priority has decreased for the item
  5247. associated with the given handle.
  5248. \end{description}
  5249. \end{tcolorbox}
  5250. %\end{wrapfigure}
  5251. \caption{The priority queue data structure.}
  5252. \label{fig:priority-queue}
  5253. \end{figure}
  5254. \fi}
  5255. With the coloring complete, we finalize the assignment of variables to
  5256. registers and stack locations. We map the first $k$ colors to the $k$
  5257. registers and the rest of the colors to stack locations. Suppose for
  5258. the moment that we have just one register to use for register
  5259. allocation, \key{rcx}. Then we have the following map from colors to
  5260. locations.
  5261. \[
  5262. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5263. \]
  5264. Composing this mapping with the coloring, we arrive at the following
  5265. assignment of variables to locations.
  5266. {\if\edition\racketEd
  5267. \begin{gather*}
  5268. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5269. \ttm{w} \mapsto \key{\%rcx}, \,
  5270. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5271. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5272. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5273. \ttm{t} \mapsto \key{\%rcx} \}
  5274. \end{gather*}
  5275. \fi}
  5276. {\if\edition\pythonEd
  5277. \begin{gather*}
  5278. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5279. \ttm{w} \mapsto \key{\%rcx}, \,
  5280. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5281. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5282. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5283. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5284. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5285. \end{gather*}
  5286. \fi}
  5287. Adapt the code from the \code{assign\_homes} pass
  5288. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  5289. assigned location. Applying this assignment to our running
  5290. example shown next, on the left, yields the program on the right.
  5291. % why frame size of 32? -JGS
  5292. \begin{center}
  5293. {\if\edition\racketEd
  5294. \begin{minipage}{0.3\textwidth}
  5295. \begin{lstlisting}
  5296. movq $1, v
  5297. movq $42, w
  5298. movq v, x
  5299. addq $7, x
  5300. movq x, y
  5301. movq x, z
  5302. addq w, z
  5303. movq y, t
  5304. negq t
  5305. movq z, %rax
  5306. addq t, %rax
  5307. jmp conclusion
  5308. \end{lstlisting}
  5309. \end{minipage}
  5310. $\Rightarrow\qquad$
  5311. \begin{minipage}{0.45\textwidth}
  5312. \begin{lstlisting}
  5313. movq $1, -8(%rbp)
  5314. movq $42, %rcx
  5315. movq -8(%rbp), -8(%rbp)
  5316. addq $7, -8(%rbp)
  5317. movq -8(%rbp), -16(%rbp)
  5318. movq -8(%rbp), -8(%rbp)
  5319. addq %rcx, -8(%rbp)
  5320. movq -16(%rbp), %rcx
  5321. negq %rcx
  5322. movq -8(%rbp), %rax
  5323. addq %rcx, %rax
  5324. jmp conclusion
  5325. \end{lstlisting}
  5326. \end{minipage}
  5327. \fi}
  5328. {\if\edition\pythonEd
  5329. \begin{minipage}{0.3\textwidth}
  5330. \begin{lstlisting}
  5331. movq $1, v
  5332. movq $42, w
  5333. movq v, x
  5334. addq $7, x
  5335. movq x, y
  5336. movq x, z
  5337. addq w, z
  5338. movq y, tmp_0
  5339. negq tmp_0
  5340. movq z, tmp_1
  5341. addq tmp_0, tmp_1
  5342. movq tmp_1, %rdi
  5343. callq print_int
  5344. \end{lstlisting}
  5345. \end{minipage}
  5346. $\Rightarrow\qquad$
  5347. \begin{minipage}{0.45\textwidth}
  5348. \begin{lstlisting}
  5349. movq $1, -8(%rbp)
  5350. movq $42, %rcx
  5351. movq -8(%rbp), -8(%rbp)
  5352. addq $7, -8(%rbp)
  5353. movq -8(%rbp), -16(%rbp)
  5354. movq -8(%rbp), -8(%rbp)
  5355. addq %rcx, -8(%rbp)
  5356. movq -16(%rbp), %rcx
  5357. negq %rcx
  5358. movq -8(%rbp), -8(%rbp)
  5359. addq %rcx, -8(%rbp)
  5360. movq -8(%rbp), %rdi
  5361. callq print_int
  5362. \end{lstlisting}
  5363. \end{minipage}
  5364. \fi}
  5365. \end{center}
  5366. \begin{exercise}\normalfont\normalsize
  5367. Implement the \code{allocate\_registers} pass.
  5368. Create five programs that exercise all aspects of the register
  5369. allocation algorithm, including spilling variables to the stack.
  5370. %
  5371. {\if\edition\racketEd
  5372. Replace \code{assign\_homes} in the list of \code{passes} in the
  5373. \code{run-tests.rkt} script with the three new passes:
  5374. \code{uncover\_live}, \code{build\_interference}, and
  5375. \code{allocate\_registers}.
  5376. Temporarily remove the call to \code{compiler-tests}.
  5377. Run the script to test the register allocator.
  5378. \fi}
  5379. %
  5380. {\if\edition\pythonEd
  5381. Run the \code{run-tests.py} script to to check whether the
  5382. output programs produce the same result as the input programs.
  5383. \fi}
  5384. \end{exercise}
  5385. \section{Patch Instructions}
  5386. \label{sec:patch-instructions}
  5387. The remaining step in the compilation to x86 is to ensure that the
  5388. instructions have at most one argument that is a memory access.
  5389. %
  5390. In the running example, the instruction \code{movq -8(\%rbp),
  5391. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  5392. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5393. then move \code{rax} into \code{-16(\%rbp)}.
  5394. %
  5395. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5396. problematic, but they can simply be deleted. In general, we recommend
  5397. deleting all the trivial moves whose source and destination are the
  5398. same location.
  5399. %
  5400. The following is the output of \code{patch\_instructions} on the
  5401. running example.
  5402. \begin{center}
  5403. {\if\edition\racketEd
  5404. \begin{minipage}{0.4\textwidth}
  5405. \begin{lstlisting}
  5406. movq $1, -8(%rbp)
  5407. movq $42, %rcx
  5408. movq -8(%rbp), -8(%rbp)
  5409. addq $7, -8(%rbp)
  5410. movq -8(%rbp), -16(%rbp)
  5411. movq -8(%rbp), -8(%rbp)
  5412. addq %rcx, -8(%rbp)
  5413. movq -16(%rbp), %rcx
  5414. negq %rcx
  5415. movq -8(%rbp), %rax
  5416. addq %rcx, %rax
  5417. jmp conclusion
  5418. \end{lstlisting}
  5419. \end{minipage}
  5420. $\Rightarrow\qquad$
  5421. \begin{minipage}{0.45\textwidth}
  5422. \begin{lstlisting}
  5423. movq $1, -8(%rbp)
  5424. movq $42, %rcx
  5425. addq $7, -8(%rbp)
  5426. movq -8(%rbp), %rax
  5427. movq %rax, -16(%rbp)
  5428. addq %rcx, -8(%rbp)
  5429. movq -16(%rbp), %rcx
  5430. negq %rcx
  5431. movq -8(%rbp), %rax
  5432. addq %rcx, %rax
  5433. jmp conclusion
  5434. \end{lstlisting}
  5435. \end{minipage}
  5436. \fi}
  5437. {\if\edition\pythonEd
  5438. \begin{minipage}{0.4\textwidth}
  5439. \begin{lstlisting}
  5440. movq $1, -8(%rbp)
  5441. movq $42, %rcx
  5442. movq -8(%rbp), -8(%rbp)
  5443. addq $7, -8(%rbp)
  5444. movq -8(%rbp), -16(%rbp)
  5445. movq -8(%rbp), -8(%rbp)
  5446. addq %rcx, -8(%rbp)
  5447. movq -16(%rbp), %rcx
  5448. negq %rcx
  5449. movq -8(%rbp), -8(%rbp)
  5450. addq %rcx, -8(%rbp)
  5451. movq -8(%rbp), %rdi
  5452. callq print_int
  5453. \end{lstlisting}
  5454. \end{minipage}
  5455. $\Rightarrow\qquad$
  5456. \begin{minipage}{0.45\textwidth}
  5457. \begin{lstlisting}
  5458. movq $1, -8(%rbp)
  5459. movq $42, %rcx
  5460. addq $7, -8(%rbp)
  5461. movq -8(%rbp), %rax
  5462. movq %rax, -16(%rbp)
  5463. addq %rcx, -8(%rbp)
  5464. movq -16(%rbp), %rcx
  5465. negq %rcx
  5466. addq %rcx, -8(%rbp)
  5467. movq -8(%rbp), %rdi
  5468. callq print_int
  5469. \end{lstlisting}
  5470. \end{minipage}
  5471. \fi}
  5472. \end{center}
  5473. \begin{exercise}\normalfont\normalsize
  5474. %
  5475. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5476. %
  5477. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5478. %in the \code{run-tests.rkt} script.
  5479. %
  5480. Run the script to test the \code{patch\_instructions} pass.
  5481. \end{exercise}
  5482. \section{Prelude and Conclusion}
  5483. \label{sec:print-x86-reg-alloc}
  5484. \index{subject}{calling conventions}
  5485. \index{subject}{prelude}\index{subject}{conclusion}
  5486. Recall that this pass generates the prelude and conclusion
  5487. instructions to satisfy the x86 calling conventions
  5488. (section~\ref{sec:calling-conventions}). With the addition of the
  5489. register allocator, the callee-saved registers used by the register
  5490. allocator must be saved in the prelude and restored in the conclusion.
  5491. In the \code{allocate\_registers} pass,
  5492. %
  5493. \racket{add an entry to the \itm{info}
  5494. of \code{X86Program} named \code{used\_callee}}
  5495. %
  5496. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5497. %
  5498. that stores the set of callee-saved registers that were assigned to
  5499. variables. The \code{prelude\_and\_conclusion} pass can then access
  5500. this information to decide which callee-saved registers need to be
  5501. saved and restored.
  5502. %
  5503. When calculating the amount to adjust the \code{rsp} in the prelude,
  5504. make sure to take into account the space used for saving the
  5505. callee-saved registers. Also, remember that the frame needs to be a
  5506. multiple of 16 bytes! We recommend using the following equation for
  5507. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5508. of spilled variables and $C$ be the number of callee-saved registers
  5509. that were allocated to variables. The $\itm{align}$ function rounds a
  5510. number up to the nearest 16 bytes.
  5511. \[
  5512. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5513. \]
  5514. The reason we subtract $8\itm{C}$ in this equation is that the
  5515. prelude uses \code{pushq} to save each of the callee-saved registers,
  5516. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5517. \racket{An overview of all the passes involved in register
  5518. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  5519. {\if\edition\racketEd
  5520. \begin{figure}[tbp]
  5521. \begin{tcolorbox}[colback=white]
  5522. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5523. \node (Lvar) at (0,2) {\large \LangVar{}};
  5524. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5525. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  5526. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  5527. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  5528. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  5529. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  5530. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  5531. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  5532. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  5533. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5534. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  5535. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5536. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  5537. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5538. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  5539. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  5540. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  5541. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  5542. \end{tikzpicture}
  5543. \end{tcolorbox}
  5544. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5545. \label{fig:reg-alloc-passes}
  5546. \end{figure}
  5547. \fi}
  5548. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5549. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  5550. use of registers and the stack, we limit the register allocator for
  5551. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5552. the prelude\index{subject}{prelude} of the \code{main} function, we
  5553. push \code{rbx} onto the stack because it is a callee-saved register
  5554. and it was assigned to a variable by the register allocator. We
  5555. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5556. reserve space for the one spilled variable. After that subtraction,
  5557. the \code{rsp} is aligned to 16 bytes.
  5558. Moving on to the program proper, we see how the registers were
  5559. allocated.
  5560. %
  5561. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5562. \code{rbx}, and variable \code{z} was assigned to \code{rcx}.}
  5563. %
  5564. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5565. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5566. were assigned to \code{rbx}.}
  5567. %
  5568. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5569. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5570. callee-save register \code{rbx} onto the stack. The spilled variables
  5571. must be placed lower on the stack than the saved callee-save
  5572. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5573. \code{-16(\%rbp)}.
  5574. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5575. done in the prelude. We move the stack pointer up by \code{8} bytes
  5576. (the room for spilled variables), then pop the old values of
  5577. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5578. \code{retq} to return control to the operating system.
  5579. \begin{figure}[tbp]
  5580. \begin{minipage}{0.55\textwidth}
  5581. \begin{tcolorbox}[colback=white]
  5582. % var_test_28.rkt
  5583. % (use-minimal-set-of-registers! #t)
  5584. % and only rbx rcx
  5585. % tmp 0 rbx
  5586. % z 1 rcx
  5587. % y 0 rbx
  5588. % w 2 16(%rbp)
  5589. % v 0 rbx
  5590. % x 0 rbx
  5591. {\if\edition\racketEd
  5592. \begin{lstlisting}
  5593. start:
  5594. movq $1, %rbx
  5595. movq $42, -16(%rbp)
  5596. addq $7, %rbx
  5597. movq %rbx, %rcx
  5598. addq -16(%rbp), %rcx
  5599. negq %rbx
  5600. movq %rcx, %rax
  5601. addq %rbx, %rax
  5602. jmp conclusion
  5603. .globl main
  5604. main:
  5605. pushq %rbp
  5606. movq %rsp, %rbp
  5607. pushq %rbx
  5608. subq $8, %rsp
  5609. jmp start
  5610. conclusion:
  5611. addq $8, %rsp
  5612. popq %rbx
  5613. popq %rbp
  5614. retq
  5615. \end{lstlisting}
  5616. \fi}
  5617. {\if\edition\pythonEd
  5618. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5619. \begin{lstlisting}
  5620. .globl main
  5621. main:
  5622. pushq %rbp
  5623. movq %rsp, %rbp
  5624. pushq %rbx
  5625. subq $8, %rsp
  5626. movq $1, %rcx
  5627. movq $42, %rbx
  5628. addq $7, %rcx
  5629. movq %rcx, -16(%rbp)
  5630. addq %rbx, -16(%rbp)
  5631. negq %rcx
  5632. movq -16(%rbp), %rbx
  5633. addq %rcx, %rbx
  5634. movq %rbx, %rdi
  5635. callq print_int
  5636. addq $8, %rsp
  5637. popq %rbx
  5638. popq %rbp
  5639. retq
  5640. \end{lstlisting}
  5641. \fi}
  5642. \end{tcolorbox}
  5643. \end{minipage}
  5644. \caption{The x86 output from the running example
  5645. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5646. and \code{rcx}.}
  5647. \label{fig:running-example-x86}
  5648. \end{figure}
  5649. \begin{exercise}\normalfont\normalsize
  5650. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5651. %
  5652. \racket{
  5653. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5654. list of passes and the call to \code{compiler-tests}.}
  5655. %
  5656. Run the script to test the complete compiler for \LangVar{} that
  5657. performs register allocation.
  5658. \end{exercise}
  5659. \section{Challenge: Move Biasing}
  5660. \label{sec:move-biasing}
  5661. \index{subject}{move biasing}
  5662. This section describes an enhancement to the register allocator,
  5663. called move biasing, for students who are looking for an extra
  5664. challenge.
  5665. {\if\edition\racketEd
  5666. To motivate the need for move biasing we return to the running example,
  5667. but this time we use all the general purpose registers. So, we have
  5668. the following mapping of color numbers to registers.
  5669. \[
  5670. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5671. \]
  5672. Using the same assignment of variables to color numbers that was
  5673. produced by the register allocator described in the last section, we
  5674. get the following program.
  5675. \begin{center}
  5676. \begin{minipage}{0.3\textwidth}
  5677. \begin{lstlisting}
  5678. movq $1, v
  5679. movq $42, w
  5680. movq v, x
  5681. addq $7, x
  5682. movq x, y
  5683. movq x, z
  5684. addq w, z
  5685. movq y, t
  5686. negq t
  5687. movq z, %rax
  5688. addq t, %rax
  5689. jmp conclusion
  5690. \end{lstlisting}
  5691. \end{minipage}
  5692. $\Rightarrow\qquad$
  5693. \begin{minipage}{0.45\textwidth}
  5694. \begin{lstlisting}
  5695. movq $1, %rdx
  5696. movq $42, %rcx
  5697. movq %rdx, %rdx
  5698. addq $7, %rdx
  5699. movq %rdx, %rsi
  5700. movq %rdx, %rdx
  5701. addq %rcx, %rdx
  5702. movq %rsi, %rcx
  5703. negq %rcx
  5704. movq %rdx, %rax
  5705. addq %rcx, %rax
  5706. jmp conclusion
  5707. \end{lstlisting}
  5708. \end{minipage}
  5709. \end{center}
  5710. In this output code there are two \key{movq} instructions that
  5711. can be removed because their source and target are the same. However,
  5712. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5713. register, we could instead remove three \key{movq} instructions. We
  5714. can accomplish this by taking into account which variables appear in
  5715. \key{movq} instructions with which other variables.
  5716. \fi}
  5717. {\if\edition\pythonEd
  5718. %
  5719. To motivate the need for move biasing we return to the running example
  5720. and recall that in section~\ref{sec:patch-instructions} we were able to
  5721. remove three trivial move instructions from the running
  5722. example. However, we could remove another trivial move if we were able
  5723. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5724. We say that two variables $p$ and $q$ are \emph{move
  5725. related}\index{subject}{move related} if they participate together in
  5726. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5727. \key{movq} $q$\key{,} $p$. In deciding which variable to color next,
  5728. if there are multiple variables with the same saturation, prefer
  5729. variables that can be assigned to a color that is the same as the
  5730. color of a move-related variable. Furthermore, when the register
  5731. allocator chooses a color for a variable, it should prefer a color
  5732. that has already been used for a move-related variable (assuming that
  5733. they do not interfere). Of course, this preference should not override
  5734. the preference for registers over stack locations. So, this preference
  5735. should be used as a tie breaker in choosing between registers and
  5736. in choosing between stack locations.
  5737. We recommend representing the move relationships in a graph, similarly
  5738. to how we represented interference. The following is the \emph{move
  5739. graph} for our running example.
  5740. {\if\edition\racketEd
  5741. \[
  5742. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5743. \node (rax) at (0,0) {$\ttm{rax}$};
  5744. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5745. \node (t) at (0,2) {$\ttm{t}$};
  5746. \node (z) at (3,2) {$\ttm{z}$};
  5747. \node (x) at (6,2) {$\ttm{x}$};
  5748. \node (y) at (3,0) {$\ttm{y}$};
  5749. \node (w) at (6,0) {$\ttm{w}$};
  5750. \node (v) at (9,0) {$\ttm{v}$};
  5751. \draw (v) to (x);
  5752. \draw (x) to (y);
  5753. \draw (x) to (z);
  5754. \draw (y) to (t);
  5755. \end{tikzpicture}
  5756. \]
  5757. \fi}
  5758. %
  5759. {\if\edition\pythonEd
  5760. \[
  5761. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5762. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5763. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5764. \node (z) at (3,2) {$\ttm{z}$};
  5765. \node (x) at (6,2) {$\ttm{x}$};
  5766. \node (y) at (3,0) {$\ttm{y}$};
  5767. \node (w) at (6,0) {$\ttm{w}$};
  5768. \node (v) at (9,0) {$\ttm{v}$};
  5769. \draw (y) to (t0);
  5770. \draw (z) to (x);
  5771. \draw (z) to (t1);
  5772. \draw (x) to (y);
  5773. \draw (x) to (v);
  5774. \end{tikzpicture}
  5775. \]
  5776. \fi}
  5777. {\if\edition\racketEd
  5778. Now we replay the graph coloring, pausing to see the coloring of
  5779. \code{y}. Recall the following configuration. The most saturated vertices
  5780. were \code{w} and \code{y}.
  5781. \[
  5782. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5783. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5784. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5785. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5786. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5787. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5788. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5789. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5790. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5791. \draw (t1) to (rax);
  5792. \draw (t1) to (z);
  5793. \draw (z) to (y);
  5794. \draw (z) to (w);
  5795. \draw (x) to (w);
  5796. \draw (y) to (w);
  5797. \draw (v) to (w);
  5798. \draw (v) to (rsp);
  5799. \draw (w) to (rsp);
  5800. \draw (x) to (rsp);
  5801. \draw (y) to (rsp);
  5802. \path[-.,bend left=15] (z) edge node {} (rsp);
  5803. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5804. \draw (rax) to (rsp);
  5805. \end{tikzpicture}
  5806. \]
  5807. %
  5808. The last time, we chose to color \code{w} with $0$. This time, we see
  5809. that \code{w} is not move-related to any vertex, but \code{y} is
  5810. move-related to \code{t}. So we choose to color \code{y} with $0$,
  5811. the same color as \code{t}.
  5812. \[
  5813. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5814. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5815. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5816. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5817. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5818. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5819. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5820. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5821. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5822. \draw (t1) to (rax);
  5823. \draw (t1) to (z);
  5824. \draw (z) to (y);
  5825. \draw (z) to (w);
  5826. \draw (x) to (w);
  5827. \draw (y) to (w);
  5828. \draw (v) to (w);
  5829. \draw (v) to (rsp);
  5830. \draw (w) to (rsp);
  5831. \draw (x) to (rsp);
  5832. \draw (y) to (rsp);
  5833. \path[-.,bend left=15] (z) edge node {} (rsp);
  5834. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5835. \draw (rax) to (rsp);
  5836. \end{tikzpicture}
  5837. \]
  5838. Now \code{w} is the most saturated, so we color it $2$.
  5839. \[
  5840. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5841. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5842. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5843. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5844. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5845. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5846. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5847. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5848. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5849. \draw (t1) to (rax);
  5850. \draw (t1) to (z);
  5851. \draw (z) to (y);
  5852. \draw (z) to (w);
  5853. \draw (x) to (w);
  5854. \draw (y) to (w);
  5855. \draw (v) to (w);
  5856. \draw (v) to (rsp);
  5857. \draw (w) to (rsp);
  5858. \draw (x) to (rsp);
  5859. \draw (y) to (rsp);
  5860. \path[-.,bend left=15] (z) edge node {} (rsp);
  5861. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5862. \draw (rax) to (rsp);
  5863. \end{tikzpicture}
  5864. \]
  5865. At this point, vertices \code{x} and \code{v} are most saturated, but
  5866. \code{x} is move related to \code{y} and \code{z}, so we color
  5867. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5868. \[
  5869. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5870. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5871. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5872. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5873. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5874. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5875. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5876. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5877. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5878. \draw (t1) to (rax);
  5879. \draw (t) to (z);
  5880. \draw (z) to (y);
  5881. \draw (z) to (w);
  5882. \draw (x) to (w);
  5883. \draw (y) to (w);
  5884. \draw (v) to (w);
  5885. \draw (v) to (rsp);
  5886. \draw (w) to (rsp);
  5887. \draw (x) to (rsp);
  5888. \draw (y) to (rsp);
  5889. \path[-.,bend left=15] (z) edge node {} (rsp);
  5890. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5891. \draw (rax) to (rsp);
  5892. \end{tikzpicture}
  5893. \]
  5894. \fi}
  5895. %
  5896. {\if\edition\pythonEd
  5897. Now we replay the graph coloring, pausing before the coloring of
  5898. \code{w}. Recall the following configuration. The most saturated vertices
  5899. were \code{tmp\_1}, \code{w}, and \code{y}.
  5900. \[
  5901. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5902. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5903. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5904. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5905. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5906. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5907. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5908. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5909. \draw (t0) to (t1);
  5910. \draw (t0) to (z);
  5911. \draw (z) to (y);
  5912. \draw (z) to (w);
  5913. \draw (x) to (w);
  5914. \draw (y) to (w);
  5915. \draw (v) to (w);
  5916. \end{tikzpicture}
  5917. \]
  5918. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5919. or \code{y}, but note that \code{w} is not move related to any
  5920. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5921. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5922. \code{y} and color it $0$, we can delete another move instruction.
  5923. \[
  5924. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5925. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5926. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5927. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5928. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5929. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5930. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5931. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5932. \draw (t0) to (t1);
  5933. \draw (t0) to (z);
  5934. \draw (z) to (y);
  5935. \draw (z) to (w);
  5936. \draw (x) to (w);
  5937. \draw (y) to (w);
  5938. \draw (v) to (w);
  5939. \end{tikzpicture}
  5940. \]
  5941. Now \code{w} is the most saturated, so we color it $2$.
  5942. \[
  5943. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5944. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5945. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5946. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5947. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5948. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5949. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5950. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5951. \draw (t0) to (t1);
  5952. \draw (t0) to (z);
  5953. \draw (z) to (y);
  5954. \draw (z) to (w);
  5955. \draw (x) to (w);
  5956. \draw (y) to (w);
  5957. \draw (v) to (w);
  5958. \end{tikzpicture}
  5959. \]
  5960. To finish the coloring, \code{x} and \code{v} get $0$ and
  5961. \code{tmp\_1} gets $1$.
  5962. \[
  5963. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5964. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5965. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5966. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5967. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5968. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5969. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5970. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5971. \draw (t0) to (t1);
  5972. \draw (t0) to (z);
  5973. \draw (z) to (y);
  5974. \draw (z) to (w);
  5975. \draw (x) to (w);
  5976. \draw (y) to (w);
  5977. \draw (v) to (w);
  5978. \end{tikzpicture}
  5979. \]
  5980. \fi}
  5981. So, we have the following assignment of variables to registers.
  5982. {\if\edition\racketEd
  5983. \begin{gather*}
  5984. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5985. \ttm{w} \mapsto \key{\%rsi}, \,
  5986. \ttm{x} \mapsto \key{\%rcx}, \,
  5987. \ttm{y} \mapsto \key{\%rcx}, \,
  5988. \ttm{z} \mapsto \key{\%rdx}, \,
  5989. \ttm{t} \mapsto \key{\%rcx} \}
  5990. \end{gather*}
  5991. \fi}
  5992. {\if\edition\pythonEd
  5993. \begin{gather*}
  5994. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5995. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5996. \ttm{x} \mapsto \key{\%rcx}, \,
  5997. \ttm{y} \mapsto \key{\%rcx}, \\
  5998. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5999. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6000. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6001. \end{gather*}
  6002. \fi}
  6003. %
  6004. We apply this register assignment to the running example shown next,
  6005. on the left, to obtain the code in the middle. The
  6006. \code{patch\_instructions} then deletes the trivial moves to obtain
  6007. the code on the right.
  6008. {\if\edition\racketEd
  6009. \begin{minipage}{0.25\textwidth}
  6010. \begin{lstlisting}
  6011. movq $1, v
  6012. movq $42, w
  6013. movq v, x
  6014. addq $7, x
  6015. movq x, y
  6016. movq x, z
  6017. addq w, z
  6018. movq y, t
  6019. negq t
  6020. movq z, %rax
  6021. addq t, %rax
  6022. jmp conclusion
  6023. \end{lstlisting}
  6024. \end{minipage}
  6025. $\Rightarrow\qquad$
  6026. \begin{minipage}{0.25\textwidth}
  6027. \begin{lstlisting}
  6028. movq $1, %rcx
  6029. movq $42, %rsi
  6030. movq %rcx, %rcx
  6031. addq $7, %rcx
  6032. movq %rcx, %rcx
  6033. movq %rcx, %rdx
  6034. addq %rsi, %rdx
  6035. movq %rcx, %rcx
  6036. negq %rcx
  6037. movq %rdx, %rax
  6038. addq %rcx, %rax
  6039. jmp conclusion
  6040. \end{lstlisting}
  6041. \end{minipage}
  6042. $\Rightarrow\qquad$
  6043. \begin{minipage}{0.25\textwidth}
  6044. \begin{lstlisting}
  6045. movq $1, %rcx
  6046. movq $42, %rsi
  6047. addq $7, %rcx
  6048. movq %rcx, %rdx
  6049. addq %rsi, %rdx
  6050. negq %rcx
  6051. movq %rdx, %rax
  6052. addq %rcx, %rax
  6053. jmp conclusion
  6054. \end{lstlisting}
  6055. \end{minipage}
  6056. \fi}
  6057. {\if\edition\pythonEd
  6058. \begin{minipage}{0.20\textwidth}
  6059. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6060. movq $1, v
  6061. movq $42, w
  6062. movq v, x
  6063. addq $7, x
  6064. movq x, y
  6065. movq x, z
  6066. addq w, z
  6067. movq y, tmp_0
  6068. negq tmp_0
  6069. movq z, tmp_1
  6070. addq tmp_0, tmp_1
  6071. movq tmp_1, %rdi
  6072. callq _print_int
  6073. \end{lstlisting}
  6074. \end{minipage}
  6075. ${\Rightarrow\qquad}$
  6076. \begin{minipage}{0.30\textwidth}
  6077. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6078. movq $1, %rcx
  6079. movq $42, -16(%rbp)
  6080. movq %rcx, %rcx
  6081. addq $7, %rcx
  6082. movq %rcx, %rcx
  6083. movq %rcx, -8(%rbp)
  6084. addq -16(%rbp), -8(%rbp)
  6085. movq %rcx, %rcx
  6086. negq %rcx
  6087. movq -8(%rbp), -8(%rbp)
  6088. addq %rcx, -8(%rbp)
  6089. movq -8(%rbp), %rdi
  6090. callq _print_int
  6091. \end{lstlisting}
  6092. \end{minipage}
  6093. ${\Rightarrow\qquad}$
  6094. \begin{minipage}{0.20\textwidth}
  6095. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6096. movq $1, %rcx
  6097. movq $42, -16(%rbp)
  6098. addq $7, %rcx
  6099. movq %rcx, -8(%rbp)
  6100. movq -16(%rbp), %rax
  6101. addq %rax, -8(%rbp)
  6102. negq %rcx
  6103. addq %rcx, -8(%rbp)
  6104. movq -8(%rbp), %rdi
  6105. callq print_int
  6106. \end{lstlisting}
  6107. \end{minipage}
  6108. \fi}
  6109. \begin{exercise}\normalfont\normalsize
  6110. Change your implementation of \code{allocate\_registers} to take move
  6111. biasing into account. Create two new tests that include at least one
  6112. opportunity for move biasing, and visually inspect the output x86
  6113. programs to make sure that your move biasing is working properly. Make
  6114. sure that your compiler still passes all the tests.
  6115. \end{exercise}
  6116. %To do: another neat challenge would be to do
  6117. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6118. %% \subsection{Output of the Running Example}
  6119. %% \label{sec:reg-alloc-output}
  6120. % challenge: prioritize variables based on execution frequencies
  6121. % and the number of uses of a variable
  6122. % challenge: enhance the coloring algorithm using Chaitin's
  6123. % approach of prioritizing high-degree variables
  6124. % by removing low-degree variables (coloring them later)
  6125. % from the interference graph
  6126. \section{Further Reading}
  6127. \label{sec:register-allocation-further-reading}
  6128. Early register allocation algorithms were developed for Fortran
  6129. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6130. of graph coloring began in the late 1970s and early 1980s with the
  6131. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6132. algorithm is based on the following observation of
  6133. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6134. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6135. $v$ removed is also $k$ colorable. To see why, suppose that the
  6136. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6137. different colors, but because there are fewer than $k$ neighbors, there
  6138. will be one or more colors left over to use for coloring $v$ in $G$.
  6139. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6140. less than $k$ from the graph and recursively colors the rest of the
  6141. graph. Upon returning from the recursion, it colors $v$ with one of
  6142. the available colors and returns. \citet{Chaitin:1982vn} augments
  6143. this algorithm to handle spilling as follows. If there are no vertices
  6144. of degree lower than $k$ then pick a vertex at random, spill it,
  6145. remove it from the graph, and proceed recursively to color the rest of
  6146. the graph.
  6147. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6148. move-related and that don't interfere with each other, in a process
  6149. called \emph{coalescing}. Although coalescing decreases the number of
  6150. moves, it can make the graph more difficult to
  6151. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6152. which two variables are merged only if they have fewer than $k$
  6153. neighbors of high degree. \citet{George:1996aa} observed that
  6154. conservative coalescing is sometimes too conservative and made it more
  6155. aggressive by iterating the coalescing with the removal of low-degree
  6156. vertices.
  6157. %
  6158. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6159. also proposed \emph{biased coloring}, in which a variable is assigned to
  6160. the same color as another move-related variable if possible, as
  6161. discussed in section~\ref{sec:move-biasing}.
  6162. %
  6163. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6164. performs coalescing, graph coloring, and spill code insertion until
  6165. all variables have been assigned a location.
  6166. \citet{Briggs:1994kx} observed that \citet{Chaitin:1982vn} sometimes
  6167. spilled variables that don't have to be: a high-degree variable can be
  6168. colorable if many of its neighbors are assigned the same color.
  6169. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6170. high-degree vertex is not immediately spilled. Instead the decision is
  6171. deferred until after the recursive call, at which point it is apparent
  6172. whether there is actually an available color or not. We observe that
  6173. this algorithm is equivalent to the smallest-last ordering
  6174. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6175. be registers and the rest to be stack locations.
  6176. %% biased coloring
  6177. Earlier editions of the compiler course at Indiana University
  6178. \citep{Dybvig:2010aa} were based on the algorithm of
  6179. \citet{Briggs:1994kx}.
  6180. The smallest-last ordering algorithm is one of many \emph{greedy}
  6181. coloring algorithms. A greedy coloring algorithm visits all the
  6182. vertices in a particular order and assigns each one the first
  6183. available color. An \emph{offline} greedy algorithm chooses the
  6184. ordering up front, prior to assigning colors. The algorithm of
  6185. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6186. ordering does not depend on the colors assigned. Other orderings are
  6187. possible. For example, \citet{Chow:1984ys} ordered variables according
  6188. to an estimate of runtime cost.
  6189. An \emph{online} greedy coloring algorithm uses information about the
  6190. current assignment of colors to influence the order in which the
  6191. remaining vertices are colored. The saturation-based algorithm
  6192. described in this chapter is one such algorithm. We choose to use
  6193. saturation-based coloring because it is fun to introduce graph
  6194. coloring via sudoku!
  6195. A register allocator may choose to map each variable to just one
  6196. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6197. variable to one or more locations. The latter can be achieved by
  6198. \emph{live range splitting}, where a variable is replaced by several
  6199. variables that each handle part of its live
  6200. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6201. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6202. %% replacement algorithm, bottom-up local
  6203. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6204. %% Cooper: top-down (priority bassed), bottom-up
  6205. %% top-down
  6206. %% order variables by priority (estimated cost)
  6207. %% caveat: split variables into two groups:
  6208. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6209. %% color the constrained ones first
  6210. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6211. %% cite J. Cocke for an algorithm that colors variables
  6212. %% in a high-degree first ordering
  6213. %Register Allocation via Usage Counts, Freiburghouse CACM
  6214. \citet{Palsberg:2007si} observed that many of the interference graphs
  6215. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6216. that is, every cycle with four or more edges has an edge that is not
  6217. part of the cycle but that connects two vertices on the cycle. Such
  6218. graphs can be optimally colored by the greedy algorithm with a vertex
  6219. ordering determined by maximum cardinality search.
  6220. In situations in which compile time is of utmost importance, such as
  6221. in just-in-time compilers, graph coloring algorithms can be too
  6222. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6223. be more appropriate.
  6224. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6225. \chapter{Booleans and Conditionals}
  6226. \label{ch:Lif}
  6227. \index{subject}{Boolean}
  6228. \index{subject}{control flow}
  6229. \index{subject}{conditional expression}
  6230. \setcounter{footnote}{0}
  6231. The \LangVar{} language has only a single kind of value, the
  6232. integers. In this chapter we add a second kind of value, the Booleans,
  6233. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  6234. the Boolean values \emph{true} and \emph{false} are written \TRUE{}
  6235. and \FALSE{}, respectively. The \LangIf{} language includes several
  6236. operations that involve Booleans (\key{and}, \key{not},
  6237. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6238. expression \python{and statement}. With the addition of \key{if},
  6239. programs can have nontrivial control flow which
  6240. %
  6241. \racket{impacts \code{explicate\_control} and liveness analysis}
  6242. %
  6243. \python{impacts liveness analysis and motivates a new pass named
  6244. \code{explicate\_control}}.
  6245. %
  6246. Also, because we now have two kinds of values, we need to handle
  6247. programs that apply an operation to the wrong kind of value, such as
  6248. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6249. There are two language design options for such situations. One option
  6250. is to signal an error and the other is to provide a wider
  6251. interpretation of the operation. \racket{The Racket
  6252. language}\python{Python} uses a mixture of these two options,
  6253. depending on the operation and the kind of value. For example, the
  6254. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6255. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6256. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6257. %
  6258. \racket{On the other hand, \code{(car 1)} results in a runtime error
  6259. in Racket because \code{car} expects a pair.}
  6260. %
  6261. \python{On the other hand, \code{1[0]} results in a runtime error
  6262. in Python because an ``\code{int} object is not subscriptable''.}
  6263. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6264. design choices as \racket{Racket}\python{Python}, except that much of the
  6265. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6266. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6267. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  6268. \python{MyPy} reports a compile-time error
  6269. %
  6270. \racket{because Racket expects the type of the argument to be of the form
  6271. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6272. %
  6273. \python{stating that a ``value of type \code{int} is not indexable''.}
  6274. The \LangIf{} language performs type checking during compilation just as
  6275. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  6276. the alternative choice, that is, a dynamically typed language like
  6277. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6278. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6279. restrictive, for example, rejecting \racket{\code{(not
  6280. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6281. fairly simple because the focus of this book is on compilation and not
  6282. type systems, about which there are already several excellent
  6283. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6284. This chapter is organized as follows. We begin by defining the syntax
  6285. and interpreter for the \LangIf{} language
  6286. (section~\ref{sec:lang-if}). We then introduce the idea of type
  6287. checking and define a type checker for \LangIf{}
  6288. (section~\ref{sec:type-check-Lif}).
  6289. %
  6290. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6291. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  6292. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  6293. %
  6294. The remaining sections of this chapter discuss how Booleans and
  6295. conditional control flow require changes to the existing compiler
  6296. passes and the addition of new ones. We introduce the \code{shrink}
  6297. pass to translate some operators into others, thereby reducing the
  6298. number of operators that need to be handled in later passes.
  6299. %
  6300. The main event of this chapter is the \code{explicate\_control} pass
  6301. that is responsible for translating \code{if}s into conditional
  6302. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  6303. %
  6304. Regarding register allocation, there is the interesting question of
  6305. how to handle conditional \code{goto}s during liveness analysis.
  6306. \section{The \LangIf{} Language}
  6307. \label{sec:lang-if}
  6308. Definitions of the concrete syntax and abstract syntax of the
  6309. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  6310. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  6311. includes all of \LangVar{} {(shown in gray)}, the Boolean literals
  6312. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression
  6313. %
  6314. \python{, and the \code{if} statement}. We expand the set of
  6315. operators to include
  6316. \begin{enumerate}
  6317. \item the logical operators \key{and}, \key{or}, and \key{not},
  6318. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6319. for comparing integers or Booleans for equality, and
  6320. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6321. comparing integers.
  6322. \end{enumerate}
  6323. \racket{We reorganize the abstract syntax for the primitive
  6324. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  6325. rule for all of them. This means that the grammar no longer checks
  6326. whether the arity of an operators matches the number of
  6327. arguments. That responsibility is moved to the type checker for
  6328. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  6329. \newcommand{\LifGrammarRacket}{
  6330. \begin{array}{lcl}
  6331. \Type &::=& \key{Boolean} \\
  6332. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6333. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6334. \Exp &::=& \itm{bool}
  6335. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6336. \MID (\key{not}\;\Exp) \\
  6337. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6338. \end{array}
  6339. }
  6340. \newcommand{\LifASTRacket}{
  6341. \begin{array}{lcl}
  6342. \Type &::=& \key{Boolean} \\
  6343. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6344. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6345. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6346. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6347. \end{array}
  6348. }
  6349. \newcommand{\LintOpAST}{
  6350. \begin{array}{rcl}
  6351. \Type &::=& \key{Integer} \\
  6352. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6353. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6354. \end{array}
  6355. }
  6356. \newcommand{\LifGrammarPython}{
  6357. \begin{array}{rcl}
  6358. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6359. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6360. \MID \key{not}~\Exp \\
  6361. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6362. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6363. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6364. \end{array}
  6365. }
  6366. \newcommand{\LifASTPython}{
  6367. \begin{array}{lcl}
  6368. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6369. \itm{unaryop} &::=& \code{Not()} \\
  6370. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6371. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6372. \Exp &::=& \BOOL{\itm{bool}}
  6373. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6374. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6375. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6376. \end{array}
  6377. }
  6378. \begin{figure}[tp]
  6379. \centering
  6380. \begin{tcolorbox}[colback=white]
  6381. {\if\edition\racketEd
  6382. \[
  6383. \begin{array}{l}
  6384. \gray{\LintGrammarRacket{}} \\ \hline
  6385. \gray{\LvarGrammarRacket{}} \\ \hline
  6386. \LifGrammarRacket{} \\
  6387. \begin{array}{lcl}
  6388. \LangIfM{} &::=& \Exp
  6389. \end{array}
  6390. \end{array}
  6391. \]
  6392. \fi}
  6393. {\if\edition\pythonEd
  6394. \[
  6395. \begin{array}{l}
  6396. \gray{\LintGrammarPython} \\ \hline
  6397. \gray{\LvarGrammarPython} \\ \hline
  6398. \LifGrammarPython \\
  6399. \begin{array}{rcl}
  6400. \LangIfM{} &::=& \Stmt^{*}
  6401. \end{array}
  6402. \end{array}
  6403. \]
  6404. \fi}
  6405. \end{tcolorbox}
  6406. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6407. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6408. \label{fig:Lif-concrete-syntax}
  6409. \end{figure}
  6410. \begin{figure}[tp]
  6411. %\begin{minipage}{0.66\textwidth}
  6412. \begin{tcolorbox}[colback=white]
  6413. \centering
  6414. {\if\edition\racketEd
  6415. \[
  6416. \begin{array}{l}
  6417. \gray{\LintOpAST} \\ \hline
  6418. \gray{\LvarASTRacket{}} \\ \hline
  6419. \LifASTRacket{} \\
  6420. \begin{array}{lcl}
  6421. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6422. \end{array}
  6423. \end{array}
  6424. \]
  6425. \fi}
  6426. {\if\edition\pythonEd
  6427. \[
  6428. \begin{array}{l}
  6429. \gray{\LintASTPython} \\ \hline
  6430. \gray{\LvarASTPython} \\ \hline
  6431. \LifASTPython \\
  6432. \begin{array}{lcl}
  6433. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6434. \end{array}
  6435. \end{array}
  6436. \]
  6437. \fi}
  6438. \end{tcolorbox}
  6439. %\end{minipage}
  6440. \index{subject}{True@\TRUE{}}\index{subject}{False@\FALSE{}}
  6441. \index{subject}{IfExp@\IFNAME{}}
  6442. \python{\index{subject}{IfStmt@\IFSTMTNAME{}}}
  6443. \index{subject}{and@\ANDNAME{}}
  6444. \index{subject}{or@\ORNAME{}}
  6445. \index{subject}{not@\NOTNAME{}}
  6446. \index{subject}{equal@\EQNAME{}}
  6447. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  6448. \racket{
  6449. \index{subject}{lessthan@\texttt{<}}
  6450. \index{subject}{lessthaneq@\texttt{<=}}
  6451. \index{subject}{greaterthan@\texttt{>}}
  6452. \index{subject}{greaterthaneq@\texttt{>=}}
  6453. }
  6454. \python{
  6455. \index{subject}{BoolOp@\texttt{BoolOp}}
  6456. \index{subject}{Compare@\texttt{Compare}}
  6457. \index{subject}{Lt@\texttt{Lt}}
  6458. \index{subject}{LtE@\texttt{LtE}}
  6459. \index{subject}{Gt@\texttt{Gt}}
  6460. \index{subject}{GtE@\texttt{GtE}}
  6461. }
  6462. \caption{The abstract syntax of \LangIf{}.}
  6463. \label{fig:Lif-syntax}
  6464. \end{figure}
  6465. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  6466. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  6467. (figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6468. evaluate to the corresponding Boolean values. The conditional
  6469. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$ and
  6470. then either evaluates $e_2$ or $e_3$, depending on whether $e_1$
  6471. produced \TRUE{} or \FALSE{}. The logical operations \code{and},
  6472. \code{or}, and \code{not} behave according to propositional logic. In
  6473. addition, the \code{and} and \code{or} operations perform
  6474. \emph{short-circuit evaluation}.
  6475. %
  6476. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6477. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6478. %
  6479. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6480. evaluated if $e_1$ evaluates to \TRUE{}.
  6481. \racket{With the increase in the number of primitive operations, the
  6482. interpreter would become repetitive without some care. We refactor
  6483. the case for \code{Prim}, moving the code that differs with each
  6484. operation into the \code{interp\_op} method shown in
  6485. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6486. \code{or} operations separately because of their short-circuiting
  6487. behavior.}
  6488. \begin{figure}[tbp]
  6489. \begin{tcolorbox}[colback=white]
  6490. {\if\edition\racketEd
  6491. \begin{lstlisting}
  6492. (define interp-Lif-class
  6493. (class interp-Lvar-class
  6494. (super-new)
  6495. (define/public (interp_op op) ...)
  6496. (define/override ((interp_exp env) e)
  6497. (define recur (interp_exp env))
  6498. (match e
  6499. [(Bool b) b]
  6500. [(If cnd thn els)
  6501. (match (recur cnd)
  6502. [#t (recur thn)]
  6503. [#f (recur els)])]
  6504. [(Prim 'and (list e1 e2))
  6505. (match (recur e1)
  6506. [#t (match (recur e2) [#t #t] [#f #f])]
  6507. [#f #f])]
  6508. [(Prim 'or (list e1 e2))
  6509. (define v1 (recur e1))
  6510. (match v1
  6511. [#t #t]
  6512. [#f (match (recur e2) [#t #t] [#f #f])])]
  6513. [(Prim op args)
  6514. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6515. [else ((super interp_exp env) e)]))
  6516. ))
  6517. (define (interp_Lif p)
  6518. (send (new interp-Lif-class) interp_program p))
  6519. \end{lstlisting}
  6520. \fi}
  6521. {\if\edition\pythonEd
  6522. \begin{lstlisting}
  6523. class InterpLif(InterpLvar):
  6524. def interp_exp(self, e, env):
  6525. match e:
  6526. case IfExp(test, body, orelse):
  6527. if self.interp_exp(test, env):
  6528. return self.interp_exp(body, env)
  6529. else:
  6530. return self.interp_exp(orelse, env)
  6531. case UnaryOp(Not(), v):
  6532. return not self.interp_exp(v, env)
  6533. case BoolOp(And(), values):
  6534. if self.interp_exp(values[0], env):
  6535. return self.interp_exp(values[1], env)
  6536. else:
  6537. return False
  6538. case BoolOp(Or(), values):
  6539. if self.interp_exp(values[0], env):
  6540. return True
  6541. else:
  6542. return self.interp_exp(values[1], env)
  6543. case Compare(left, [cmp], [right]):
  6544. l = self.interp_exp(left, env)
  6545. r = self.interp_exp(right, env)
  6546. return self.interp_cmp(cmp)(l, r)
  6547. case _:
  6548. return super().interp_exp(e, env)
  6549. def interp_stmts(self, ss, env):
  6550. if len(ss) == 0:
  6551. return
  6552. match ss[0]:
  6553. case If(test, body, orelse):
  6554. if self.interp_exp(test, env):
  6555. return self.interp_stmts(body + ss[1:], env)
  6556. else:
  6557. return self.interp_stmts(orelse + ss[1:], env)
  6558. case _:
  6559. return super().interp_stmts(ss, env)
  6560. ...
  6561. \end{lstlisting}
  6562. \fi}
  6563. \end{tcolorbox}
  6564. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6565. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6566. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6567. \label{fig:interp-Lif}
  6568. \end{figure}
  6569. {\if\edition\racketEd
  6570. \begin{figure}[tbp]
  6571. \begin{tcolorbox}[colback=white]
  6572. \begin{lstlisting}
  6573. (define/public (interp_op op)
  6574. (match op
  6575. ['+ fx+]
  6576. ['- fx-]
  6577. ['read read-fixnum]
  6578. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6579. ['eq? (lambda (v1 v2)
  6580. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6581. (and (boolean? v1) (boolean? v2))
  6582. (and (vector? v1) (vector? v2)))
  6583. (eq? v1 v2)]))]
  6584. ['< (lambda (v1 v2)
  6585. (cond [(and (fixnum? v1) (fixnum? v2))
  6586. (< v1 v2)]))]
  6587. ['<= (lambda (v1 v2)
  6588. (cond [(and (fixnum? v1) (fixnum? v2))
  6589. (<= v1 v2)]))]
  6590. ['> (lambda (v1 v2)
  6591. (cond [(and (fixnum? v1) (fixnum? v2))
  6592. (> v1 v2)]))]
  6593. ['>= (lambda (v1 v2)
  6594. (cond [(and (fixnum? v1) (fixnum? v2))
  6595. (>= v1 v2)]))]
  6596. [else (error 'interp_op "unknown operator")]))
  6597. \end{lstlisting}
  6598. \end{tcolorbox}
  6599. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6600. \label{fig:interp-op-Lif}
  6601. \end{figure}
  6602. \fi}
  6603. {\if\edition\pythonEd
  6604. \begin{figure}
  6605. \begin{tcolorbox}[colback=white]
  6606. \begin{lstlisting}
  6607. class InterpLif(InterpLvar):
  6608. ...
  6609. def interp_cmp(self, cmp):
  6610. match cmp:
  6611. case Lt():
  6612. return lambda x, y: x < y
  6613. case LtE():
  6614. return lambda x, y: x <= y
  6615. case Gt():
  6616. return lambda x, y: x > y
  6617. case GtE():
  6618. return lambda x, y: x >= y
  6619. case Eq():
  6620. return lambda x, y: x == y
  6621. case NotEq():
  6622. return lambda x, y: x != y
  6623. \end{lstlisting}
  6624. \end{tcolorbox}
  6625. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6626. \label{fig:interp-cmp-Lif}
  6627. \end{figure}
  6628. \fi}
  6629. \section{Type Checking \LangIf{} Programs}
  6630. \label{sec:type-check-Lif}
  6631. \index{subject}{type checking}
  6632. \index{subject}{semantic analysis}
  6633. It is helpful to think about type checking in two complementary
  6634. ways. A type checker predicts the type of value that will be produced
  6635. by each expression in the program. For \LangIf{}, we have just two types,
  6636. \INTTY{} and \BOOLTY{}. So, a type checker should predict that
  6637. {\if\edition\racketEd
  6638. \begin{lstlisting}
  6639. (+ 10 (- (+ 12 20)))
  6640. \end{lstlisting}
  6641. \fi}
  6642. {\if\edition\pythonEd
  6643. \begin{lstlisting}
  6644. 10 + -(12 + 20)
  6645. \end{lstlisting}
  6646. \fi}
  6647. \noindent produces a value of type \INTTY{}, whereas
  6648. {\if\edition\racketEd
  6649. \begin{lstlisting}
  6650. (and (not #f) #t)
  6651. \end{lstlisting}
  6652. \fi}
  6653. {\if\edition\pythonEd
  6654. \begin{lstlisting}
  6655. (not False) and True
  6656. \end{lstlisting}
  6657. \fi}
  6658. \noindent produces a value of type \BOOLTY{}.
  6659. A second way to think about type checking is that it enforces a set of
  6660. rules about which operators can be applied to which kinds of
  6661. values. For example, our type checker for \LangIf{} signals an error
  6662. for the following expression:
  6663. %
  6664. {\if\edition\racketEd
  6665. \begin{lstlisting}
  6666. (not (+ 10 (- (+ 12 20))))
  6667. \end{lstlisting}
  6668. \fi}
  6669. {\if\edition\pythonEd
  6670. \begin{lstlisting}
  6671. not (10 + -(12 + 20))
  6672. \end{lstlisting}
  6673. \fi}
  6674. \noindent The subexpression
  6675. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6676. \python{\code{(10 + -(12 + 20))}}
  6677. has type \INTTY{}, but the type checker enforces the rule that the
  6678. argument of \code{not} must be an expression of type \BOOLTY{}.
  6679. We implement type checking using classes and methods because they
  6680. provide the open recursion needed to reuse code as we extend the type
  6681. checker in subsequent chapters, analogous to the use of classes and methods
  6682. for the interpreters (section~\ref{sec:extensible-interp}).
  6683. We separate the type checker for the \LangVar{} subset into its own
  6684. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  6685. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  6686. from the type checker for \LangVar{}. These type checkers are in the
  6687. files
  6688. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6689. and
  6690. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6691. of the support code.
  6692. %
  6693. Each type checker is a structurally recursive function over the AST.
  6694. Given an input expression \code{e}, the type checker either signals an
  6695. error or returns \racket{an expression and} its type.
  6696. %
  6697. \racket{It returns an expression because there are situations in which
  6698. we want to change or update the expression.}
  6699. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  6700. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  6701. constant is \INTTY{}. To handle variables, the type checker uses the
  6702. environment \code{env} to map variables to types.
  6703. %
  6704. \racket{Consider the case for \key{let}. We type check the
  6705. initializing expression to obtain its type \key{T} and then
  6706. associate type \code{T} with the variable \code{x} in the
  6707. environment used to type check the body of the \key{let}. Thus,
  6708. when the type checker encounters a use of variable \code{x}, it can
  6709. find its type in the environment.}
  6710. %
  6711. \python{Consider the case for assignment. We type check the
  6712. initializing expression to obtain its type \key{t}. If the variable
  6713. \code{lhs.id} is already in the environment because there was a
  6714. prior assignment, we check that this initializer has the same type
  6715. as the prior one. If this is the first assignment to the variable,
  6716. we associate type \code{t} with the variable \code{lhs.id} in the
  6717. environment. Thus, when the type checker encounters a use of
  6718. variable \code{x}, it can find its type in the environment.}
  6719. %
  6720. \racket{Regarding primitive operators, we recursively analyze the
  6721. arguments and then invoke \code{type\_check\_op} to check whether
  6722. the argument types are allowed.}
  6723. %
  6724. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6725. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6726. \racket{Several auxiliary methods are used in the type checker. The
  6727. method \code{operator-types} defines a dictionary that maps the
  6728. operator names to their parameter and return types. The
  6729. \code{type-equal?} method determines whether two types are equal,
  6730. which for now simply dispatches to \code{equal?} (deep
  6731. equality). The \code{check-type-equal?} method triggers an error if
  6732. the two types are not equal. The \code{type-check-op} method looks
  6733. up the operator in the \code{operator-types} dictionary and then
  6734. checks whether the argument types are equal to the parameter types.
  6735. The result is the return type of the operator.}
  6736. %
  6737. \python{The auxiliary method \code{check\_type\_equal} triggers
  6738. an error if the two types are not equal.}
  6739. \begin{figure}[tbp]
  6740. \begin{tcolorbox}[colback=white]
  6741. {\if\edition\racketEd
  6742. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6743. (define type-check-Lvar-class
  6744. (class object%
  6745. (super-new)
  6746. (define/public (operator-types)
  6747. '((+ . ((Integer Integer) . Integer))
  6748. (- . ((Integer Integer) . Integer))
  6749. (read . (() . Integer))))
  6750. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6751. (define/public (check-type-equal? t1 t2 e)
  6752. (unless (type-equal? t1 t2)
  6753. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6754. (define/public (type-check-op op arg-types e)
  6755. (match (dict-ref (operator-types) op)
  6756. [`(,param-types . ,return-type)
  6757. (for ([at arg-types] [pt param-types])
  6758. (check-type-equal? at pt e))
  6759. return-type]
  6760. [else (error 'type-check-op "unrecognized ~a" op)]))
  6761. (define/public (type-check-exp env)
  6762. (lambda (e)
  6763. (match e
  6764. [(Int n) (values (Int n) 'Integer)]
  6765. [(Var x) (values (Var x) (dict-ref env x))]
  6766. [(Let x e body)
  6767. (define-values (e^ Te) ((type-check-exp env) e))
  6768. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6769. (values (Let x e^ b) Tb)]
  6770. [(Prim op es)
  6771. (define-values (new-es ts)
  6772. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6773. (values (Prim op new-es) (type-check-op op ts e))]
  6774. [else (error 'type-check-exp "couldn't match" e)])))
  6775. (define/public (type-check-program e)
  6776. (match e
  6777. [(Program info body)
  6778. (define-values (body^ Tb) ((type-check-exp '()) body))
  6779. (check-type-equal? Tb 'Integer body)
  6780. (Program info body^)]
  6781. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6782. ))
  6783. (define (type-check-Lvar p)
  6784. (send (new type-check-Lvar-class) type-check-program p))
  6785. \end{lstlisting}
  6786. \fi}
  6787. {\if\edition\pythonEd
  6788. \begin{lstlisting}[escapechar=`]
  6789. class TypeCheckLvar:
  6790. def check_type_equal(self, t1, t2, e):
  6791. if t1 != t2:
  6792. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6793. raise Exception(msg)
  6794. def type_check_exp(self, e, env):
  6795. match e:
  6796. case BinOp(left, (Add() | Sub()), right):
  6797. l = self.type_check_exp(left, env)
  6798. check_type_equal(l, int, left)
  6799. r = self.type_check_exp(right, env)
  6800. check_type_equal(r, int, right)
  6801. return int
  6802. case UnaryOp(USub(), v):
  6803. t = self.type_check_exp(v, env)
  6804. check_type_equal(t, int, v)
  6805. return int
  6806. case Name(id):
  6807. return env[id]
  6808. case Constant(value) if isinstance(value, int):
  6809. return int
  6810. case Call(Name('input_int'), []):
  6811. return int
  6812. def type_check_stmts(self, ss, env):
  6813. if len(ss) == 0:
  6814. return
  6815. match ss[0]:
  6816. case Assign([lhs], value):
  6817. t = self.type_check_exp(value, env)
  6818. if lhs.id in env:
  6819. check_type_equal(env[lhs.id], t, value)
  6820. else:
  6821. env[lhs.id] = t
  6822. return self.type_check_stmts(ss[1:], env)
  6823. case Expr(Call(Name('print'), [arg])):
  6824. t = self.type_check_exp(arg, env)
  6825. check_type_equal(t, int, arg)
  6826. return self.type_check_stmts(ss[1:], env)
  6827. case Expr(value):
  6828. self.type_check_exp(value, env)
  6829. return self.type_check_stmts(ss[1:], env)
  6830. def type_check_P(self, p):
  6831. match p:
  6832. case Module(body):
  6833. self.type_check_stmts(body, {})
  6834. \end{lstlisting}
  6835. \fi}
  6836. \end{tcolorbox}
  6837. \caption{Type checker for the \LangVar{} language.}
  6838. \label{fig:type-check-Lvar}
  6839. \end{figure}
  6840. \begin{figure}[tbp]
  6841. \begin{tcolorbox}[colback=white]
  6842. {\if\edition\racketEd
  6843. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6844. (define type-check-Lif-class
  6845. (class type-check-Lvar-class
  6846. (super-new)
  6847. (inherit check-type-equal?)
  6848. (define/override (operator-types)
  6849. (append '((and . ((Boolean Boolean) . Boolean))
  6850. (or . ((Boolean Boolean) . Boolean))
  6851. (< . ((Integer Integer) . Boolean))
  6852. (<= . ((Integer Integer) . Boolean))
  6853. (> . ((Integer Integer) . Boolean))
  6854. (>= . ((Integer Integer) . Boolean))
  6855. (not . ((Boolean) . Boolean)))
  6856. (super operator-types)))
  6857. (define/override (type-check-exp env)
  6858. (lambda (e)
  6859. (match e
  6860. [(Bool b) (values (Bool b) 'Boolean)]
  6861. [(Prim 'eq? (list e1 e2))
  6862. (define-values (e1^ T1) ((type-check-exp env) e1))
  6863. (define-values (e2^ T2) ((type-check-exp env) e2))
  6864. (check-type-equal? T1 T2 e)
  6865. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6866. [(If cnd thn els)
  6867. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6868. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6869. (define-values (els^ Te) ((type-check-exp env) els))
  6870. (check-type-equal? Tc 'Boolean e)
  6871. (check-type-equal? Tt Te e)
  6872. (values (If cnd^ thn^ els^) Te)]
  6873. [else ((super type-check-exp env) e)])))
  6874. ))
  6875. (define (type-check-Lif p)
  6876. (send (new type-check-Lif-class) type-check-program p))
  6877. \end{lstlisting}
  6878. \fi}
  6879. {\if\edition\pythonEd
  6880. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6881. class TypeCheckLif(TypeCheckLvar):
  6882. def type_check_exp(self, e, env):
  6883. match e:
  6884. case Constant(value) if isinstance(value, bool):
  6885. return bool
  6886. case BinOp(left, Sub(), right):
  6887. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6888. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6889. return int
  6890. case UnaryOp(Not(), v):
  6891. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6892. return bool
  6893. case BoolOp(op, values):
  6894. left = values[0] ; right = values[1]
  6895. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6896. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6897. return bool
  6898. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6899. or isinstance(cmp, NotEq):
  6900. l = self.type_check_exp(left, env)
  6901. r = self.type_check_exp(right, env)
  6902. check_type_equal(l, r, e)
  6903. return bool
  6904. case Compare(left, [cmp], [right]):
  6905. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6906. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6907. return bool
  6908. case IfExp(test, body, orelse):
  6909. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6910. b = self.type_check_exp(body, env)
  6911. o = self.type_check_exp(orelse, env)
  6912. check_type_equal(b, o, e)
  6913. return b
  6914. case _:
  6915. return super().type_check_exp(e, env)
  6916. def type_check_stmts(self, ss, env):
  6917. if len(ss) == 0:
  6918. return
  6919. match ss[0]:
  6920. case If(test, body, orelse):
  6921. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6922. b = self.type_check_stmts(body, env)
  6923. o = self.type_check_stmts(orelse, env)
  6924. check_type_equal(b, o, ss[0])
  6925. return self.type_check_stmts(ss[1:], env)
  6926. case _:
  6927. return super().type_check_stmts(ss, env)
  6928. \end{lstlisting}
  6929. \fi}
  6930. \end{tcolorbox}
  6931. \caption{Type checker for the \LangIf{} language.}
  6932. \label{fig:type-check-Lif}
  6933. \end{figure}
  6934. The definition of the type checker for \LangIf{} is shown in
  6935. figure~\ref{fig:type-check-Lif}.
  6936. %
  6937. The type of a Boolean constant is \BOOLTY{}.
  6938. %
  6939. \racket{The \code{operator-types} function adds dictionary entries for
  6940. the new operators.}
  6941. %
  6942. \python{Logical not requires its argument to be a \BOOLTY{} and
  6943. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6944. %
  6945. The equality operator requires the two arguments to have the same type,
  6946. and therefore we handle it separately from the other operators.
  6947. %
  6948. \python{The other comparisons (less-than, etc.) require their
  6949. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6950. %
  6951. The condition of an \code{if} must
  6952. be of \BOOLTY{} type, and the two branches must have the same type.
  6953. \begin{exercise}\normalfont\normalsize
  6954. Create ten new test programs in \LangIf{}. Half the programs should
  6955. have a type error. For those programs, create an empty file with the
  6956. same base name and with file extension \code{.tyerr}. For example, if
  6957. the test
  6958. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6959. is expected to error, then create
  6960. an empty file named \code{cond\_test\_14.tyerr}.
  6961. %
  6962. \racket{This indicates to \code{interp-tests} and
  6963. \code{compiler-tests} that a type error is expected. }
  6964. %
  6965. The other half of the test programs should not have type errors.
  6966. %
  6967. \racket{In the \code{run-tests.rkt} script, change the second argument
  6968. of \code{interp-tests} and \code{compiler-tests} to
  6969. \code{type-check-Lif}, which causes the type checker to run prior to
  6970. the compiler passes. Temporarily change the \code{passes} to an
  6971. empty list and run the script, thereby checking that the new test
  6972. programs either type check or do not, as intended.}
  6973. %
  6974. Run the test script to check that these test programs type check as
  6975. expected.
  6976. \end{exercise}
  6977. \clearpage
  6978. \section{The \LangCIf{} Intermediate Language}
  6979. \label{sec:Cif}
  6980. {\if\edition\racketEd
  6981. %
  6982. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6983. comparison operators to the \Exp{} nonterminal and the literals
  6984. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  6985. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6986. \Tail{} nonterminal. The condition of an \code{if} statement is a
  6987. comparison operation and the branches are \code{goto} statements,
  6988. making it straightforward to compile \code{if} statements to x86. The
  6989. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6990. expressions. A \code{goto} statement transfers control to the $\Tail$
  6991. expression corresponding to its label.
  6992. %
  6993. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6994. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  6995. defines its abstract syntax.
  6996. %
  6997. \fi}
  6998. %
  6999. {\if\edition\pythonEd
  7000. %
  7001. The output of \key{explicate\_control} is a language similar to the
  7002. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7003. \code{goto} statements, so we name it \LangCIf{}.
  7004. %
  7005. The \LangCIf{} language supports the same operators as \LangIf{} but
  7006. the arguments of operators are restricted to atomic expressions. The
  7007. \LangCIf{} language does not include \code{if} expressions but it does
  7008. include a restricted form of \code{if} statement. The condition must be
  7009. a comparison and the two branches may only contain \code{goto}
  7010. statements. These restrictions make it easier to translate \code{if}
  7011. statements to x86. The \LangCIf{} language also adds a \code{return}
  7012. statement to finish the program with a specified value.
  7013. %
  7014. The \key{CProgram} construct contains a dictionary mapping labels to
  7015. lists of statements that end with a \code{return} statement, a
  7016. \code{goto}, or a conditional \code{goto}.
  7017. %% Statement lists of this
  7018. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  7019. %% is a control transfer at the end and control only enters at the
  7020. %% beginning of the list, which is marked by the label.
  7021. %
  7022. A \code{goto} statement transfers control to the sequence of statements
  7023. associated with its label.
  7024. %
  7025. The concrete syntax for \LangCIf{} is defined in
  7026. figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  7027. in figure~\ref{fig:c1-syntax}.
  7028. %
  7029. \fi}
  7030. %
  7031. \newcommand{\CifGrammarRacket}{
  7032. \begin{array}{lcl}
  7033. \Atm &::=& \itm{bool} \\
  7034. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7035. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7036. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7037. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7038. \end{array}
  7039. }
  7040. \newcommand{\CifASTRacket}{
  7041. \begin{array}{lcl}
  7042. \Atm &::=& \BOOL{\itm{bool}} \\
  7043. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7044. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7045. \Tail &::= & \GOTO{\itm{label}} \\
  7046. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7047. \end{array}
  7048. }
  7049. \newcommand{\CifGrammarPython}{
  7050. \begin{array}{lcl}
  7051. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7052. \Exp &::= & \Atm \MID \CREAD{}
  7053. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  7054. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  7055. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7056. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  7057. &\MID& \CASSIGN{\Var}{\Exp}
  7058. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7059. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7060. \end{array}
  7061. }
  7062. \newcommand{\CifASTPython}{
  7063. \begin{array}{lcl}
  7064. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7065. \Exp &::= & \Atm \MID \READ{} \\
  7066. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  7067. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  7068. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7069. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7070. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  7071. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7072. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7073. \end{array}
  7074. }
  7075. \begin{figure}[tbp]
  7076. \begin{tcolorbox}[colback=white]
  7077. \small
  7078. {\if\edition\racketEd
  7079. \[
  7080. \begin{array}{l}
  7081. \gray{\CvarGrammarRacket} \\ \hline
  7082. \CifGrammarRacket \\
  7083. \begin{array}{lcl}
  7084. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7085. \end{array}
  7086. \end{array}
  7087. \]
  7088. \fi}
  7089. {\if\edition\pythonEd
  7090. \[
  7091. \begin{array}{l}
  7092. \CifGrammarPython \\
  7093. \begin{array}{lcl}
  7094. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  7095. \end{array}
  7096. \end{array}
  7097. \]
  7098. \fi}
  7099. \end{tcolorbox}
  7100. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7101. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7102. \label{fig:c1-concrete-syntax}
  7103. \end{figure}
  7104. \begin{figure}[tp]
  7105. \begin{tcolorbox}[colback=white]
  7106. \small
  7107. {\if\edition\racketEd
  7108. \[
  7109. \begin{array}{l}
  7110. \gray{\CvarASTRacket} \\ \hline
  7111. \CifASTRacket \\
  7112. \begin{array}{lcl}
  7113. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7114. \end{array}
  7115. \end{array}
  7116. \]
  7117. \fi}
  7118. {\if\edition\pythonEd
  7119. \[
  7120. \begin{array}{l}
  7121. \CifASTPython \\
  7122. \begin{array}{lcl}
  7123. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  7124. \end{array}
  7125. \end{array}
  7126. \]
  7127. \fi}
  7128. \end{tcolorbox}
  7129. \racket{
  7130. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7131. }
  7132. \index{subject}{Goto@\texttt{Goto}}
  7133. \index{subject}{Return@\texttt{Return}}
  7134. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7135. (figure~\ref{fig:c0-syntax})}.}
  7136. \label{fig:c1-syntax}
  7137. \end{figure}
  7138. \section{The \LangXIf{} Language}
  7139. \label{sec:x86-if}
  7140. \index{subject}{x86} To implement the new logical operations, the
  7141. comparison operations, and the \key{if} expression\python{ and
  7142. statement}, we delve further into the x86
  7143. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7144. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7145. subset of x86, which includes instructions for logical operations,
  7146. comparisons, and \racket{conditional} jumps.
  7147. %
  7148. \python{The abstract syntax for an \LangXIf{} program contains a
  7149. dictionary mapping labels to sequences of instructions, each of
  7150. which we refer to as a \emph{basic block}\index{subject}{basic
  7151. block}.}
  7152. One challenge is that x86 does not provide an instruction that
  7153. directly implements logical negation (\code{not} in \LangIf{} and
  7154. \LangCIf{}). However, the \code{xorq} instruction can be used to
  7155. encode \code{not}. The \key{xorq} instruction takes two arguments,
  7156. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  7157. bit of its arguments, and writes the results into its second argument.
  7158. Recall the following truth table for exclusive-or:
  7159. \begin{center}
  7160. \begin{tabular}{l|cc}
  7161. & 0 & 1 \\ \hline
  7162. 0 & 0 & 1 \\
  7163. 1 & 1 & 0
  7164. \end{tabular}
  7165. \end{center}
  7166. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7167. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7168. for the bit $1$, the result is the opposite of the second bit. Thus,
  7169. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7170. the first argument, as follows, where $\Arg$ is the translation of
  7171. $\Atm$ to x86:
  7172. \[
  7173. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7174. \qquad\Rightarrow\qquad
  7175. \begin{array}{l}
  7176. \key{movq}~ \Arg\key{,} \Var\\
  7177. \key{xorq}~ \key{\$1,} \Var
  7178. \end{array}
  7179. \]
  7180. \newcommand{\GrammarXIf}{
  7181. \begin{array}{lcl}
  7182. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7183. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7184. \Arg &::=& \key{\%}\itm{bytereg}\\
  7185. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7186. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7187. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7188. \MID \key{set}cc~\Arg
  7189. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7190. &\MID& \key{j}cc~\itm{label} \\
  7191. \end{array}
  7192. }
  7193. \begin{figure}[tp]
  7194. \begin{tcolorbox}[colback=white]
  7195. \[
  7196. \begin{array}{l}
  7197. \gray{\GrammarXInt} \\ \hline
  7198. \GrammarXIf \\
  7199. \begin{array}{lcl}
  7200. \LangXIfM{} &::= & \key{.globl main} \\
  7201. & & \key{main:} \; \Instr\ldots
  7202. \end{array}
  7203. \end{array}
  7204. \]
  7205. \end{tcolorbox}
  7206. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7207. \label{fig:x86-1-concrete}
  7208. \end{figure}
  7209. \newcommand{\ASTXIfRacket}{
  7210. \begin{array}{lcl}
  7211. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7212. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7213. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7214. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7215. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7216. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7217. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7218. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7219. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  7220. \end{array}
  7221. }
  7222. \begin{figure}[tp]
  7223. \begin{tcolorbox}[colback=white]
  7224. \small
  7225. {\if\edition\racketEd
  7226. \[\arraycolsep=3pt
  7227. \begin{array}{l}
  7228. \gray{\ASTXIntRacket} \\ \hline
  7229. \ASTXIfRacket \\
  7230. \begin{array}{lcl}
  7231. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  7232. \end{array}
  7233. \end{array}
  7234. \]
  7235. \fi}
  7236. %
  7237. {\if\edition\pythonEd
  7238. \[
  7239. \begin{array}{lcl}
  7240. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7241. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7242. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7243. \MID \BYTEREG{\itm{bytereg}} \\
  7244. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  7245. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7246. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7247. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7248. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7249. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7250. \MID \PUSHQ{\Arg}} \\
  7251. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7252. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7253. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7254. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7255. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7256. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7257. \Block &::= & \Instr^{+} \\
  7258. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7259. \end{array}
  7260. \]
  7261. \fi}
  7262. \end{tcolorbox}
  7263. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  7264. \label{fig:x86-1}
  7265. \end{figure}
  7266. Next we consider the x86 instructions that are relevant for compiling
  7267. the comparison operations. The \key{cmpq} instruction compares its two
  7268. arguments to determine whether one argument is less than, equal to, or
  7269. greater than the other argument. The \key{cmpq} instruction is unusual
  7270. regarding the order of its arguments and where the result is
  7271. placed. The argument order is backward: if you want to test whether
  7272. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7273. \key{cmpq} is placed in the special EFLAGS register. This register
  7274. cannot be accessed directly, but it can be queried by a number of
  7275. instructions, including the \key{set} instruction. The instruction
  7276. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  7277. depending on whether the contents of the EFLAGS register matches the
  7278. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7279. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7280. The \key{set} instruction has a quirk in that its destination argument
  7281. must be single-byte register, such as \code{al} (\code{l} for lower bits) or
  7282. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  7283. register. Thankfully, the \key{movzbq} instruction can be used to
  7284. move from a single-byte register to a normal 64-bit register. The
  7285. abstract syntax for the \code{set} instruction differs from the
  7286. concrete syntax in that it separates the instruction name from the
  7287. condition code.
  7288. \python{The x86 instructions for jumping are relevant to the
  7289. compilation of \key{if} expressions.}
  7290. %
  7291. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7292. counter to the address of the instruction after the specified
  7293. label.}
  7294. %
  7295. \racket{The x86 instruction for conditional jump is relevant to the
  7296. compilation of \key{if} expressions.}
  7297. %
  7298. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7299. counter to point to the instruction after \itm{label}, depending on
  7300. whether the result in the EFLAGS register matches the condition code
  7301. \itm{cc}; otherwise, the jump instruction falls through to the next
  7302. instruction. Like the abstract syntax for \code{set}, the abstract
  7303. syntax for conditional jump separates the instruction name from the
  7304. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7305. corresponds to \code{jle foo}. Because the conditional jump instruction
  7306. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7307. a \key{cmpq} instruction to set the EFLAGS register.
  7308. \section{Shrink the \LangIf{} Language}
  7309. \label{sec:shrink-Lif}
  7310. The \LangIf{} language includes several features that are easily
  7311. expressible with other features. For example, \code{and} and \code{or}
  7312. are expressible using \code{if} as follows.
  7313. \begin{align*}
  7314. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7315. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7316. \end{align*}
  7317. By performing these translations in the front end of the compiler,
  7318. subsequent passes of the compiler do not need to deal with these features,
  7319. thus making the passes shorter.
  7320. On the other hand, translations sometimes reduce the efficiency of the
  7321. generated code by increasing the number of instructions. For example,
  7322. expressing subtraction in terms of negation
  7323. \[
  7324. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7325. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7326. \]
  7327. produces code with two x86 instructions (\code{negq} and \code{addq})
  7328. instead of just one (\code{subq}).
  7329. \begin{exercise}\normalfont\normalsize
  7330. %
  7331. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7332. the language by translating them to \code{if} expressions in \LangIf{}.
  7333. %
  7334. Create four test programs that involve these operators.
  7335. %
  7336. {\if\edition\racketEd
  7337. In the \code{run-tests.rkt} script, add the following entry for
  7338. \code{shrink} to the list of passes (it should be the only pass at
  7339. this point).
  7340. \begin{lstlisting}
  7341. (list "shrink" shrink interp_Lif type-check-Lif)
  7342. \end{lstlisting}
  7343. This instructs \code{interp-tests} to run the interpreter
  7344. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7345. output of \code{shrink}.
  7346. \fi}
  7347. %
  7348. Run the script to test your compiler on all the test programs.
  7349. \end{exercise}
  7350. {\if\edition\racketEd
  7351. \section{Uniquify Variables}
  7352. \label{sec:uniquify-Lif}
  7353. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7354. \code{if} expressions.
  7355. \begin{exercise}\normalfont\normalsize
  7356. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7357. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  7358. \begin{lstlisting}
  7359. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7360. \end{lstlisting}
  7361. Run the script to test your compiler.
  7362. \end{exercise}
  7363. \fi}
  7364. \section{Remove Complex Operands}
  7365. \label{sec:remove-complex-opera-Lif}
  7366. The output language of \code{remove\_complex\_operands} is
  7367. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  7368. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  7369. but the \code{if} expression is not. All three subexpressions of an
  7370. \code{if} are allowed to be complex expressions, but the operands of
  7371. the \code{not} operator and comparison operators must be atomic.
  7372. %
  7373. \python{We add a new language form, the \code{Begin} expression, to aid
  7374. in the translation of \code{if} expressions. When we recursively
  7375. process the two branches of the \code{if}, we generate temporary
  7376. variables and their initializing expressions. However, these
  7377. expressions may contain side effects and should only be executed
  7378. when the condition of the \code{if} is true (for the ``then''
  7379. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7380. a way to initialize the temporary variables within the two branches
  7381. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7382. form execute the statements $ss$ and then returns the result of
  7383. expression $e$.}
  7384. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7385. the new features in \LangIf{}. In recursively processing
  7386. subexpressions, recall that you should invoke \code{rco\_atom} when
  7387. the output needs to be an \Atm{} (as specified in the grammar for
  7388. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7389. \Exp{}. Regarding \code{if}, it is particularly important
  7390. \textbf{not} to replace its condition with a temporary variable, because
  7391. that would interfere with the generation of high-quality output in the
  7392. upcoming \code{explicate\_control} pass.
  7393. \newcommand{\LifMonadASTRacket}{
  7394. \begin{array}{rcl}
  7395. \Atm &::=& \BOOL{\itm{bool}}\\
  7396. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7397. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7398. \MID \IF{\Exp}{\Exp}{\Exp}
  7399. \end{array}
  7400. }
  7401. \newcommand{\LifMonadASTPython}{
  7402. \begin{array}{rcl}
  7403. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7404. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7405. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7406. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7407. \Atm &::=& \BOOL{\itm{bool}}\\
  7408. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7409. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7410. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7411. \end{array}
  7412. }
  7413. \begin{figure}[tp]
  7414. \centering
  7415. \begin{tcolorbox}[colback=white]
  7416. {\if\edition\racketEd
  7417. \[
  7418. \begin{array}{l}
  7419. \gray{\LvarMonadASTRacket} \\ \hline
  7420. \LifMonadASTRacket \\
  7421. \begin{array}{rcl}
  7422. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7423. \end{array}
  7424. \end{array}
  7425. \]
  7426. \fi}
  7427. {\if\edition\pythonEd
  7428. \[
  7429. \begin{array}{l}
  7430. \gray{\LvarMonadASTPython} \\ \hline
  7431. \LifMonadASTPython \\
  7432. \begin{array}{rcl}
  7433. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7434. \end{array}
  7435. \end{array}
  7436. \]
  7437. \fi}
  7438. \end{tcolorbox}
  7439. \python{\index{subject}{Begin@\texttt{Begin}}}
  7440. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7441. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  7442. \label{fig:Lif-anf-syntax}
  7443. \end{figure}
  7444. \begin{exercise}\normalfont\normalsize
  7445. %
  7446. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7447. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7448. %
  7449. Create three new \LangIf{} programs that exercise the interesting
  7450. code in this pass.
  7451. %
  7452. {\if\edition\racketEd
  7453. In the \code{run-tests.rkt} script, add the following entry to the
  7454. list of \code{passes} and then run the script to test your compiler.
  7455. \begin{lstlisting}
  7456. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7457. \end{lstlisting}
  7458. \fi}
  7459. \end{exercise}
  7460. \section{Explicate Control}
  7461. \label{sec:explicate-control-Lif}
  7462. \racket{Recall that the purpose of \code{explicate\_control} is to
  7463. make the order of evaluation explicit in the syntax of the program.
  7464. With the addition of \key{if}, this becomes more interesting.}
  7465. %
  7466. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7467. %
  7468. The main challenge to overcome is that the condition of an \key{if}
  7469. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  7470. condition must be a comparison.
  7471. As a motivating example, consider the following program that has an
  7472. \key{if} expression nested in the condition of another \key{if}:%
  7473. \python{\footnote{Programmers rarely write nested \code{if}
  7474. expressions, but it is not uncommon for the condition of an
  7475. \code{if} statement to be a call of a function that also contains an
  7476. \code{if} statement. When such a function is inlined, the result is
  7477. a nested \code{if} that requires the techniques discussed in this
  7478. section.}}
  7479. % cond_test_41.rkt, if_lt_eq.py
  7480. \begin{center}
  7481. \begin{minipage}{0.96\textwidth}
  7482. {\if\edition\racketEd
  7483. \begin{lstlisting}
  7484. (let ([x (read)])
  7485. (let ([y (read)])
  7486. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7487. (+ y 2)
  7488. (+ y 10))))
  7489. \end{lstlisting}
  7490. \fi}
  7491. {\if\edition\pythonEd
  7492. \begin{lstlisting}
  7493. x = input_int()
  7494. y = input_int()
  7495. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7496. \end{lstlisting}
  7497. \fi}
  7498. \end{minipage}
  7499. \end{center}
  7500. %
  7501. The naive way to compile \key{if} and the comparison operations would
  7502. be to handle each of them in isolation, regardless of their context.
  7503. Each comparison would be translated into a \key{cmpq} instruction
  7504. followed by several instructions to move the result from the EFLAGS
  7505. register into a general purpose register or stack location. Each
  7506. \key{if} would be translated into a \key{cmpq} instruction followed by
  7507. a conditional jump. The generated code for the inner \key{if} in this
  7508. example would be as follows:
  7509. \begin{center}
  7510. \begin{minipage}{0.96\textwidth}
  7511. \begin{lstlisting}
  7512. cmpq $1, x
  7513. setl %al
  7514. movzbq %al, tmp
  7515. cmpq $1, tmp
  7516. je then_branch_1
  7517. jmp else_branch_1
  7518. \end{lstlisting}
  7519. \end{minipage}
  7520. \end{center}
  7521. Notice that the three instructions starting with \code{setl} are
  7522. redundant: the conditional jump could come immediately after the first
  7523. \code{cmpq}.
  7524. Our goal is to compile \key{if} expressions so that the relevant
  7525. comparison instruction appears directly before the conditional jump.
  7526. For example, we want to generate the following code for the inner
  7527. \code{if}:
  7528. \begin{center}
  7529. \begin{minipage}{0.96\textwidth}
  7530. \begin{lstlisting}
  7531. cmpq $1, x
  7532. jl then_branch_1
  7533. jmp else_branch_1
  7534. \end{lstlisting}
  7535. \end{minipage}
  7536. \end{center}
  7537. One way to achieve this goal is to reorganize the code at the level of
  7538. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7539. the following code:
  7540. \begin{center}
  7541. \begin{minipage}{0.96\textwidth}
  7542. {\if\edition\racketEd
  7543. \begin{lstlisting}
  7544. (let ([x (read)])
  7545. (let ([y (read)])
  7546. (if (< x 1)
  7547. (if (eq? x 0)
  7548. (+ y 2)
  7549. (+ y 10))
  7550. (if (eq? x 2)
  7551. (+ y 2)
  7552. (+ y 10)))))
  7553. \end{lstlisting}
  7554. \fi}
  7555. {\if\edition\pythonEd
  7556. \begin{lstlisting}
  7557. x = input_int()
  7558. y = input_int()
  7559. print(((y + 2) if x == 0 else (y + 10)) \
  7560. if (x < 1) \
  7561. else ((y + 2) if (x == 2) else (y + 10)))
  7562. \end{lstlisting}
  7563. \fi}
  7564. \end{minipage}
  7565. \end{center}
  7566. Unfortunately, this approach duplicates the two branches from the
  7567. outer \code{if}, and a compiler must never duplicate code! After all,
  7568. the two branches could be very large expressions.
  7569. How can we apply this transformation without duplicating code? In
  7570. other words, how can two different parts of a program refer to one
  7571. piece of code?
  7572. %
  7573. The answer is that we must move away from abstract syntax \emph{trees}
  7574. and instead use \emph{graphs}.
  7575. %
  7576. At the level of x86 assembly, this is straightforward because we can
  7577. label the code for each branch and insert jumps in all the places that
  7578. need to execute the branch. In this way, jump instructions are edges
  7579. in the graph and the basic blocks are the nodes.
  7580. %
  7581. Likewise, our language \LangCIf{} provides the ability to label a
  7582. sequence of statements and to jump to a label via \code{goto}.
  7583. As a preview of what \code{explicate\_control} will do,
  7584. figure~\ref{fig:explicate-control-s1-38} shows the output of
  7585. \code{explicate\_control} on this example. Note how the condition of
  7586. every \code{if} is a comparison operation and that we have not
  7587. duplicated any code but instead have used labels and \code{goto} to
  7588. enable sharing of code.
  7589. \begin{figure}[tbp]
  7590. \begin{tcolorbox}[colback=white]
  7591. {\if\edition\racketEd
  7592. \begin{tabular}{lll}
  7593. \begin{minipage}{0.4\textwidth}
  7594. % cond_test_41.rkt
  7595. \begin{lstlisting}
  7596. (let ([x (read)])
  7597. (let ([y (read)])
  7598. (if (if (< x 1)
  7599. (eq? x 0)
  7600. (eq? x 2))
  7601. (+ y 2)
  7602. (+ y 10))))
  7603. \end{lstlisting}
  7604. \end{minipage}
  7605. &
  7606. $\Rightarrow$
  7607. &
  7608. \begin{minipage}{0.55\textwidth}
  7609. \begin{lstlisting}
  7610. start:
  7611. x = (read);
  7612. y = (read);
  7613. if (< x 1)
  7614. goto block_4;
  7615. else
  7616. goto block_5;
  7617. block_4:
  7618. if (eq? x 0)
  7619. goto block_2;
  7620. else
  7621. goto block_3;
  7622. block_5:
  7623. if (eq? x 2)
  7624. goto block_2;
  7625. else
  7626. goto block_3;
  7627. block_2:
  7628. return (+ y 2);
  7629. block_3:
  7630. return (+ y 10);
  7631. \end{lstlisting}
  7632. \end{minipage}
  7633. \end{tabular}
  7634. \fi}
  7635. {\if\edition\pythonEd
  7636. \begin{tabular}{lll}
  7637. \begin{minipage}{0.4\textwidth}
  7638. % cond_test_41.rkt
  7639. \begin{lstlisting}
  7640. x = input_int()
  7641. y = input_int()
  7642. print(y + 2 \
  7643. if (x == 0 \
  7644. if x < 1 \
  7645. else x == 2) \
  7646. else y + 10)
  7647. \end{lstlisting}
  7648. \end{minipage}
  7649. &
  7650. $\Rightarrow$
  7651. &
  7652. \begin{minipage}{0.55\textwidth}
  7653. \begin{lstlisting}
  7654. start:
  7655. x = input_int()
  7656. y = input_int()
  7657. if x < 1:
  7658. goto block_8
  7659. else:
  7660. goto block_9
  7661. block_8:
  7662. if x == 0:
  7663. goto block_4
  7664. else:
  7665. goto block_5
  7666. block_9:
  7667. if x == 2:
  7668. goto block_6
  7669. else:
  7670. goto block_7
  7671. block_4:
  7672. goto block_2
  7673. block_5:
  7674. goto block_3
  7675. block_6:
  7676. goto block_2
  7677. block_7:
  7678. goto block_3
  7679. block_2:
  7680. tmp_0 = y + 2
  7681. goto block_1
  7682. block_3:
  7683. tmp_0 = y + 10
  7684. goto block_1
  7685. block_1:
  7686. print(tmp_0)
  7687. return 0
  7688. \end{lstlisting}
  7689. \end{minipage}
  7690. \end{tabular}
  7691. \fi}
  7692. \end{tcolorbox}
  7693. \caption{Translation from \LangIf{} to \LangCIf{}
  7694. via the \code{explicate\_control}.}
  7695. \label{fig:explicate-control-s1-38}
  7696. \end{figure}
  7697. {\if\edition\racketEd
  7698. %
  7699. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  7700. \code{explicate\_control} for \LangVar{} using two recursive
  7701. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7702. former function translates expressions in tail position, whereas the
  7703. latter function translates expressions on the right-hand side of a
  7704. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7705. have a new kind of position to deal with: the predicate position of
  7706. the \key{if}. We need another function, \code{explicate\_pred}, that
  7707. decides how to compile an \key{if} by analyzing its condition. So,
  7708. \code{explicate\_pred} takes an \LangIf{} expression and two
  7709. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  7710. and outputs a tail. In the following paragraphs we discuss specific
  7711. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  7712. \code{explicate\_pred} functions.
  7713. %
  7714. \fi}
  7715. %
  7716. {\if\edition\pythonEd
  7717. %
  7718. We recommend implementing \code{explicate\_control} using the
  7719. following four auxiliary functions.
  7720. \begin{description}
  7721. \item[\code{explicate\_effect}] generates code for expressions as
  7722. statements, so their result is ignored and only their side effects
  7723. matter.
  7724. \item[\code{explicate\_assign}] generates code for expressions
  7725. on the right-hand side of an assignment.
  7726. \item[\code{explicate\_pred}] generates code for an \code{if}
  7727. expression or statement by analyzing the condition expression.
  7728. \item[\code{explicate\_stmt}] generates code for statements.
  7729. \end{description}
  7730. These four functions should build the dictionary of basic blocks. The
  7731. following auxiliary function can be used to create a new basic block
  7732. from a list of statements. It returns a \code{goto} statement that
  7733. jumps to the new basic block.
  7734. \begin{center}
  7735. \begin{minipage}{\textwidth}
  7736. \begin{lstlisting}
  7737. def create_block(stmts, basic_blocks):
  7738. label = label_name(generate_name('block'))
  7739. basic_blocks[label] = stmts
  7740. return Goto(label)
  7741. \end{lstlisting}
  7742. \end{minipage}
  7743. \end{center}
  7744. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7745. \code{explicate\_control} pass.
  7746. The \code{explicate\_effect} function has three parameters: 1) the
  7747. expression to be compiled, 2) the already-compiled code for this
  7748. expression's \emph{continuation}, that is, the list of statements that
  7749. should execute after this expression, and 3) the dictionary of
  7750. generated basic blocks. The \code{explicate\_effect} function returns
  7751. a list of \LangCIf{} statements and it may add to the dictionary of
  7752. basic blocks.
  7753. %
  7754. Let's consider a few of the cases for the expression to be compiled.
  7755. If the expression to be compiled is a constant, then it can be
  7756. discarded because it has no side effects. If it's a \CREAD{}, then it
  7757. has a side-effect and should be preserved. So the expression should be
  7758. translated into a statement using the \code{Expr} AST class. If the
  7759. expression to be compiled is an \code{if} expression, we translate the
  7760. two branches using \code{explicate\_effect} and then translate the
  7761. condition expression using \code{explicate\_pred}, which generates
  7762. code for the entire \code{if}.
  7763. The \code{explicate\_assign} function has four parameters: 1) the
  7764. right-hand side of the assignment, 2) the left-hand side of the
  7765. assignment (the variable), 3) the continuation, and 4) the dictionary
  7766. of basic blocks. The \code{explicate\_assign} function returns a list
  7767. of \LangCIf{} statements and it may add to the dictionary of basic
  7768. blocks.
  7769. When the right-hand side is an \code{if} expression, there is some
  7770. work to do. In particular, the two branches should be translated using
  7771. \code{explicate\_assign} and the condition expression should be
  7772. translated using \code{explicate\_pred}. Otherwise we can simply
  7773. generate an assignment statement, with the given left and right-hand
  7774. sides, concatenated with its continuation.
  7775. \begin{figure}[tbp]
  7776. \begin{tcolorbox}[colback=white]
  7777. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7778. def explicate_effect(e, cont, basic_blocks):
  7779. match e:
  7780. case IfExp(test, body, orelse):
  7781. ...
  7782. case Call(func, args):
  7783. ...
  7784. case Begin(body, result):
  7785. ...
  7786. case _:
  7787. ...
  7788. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7789. match rhs:
  7790. case IfExp(test, body, orelse):
  7791. ...
  7792. case Begin(body, result):
  7793. ...
  7794. case _:
  7795. return [Assign([lhs], rhs)] + cont
  7796. def explicate_pred(cnd, thn, els, basic_blocks):
  7797. match cnd:
  7798. case Compare(left, [op], [right]):
  7799. goto_thn = create_block(thn, basic_blocks)
  7800. goto_els = create_block(els, basic_blocks)
  7801. return [If(cnd, [goto_thn], [goto_els])]
  7802. case Constant(True):
  7803. return thn;
  7804. case Constant(False):
  7805. return els;
  7806. case UnaryOp(Not(), operand):
  7807. ...
  7808. case IfExp(test, body, orelse):
  7809. ...
  7810. case Begin(body, result):
  7811. ...
  7812. case _:
  7813. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7814. [create_block(els, basic_blocks)],
  7815. [create_block(thn, basic_blocks)])]
  7816. def explicate_stmt(s, cont, basic_blocks):
  7817. match s:
  7818. case Assign([lhs], rhs):
  7819. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7820. case Expr(value):
  7821. return explicate_effect(value, cont, basic_blocks)
  7822. case If(test, body, orelse):
  7823. ...
  7824. def explicate_control(p):
  7825. match p:
  7826. case Module(body):
  7827. new_body = [Return(Constant(0))]
  7828. basic_blocks = {}
  7829. for s in reversed(body):
  7830. new_body = explicate_stmt(s, new_body, basic_blocks)
  7831. basic_blocks[label_name('start')] = new_body
  7832. return CProgram(basic_blocks)
  7833. \end{lstlisting}
  7834. \end{tcolorbox}
  7835. \caption{Skeleton for the \code{explicate\_control} pass.}
  7836. \label{fig:explicate-control-Lif}
  7837. \end{figure}
  7838. \fi}
  7839. {\if\edition\racketEd
  7840. \subsection{Explicate Tail and Assign}
  7841. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7842. additional cases for Boolean constants and \key{if}. The cases for
  7843. \code{if} should recursively compile the two branches using either
  7844. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7845. cases should then invoke \code{explicate\_pred} on the condition
  7846. expression, passing in the generated code for the two branches. For
  7847. example, consider the following program with an \code{if} in tail
  7848. position.
  7849. % cond_test_6.rkt
  7850. \begin{lstlisting}
  7851. (let ([x (read)])
  7852. (if (eq? x 0) 42 777))
  7853. \end{lstlisting}
  7854. The two branches are recursively compiled to return statements. We
  7855. then delegate to \code{explicate\_pred}, passing the condition
  7856. \code{(eq? x 0)} and the two return statements. We return to this
  7857. example shortly when we discuss \code{explicate\_pred}.
  7858. Next let us consider a program with an \code{if} on the right-hand
  7859. side of a \code{let}.
  7860. \begin{lstlisting}
  7861. (let ([y (read)])
  7862. (let ([x (if (eq? y 0) 40 777)])
  7863. (+ x 2)))
  7864. \end{lstlisting}
  7865. Note that the body of the inner \code{let} will have already been
  7866. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7867. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7868. to recursively process both branches of the \code{if}, and we do not
  7869. want to duplicate code, so we generate the following block using an
  7870. auxiliary function named \code{create\_block}, discussed in the next
  7871. section.
  7872. \begin{lstlisting}
  7873. block_6:
  7874. return (+ x 2)
  7875. \end{lstlisting}
  7876. We then use \code{goto block\_6;} as the \code{cont} argument for
  7877. compiling the branches. So the two branches compile to
  7878. \begin{center}
  7879. \begin{minipage}{0.2\textwidth}
  7880. \begin{lstlisting}
  7881. x = 40;
  7882. goto block_6;
  7883. \end{lstlisting}
  7884. \end{minipage}
  7885. \hspace{0.5in} and \hspace{0.5in}
  7886. \begin{minipage}{0.2\textwidth}
  7887. \begin{lstlisting}
  7888. x = 777;
  7889. goto block_6;
  7890. \end{lstlisting}
  7891. \end{minipage}
  7892. \end{center}
  7893. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7894. \code{(eq? y 0)} and the previously presented code for the branches.
  7895. \subsection{Create Block}
  7896. We recommend implementing the \code{create\_block} auxiliary function
  7897. as follows, using a global variable \code{basic-blocks} to store a
  7898. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7899. that \code{create\_block} generates a new label and then associates
  7900. the given \code{tail} with the new label in the \code{basic-blocks}
  7901. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7902. new label. However, if the given \code{tail} is already a \code{Goto},
  7903. then there is no need to generate a new label and entry in
  7904. \code{basic-blocks}; we can simply return that \code{Goto}.
  7905. %
  7906. \begin{lstlisting}
  7907. (define (create_block tail)
  7908. (match tail
  7909. [(Goto label) (Goto label)]
  7910. [else
  7911. (let ([label (gensym 'block)])
  7912. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7913. (Goto label))]))
  7914. \end{lstlisting}
  7915. \fi}
  7916. {\if\edition\racketEd
  7917. \subsection{Explicate Predicate}
  7918. \begin{figure}[tbp]
  7919. \begin{tcolorbox}[colback=white]
  7920. \begin{lstlisting}
  7921. (define (explicate_pred cnd thn els)
  7922. (match cnd
  7923. [(Var x) ___]
  7924. [(Let x rhs body) ___]
  7925. [(Prim 'not (list e)) ___]
  7926. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7927. (IfStmt (Prim op es) (create_block thn)
  7928. (create_block els))]
  7929. [(Bool b) (if b thn els)]
  7930. [(If cnd^ thn^ els^) ___]
  7931. [else (error "explicate_pred unhandled case" cnd)]))
  7932. \end{lstlisting}
  7933. \end{tcolorbox}
  7934. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7935. \label{fig:explicate-pred}
  7936. \end{figure}
  7937. \fi}
  7938. \racket{The skeleton for the \code{explicate\_pred} function is given
  7939. in figure~\ref{fig:explicate-pred}. It takes three parameters:
  7940. (1) \code{cnd}, the condition expression of the \code{if};
  7941. (2) \code{thn}, the code generated by explicate for the \emph{then} branch;
  7942. and (3) \code{els}, the code generated by
  7943. explicate for the \emph{else} branch. The \code{explicate\_pred}
  7944. function should match on \code{cnd} with a case for
  7945. every kind of expression that can have type \BOOLTY{}.}
  7946. %
  7947. \python{The \code{explicate\_pred} function has four parameters: 1)
  7948. the condition expression, 2) the generated statements for the
  7949. ``then'' branch, 3) the generated statements for the ``else''
  7950. branch, and 4) the dictionary of basic blocks. The
  7951. \code{explicate\_pred} function returns a list of \LangCIf{}
  7952. statements and it may add to the dictionary of basic blocks.}
  7953. Consider the case for comparison operators. We translate the
  7954. comparison to an \code{if} statement whose branches are \code{goto}
  7955. statements created by applying \code{create\_block} to the code
  7956. generated for the \code{thn} and \code{els} branches. Let us
  7957. illustrate this translation by returning to the program with an
  7958. \code{if} expression in tail position, shown next. We invoke
  7959. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7960. \python{\code{x == 0}}.
  7961. %
  7962. {\if\edition\racketEd
  7963. \begin{lstlisting}
  7964. (let ([x (read)])
  7965. (if (eq? x 0) 42 777))
  7966. \end{lstlisting}
  7967. \fi}
  7968. %
  7969. {\if\edition\pythonEd
  7970. \begin{lstlisting}
  7971. x = input_int()
  7972. 42 if x == 0 else 777
  7973. \end{lstlisting}
  7974. \fi}
  7975. %
  7976. \noindent The two branches \code{42} and \code{777} were already
  7977. compiled to \code{return} statements, from which we now create the
  7978. following blocks:
  7979. %
  7980. \begin{center}
  7981. \begin{minipage}{\textwidth}
  7982. \begin{lstlisting}
  7983. block_1:
  7984. return 42;
  7985. block_2:
  7986. return 777;
  7987. \end{lstlisting}
  7988. \end{minipage}
  7989. \end{center}
  7990. %
  7991. After that, \code{explicate\_pred} compiles the comparison
  7992. \racket{\code{(eq? x 0)}}
  7993. \python{\code{x == 0}}
  7994. to the following \code{if} statement:
  7995. %
  7996. {\if\edition\racketEd
  7997. \begin{center}
  7998. \begin{minipage}{\textwidth}
  7999. \begin{lstlisting}
  8000. if (eq? x 0)
  8001. goto block_1;
  8002. else
  8003. goto block_2;
  8004. \end{lstlisting}
  8005. \end{minipage}
  8006. \end{center}
  8007. \fi}
  8008. {\if\edition\pythonEd
  8009. \begin{center}
  8010. \begin{minipage}{\textwidth}
  8011. \begin{lstlisting}
  8012. if x == 0:
  8013. goto block_1;
  8014. else
  8015. goto block_2;
  8016. \end{lstlisting}
  8017. \end{minipage}
  8018. \end{center}
  8019. \fi}
  8020. Next consider the case for Boolean constants. We perform a kind of
  8021. partial evaluation\index{subject}{partial evaluation} and output
  8022. either the \code{thn} or \code{els} branch, depending on whether the
  8023. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8024. following program:
  8025. {\if\edition\racketEd
  8026. \begin{lstlisting}
  8027. (if #t 42 777)
  8028. \end{lstlisting}
  8029. \fi}
  8030. {\if\edition\pythonEd
  8031. \begin{lstlisting}
  8032. 42 if True else 777
  8033. \end{lstlisting}
  8034. \fi}
  8035. %
  8036. \noindent Again, the two branches \code{42} and \code{777} were
  8037. compiled to \code{return} statements, so \code{explicate\_pred}
  8038. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8039. code for the \emph{then} branch.
  8040. \begin{lstlisting}
  8041. return 42;
  8042. \end{lstlisting}
  8043. This case demonstrates that we sometimes discard the \code{thn} or
  8044. \code{els} blocks that are input to \code{explicate\_pred}.
  8045. The case for \key{if} expressions in \code{explicate\_pred} is
  8046. particularly illuminating because it deals with the challenges
  8047. discussed previously regarding nested \key{if} expressions
  8048. (figure~\ref{fig:explicate-control-s1-38}). The
  8049. \racket{\lstinline{thn^}}\python{\code{body}} and
  8050. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8051. \key{if} inherit their context from the current one, that is,
  8052. predicate context. So, you should recursively apply
  8053. \code{explicate\_pred} to the
  8054. \racket{\lstinline{thn^}}\python{\code{body}} and
  8055. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8056. those recursive calls, pass \code{thn} and \code{els} as the extra
  8057. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8058. inside each recursive call. As discussed previously, to avoid
  8059. duplicating code, we need to add them to the dictionary of basic
  8060. blocks so that we can instead refer to them by name and execute them
  8061. with a \key{goto}.
  8062. {\if\edition\pythonEd
  8063. %
  8064. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8065. three parameters: 1) the statement to be compiled, 2) the code for its
  8066. continuation, and 3) the dictionary of basic blocks. The
  8067. \code{explicate\_stmt} returns a list of statements and it may add to
  8068. the dictionary of basic blocks. The cases for assignment and an
  8069. expression-statement are given in full in the skeleton code: they
  8070. simply dispatch to \code{explicate\_assign} and
  8071. \code{explicate\_effect}, respectively. The case for \code{if}
  8072. statements is not given, and is similar to the case for \code{if}
  8073. expressions.
  8074. The \code{explicate\_control} function itself is given in
  8075. figure~\ref{fig:explicate-control-Lif}. It applies
  8076. \code{explicate\_stmt} to each statement in the program, from back to
  8077. front. Thus, the result so-far, stored in \code{new\_body}, can be
  8078. used as the continuation parameter in the next call to
  8079. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8080. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8081. the dictionary of basic blocks, labeling it as the ``start'' block.
  8082. %
  8083. \fi}
  8084. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8085. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8086. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8087. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8088. %% results from the two recursive calls. We complete the case for
  8089. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8090. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8091. %% the result $B_5$.
  8092. %% \[
  8093. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8094. %% \quad\Rightarrow\quad
  8095. %% B_5
  8096. %% \]
  8097. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8098. %% inherit the current context, so they are in tail position. Thus, the
  8099. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8100. %% \code{explicate\_tail}.
  8101. %% %
  8102. %% We need to pass $B_0$ as the accumulator argument for both of these
  8103. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8104. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8105. %% to the control-flow graph and obtain a promised goto $G_0$.
  8106. %% %
  8107. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8108. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8109. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8110. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8111. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8112. %% \[
  8113. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8114. %% \]
  8115. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8116. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8117. %% should not be confused with the labels for the blocks that appear in
  8118. %% the generated code. We initially construct unlabeled blocks; we only
  8119. %% attach labels to blocks when we add them to the control-flow graph, as
  8120. %% we see in the next case.
  8121. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8122. %% function. The context of the \key{if} is an assignment to some
  8123. %% variable $x$ and then the control continues to some promised block
  8124. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8125. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8126. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8127. %% branches of the \key{if} inherit the current context, so they are in
  8128. %% assignment positions. Let $B_2$ be the result of applying
  8129. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8130. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8131. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8132. %% the result of applying \code{explicate\_pred} to the predicate
  8133. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8134. %% translates to the promise $B_4$.
  8135. %% \[
  8136. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8137. %% \]
  8138. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8139. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8140. \code{remove\_complex\_operands} pass and then the
  8141. \code{explicate\_control} pass on the example program. We walk through
  8142. the output program.
  8143. %
  8144. Following the order of evaluation in the output of
  8145. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8146. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8147. in the predicate of the inner \key{if}. In the output of
  8148. \code{explicate\_control}, in the
  8149. block labeled \code{start}, two assignment statements are followed by an
  8150. \code{if} statement that branches to \code{block\_4} or
  8151. \code{block\_5}. The blocks associated with those labels contain the
  8152. translations of the code
  8153. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8154. and
  8155. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8156. respectively. In particular, we start \code{block\_4} with the
  8157. comparison
  8158. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8159. and then branch to \code{block\_2} or \code{block\_3},
  8160. which correspond to the two branches of the outer \key{if}, that is,
  8161. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8162. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8163. %
  8164. The story for \code{block\_5} is similar to that of \code{block\_4}.
  8165. %
  8166. \python{The \code{block\_1} corresponds to the \code{print} statement
  8167. at the end of the program.}
  8168. {\if\edition\racketEd
  8169. \subsection{Interactions between Explicate and Shrink}
  8170. The way in which the \code{shrink} pass transforms logical operations
  8171. such as \code{and} and \code{or} can impact the quality of code
  8172. generated by \code{explicate\_control}. For example, consider the
  8173. following program:
  8174. % cond_test_21.rkt, and_eq_input.py
  8175. \begin{lstlisting}
  8176. (if (and (eq? (read) 0) (eq? (read) 1))
  8177. 0
  8178. 42)
  8179. \end{lstlisting}
  8180. The \code{and} operation should transform into something that the
  8181. \code{explicate\_pred} function can analyze and descend through to
  8182. reach the underlying \code{eq?} conditions. Ideally, for this program
  8183. your \code{explicate\_control} pass should generate code similar to
  8184. the following:
  8185. \begin{center}
  8186. \begin{minipage}{\textwidth}
  8187. \begin{lstlisting}
  8188. start:
  8189. tmp1 = (read);
  8190. if (eq? tmp1 0) goto block40;
  8191. else goto block39;
  8192. block40:
  8193. tmp2 = (read);
  8194. if (eq? tmp2 1) goto block38;
  8195. else goto block39;
  8196. block38:
  8197. return 0;
  8198. block39:
  8199. return 42;
  8200. \end{lstlisting}
  8201. \end{minipage}
  8202. \end{center}
  8203. \fi}
  8204. \begin{exercise}\normalfont\normalsize
  8205. \racket{
  8206. Implement the pass \code{explicate\_control} by adding the cases for
  8207. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8208. \code{explicate\_assign} functions. Implement the auxiliary function
  8209. \code{explicate\_pred} for predicate contexts.}
  8210. \python{Implement \code{explicate\_control} pass with its
  8211. four auxiliary functions.}
  8212. %
  8213. Create test cases that exercise all the new cases in the code for
  8214. this pass.
  8215. %
  8216. {\if\edition\racketEd
  8217. Add the following entry to the list of \code{passes} in
  8218. \code{run-tests.rkt}:
  8219. \begin{lstlisting}
  8220. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8221. \end{lstlisting}
  8222. and then run \code{run-tests.rkt} to test your compiler.
  8223. \fi}
  8224. \end{exercise}
  8225. \section{Select Instructions}
  8226. \label{sec:select-Lif}
  8227. \index{subject}{instruction selection}
  8228. The \code{select\_instructions} pass translates \LangCIf{} to
  8229. \LangXIfVar{}.
  8230. %
  8231. \racket{Recall that we implement this pass using three auxiliary
  8232. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  8233. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  8234. %
  8235. \racket{For $\Atm$, we have new cases for the Booleans.}
  8236. %
  8237. \python{We begin with the Boolean constants.}
  8238. We take the usual approach of encoding them as integers.
  8239. \[
  8240. \TRUE{} \quad\Rightarrow\quad \key{1}
  8241. \qquad\qquad
  8242. \FALSE{} \quad\Rightarrow\quad \key{0}
  8243. \]
  8244. For translating statements, we discuss some of the cases. The
  8245. \code{not} operation can be implemented in terms of \code{xorq}, as we
  8246. discussed at the beginning of this section. Given an assignment, if
  8247. the left-hand-side variable is the same as the argument of \code{not},
  8248. then just the \code{xorq} instruction suffices.
  8249. \[
  8250. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  8251. \quad\Rightarrow\quad
  8252. \key{xorq}~\key{\$}1\key{,}~\Var
  8253. \]
  8254. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8255. semantics of x86. In the following translation, let $\Arg$ be the
  8256. result of translating $\Atm$ to x86.
  8257. \[
  8258. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8259. \quad\Rightarrow\quad
  8260. \begin{array}{l}
  8261. \key{movq}~\Arg\key{,}~\Var\\
  8262. \key{xorq}~\key{\$}1\key{,}~\Var
  8263. \end{array}
  8264. \]
  8265. Next consider the cases for equality comparisons. Translating this
  8266. operation to x86 is slightly involved due to the unusual nature of the
  8267. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  8268. We recommend translating an assignment with an equality on the
  8269. right-hand side into a sequence of three instructions. \\
  8270. \begin{tabular}{lll}
  8271. \begin{minipage}{0.4\textwidth}
  8272. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  8273. \end{minipage}
  8274. &
  8275. $\Rightarrow$
  8276. &
  8277. \begin{minipage}{0.4\textwidth}
  8278. \begin{lstlisting}
  8279. cmpq |$\Arg_2$|, |$\Arg_1$|
  8280. sete %al
  8281. movzbq %al, |$\Var$|
  8282. \end{lstlisting}
  8283. \end{minipage}
  8284. \end{tabular} \\
  8285. The translations for the other comparison operators are similar to
  8286. this but use different condition codes for the \code{set} instruction.
  8287. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  8288. \key{goto} and \key{if} statements. Both are straightforward to
  8289. translate to x86.}
  8290. %
  8291. A \key{goto} statement becomes a jump instruction.
  8292. \[
  8293. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8294. \]
  8295. %
  8296. An \key{if} statement becomes a compare instruction followed by a
  8297. conditional jump (for the \emph{then} branch), and the fall-through is to
  8298. a regular jump (for the \emph{else} branch).\\
  8299. \begin{tabular}{lll}
  8300. \begin{minipage}{0.4\textwidth}
  8301. \begin{lstlisting}
  8302. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8303. goto |$\ell_1$||$\racket{\key{;}}$|
  8304. else|$\python{\key{:}}$|
  8305. goto |$\ell_2$||$\racket{\key{;}}$|
  8306. \end{lstlisting}
  8307. \end{minipage}
  8308. &
  8309. $\Rightarrow$
  8310. &
  8311. \begin{minipage}{0.4\textwidth}
  8312. \begin{lstlisting}
  8313. cmpq |$\Arg_2$|, |$\Arg_1$|
  8314. je |$\ell_1$|
  8315. jmp |$\ell_2$|
  8316. \end{lstlisting}
  8317. \end{minipage}
  8318. \end{tabular} \\
  8319. Again, the translations for the other comparison operators are similar to this
  8320. but use different condition codes for the conditional jump instruction.
  8321. \python{Regarding the \key{return} statement, we recommend treating it
  8322. as an assignment to the \key{rax} register followed by a jump to the
  8323. conclusion of the \code{main} function.}
  8324. \begin{exercise}\normalfont\normalsize
  8325. Expand your \code{select\_instructions} pass to handle the new
  8326. features of the \LangCIf{} language.
  8327. %
  8328. {\if\edition\racketEd
  8329. Add the following entry to the list of \code{passes} in
  8330. \code{run-tests.rkt}
  8331. \begin{lstlisting}
  8332. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8333. \end{lstlisting}
  8334. \fi}
  8335. %
  8336. Run the script to test your compiler on all the test programs.
  8337. \end{exercise}
  8338. \section{Register Allocation}
  8339. \label{sec:register-allocation-Lif}
  8340. \index{subject}{register allocation}
  8341. The changes required for compiling \LangIf{} affect liveness analysis,
  8342. building the interference graph, and assigning homes, but the graph
  8343. coloring algorithm itself does not change.
  8344. \subsection{Liveness Analysis}
  8345. \label{sec:liveness-analysis-Lif}
  8346. \index{subject}{liveness analysis}
  8347. Recall that for \LangVar{} we implemented liveness analysis for a
  8348. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  8349. the addition of \key{if} expressions to \LangIf{},
  8350. \code{explicate\_control} produces many basic blocks.
  8351. %% We recommend that you create a new auxiliary function named
  8352. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8353. %% control-flow graph.
  8354. The first question is, in what order should we process the basic blocks?
  8355. Recall that to perform liveness analysis on a basic block we need to
  8356. know the live-after set for the last instruction in the block. If a
  8357. basic block has no successors (i.e., contains no jumps to other
  8358. blocks), then it has an empty live-after set and we can immediately
  8359. apply liveness analysis to it. If a basic block has some successors,
  8360. then we need to complete liveness analysis on those blocks
  8361. first. These ordering constraints are the reverse of a
  8362. \emph{topological order}\index{subject}{topological order} on a graph
  8363. representation of the program. In particular, the \emph{control flow
  8364. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8365. of a program has a node for each basic block and an edge for each jump
  8366. from one block to another. It is straightforward to generate a CFG
  8367. from the dictionary of basic blocks. One then transposes the CFG and
  8368. applies the topological sort algorithm.
  8369. %
  8370. %
  8371. \racket{We recommend using the \code{tsort} and \code{transpose}
  8372. functions of the Racket \code{graph} package to accomplish this.}
  8373. %
  8374. \python{We provide implementations of \code{topological\_sort} and
  8375. \code{transpose} in the file \code{graph.py} of the support code.}
  8376. %
  8377. As an aside, a topological ordering is only guaranteed to exist if the
  8378. graph does not contain any cycles. This is the case for the
  8379. control-flow graphs that we generate from \LangIf{} programs.
  8380. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8381. and learn how to handle cycles in the control-flow graph.
  8382. \racket{You need to construct a directed graph to represent the
  8383. control-flow graph. Do not use the \code{directed-graph} of the
  8384. \code{graph} package because that allows at most one edge
  8385. between each pair of vertices, whereas a control-flow graph may have
  8386. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8387. file in the support code implements a graph representation that
  8388. allows multiple edges between a pair of vertices.}
  8389. {\if\edition\racketEd
  8390. The next question is how to analyze jump instructions. Recall that in
  8391. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8392. \code{label->live} that maps each label to the set of live locations
  8393. at the beginning of its block. We use \code{label->live} to determine
  8394. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8395. that we have many basic blocks, \code{label->live} needs to be updated
  8396. as we process the blocks. In particular, after performing liveness
  8397. analysis on a block, we take the live-before set of its first
  8398. instruction and associate that with the block's label in the
  8399. \code{label->live} alist.
  8400. \fi}
  8401. %
  8402. {\if\edition\pythonEd
  8403. %
  8404. The next question is how to analyze jump instructions. The locations
  8405. that are live before a \code{jmp} should be the locations in
  8406. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  8407. maintaining a dictionary named \code{live\_before\_block} that maps each
  8408. label to the $L_{\mathsf{before}}$ for the first instruction in its
  8409. block. After performing liveness analysis on each block, we take the
  8410. live-before set of its first instruction and associate that with the
  8411. block's label in the \code{live\_before\_block} dictionary.
  8412. %
  8413. \fi}
  8414. In \LangXIfVar{} we also have the conditional jump
  8415. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8416. this instruction is particularly interesting because during
  8417. compilation, we do not know which way a conditional jump will go. Thus
  8418. we do not know whether to use the live-before set for the block
  8419. associated with the $\itm{label}$ or the live-before set for the
  8420. following instruction. However, there is no harm to the correctness
  8421. of the generated code if we classify more locations as live than the
  8422. ones that are truly live during one particular execution of the
  8423. instruction. Thus, we can take the union of the live-before sets from
  8424. the following instruction and from the mapping for $\itm{label}$ in
  8425. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8426. The auxiliary functions for computing the variables in an
  8427. instruction's argument and for computing the variables read-from ($R$)
  8428. or written-to ($W$) by an instruction need to be updated to handle the
  8429. new kinds of arguments and instructions in \LangXIfVar{}.
  8430. \begin{exercise}\normalfont\normalsize
  8431. {\if\edition\racketEd
  8432. %
  8433. Update the \code{uncover\_live} pass to apply liveness analysis to
  8434. every basic block in the program.
  8435. %
  8436. Add the following entry to the list of \code{passes} in the
  8437. \code{run-tests.rkt} script:
  8438. \begin{lstlisting}
  8439. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8440. \end{lstlisting}
  8441. \fi}
  8442. {\if\edition\pythonEd
  8443. %
  8444. Update the \code{uncover\_live} function to perform liveness analysis,
  8445. in reverse topological order, on all the basic blocks in the
  8446. program.
  8447. %
  8448. \fi}
  8449. % Check that the live-after sets that you generate for
  8450. % example X matches the following... -Jeremy
  8451. \end{exercise}
  8452. \subsection{Build the Interference Graph}
  8453. \label{sec:build-interference-Lif}
  8454. Many of the new instructions in \LangXIfVar{} can be handled in the
  8455. same way as the instructions in \LangXVar{}.
  8456. % Thus, if your code was
  8457. % already quite general, it will not need to be changed to handle the
  8458. % new instructions. If your code is not general enough, we recommend that
  8459. % you change your code to be more general. For example, you can factor
  8460. % out the computing of the the read and write sets for each kind of
  8461. % instruction into auxiliary functions.
  8462. %
  8463. Some instructions, such as the \key{movzbq} instruction, require special care,
  8464. similar to the \key{movq} instruction. Refer to rule number 1 in
  8465. section~\ref{sec:build-interference}.
  8466. \begin{exercise}\normalfont\normalsize
  8467. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8468. {\if\edition\racketEd
  8469. Add the following entries to the list of \code{passes} in the
  8470. \code{run-tests.rkt} script:
  8471. \begin{lstlisting}
  8472. (list "build_interference" build_interference interp-pseudo-x86-1)
  8473. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8474. \end{lstlisting}
  8475. \fi}
  8476. % Check that the interference graph that you generate for
  8477. % example X matches the following graph G... -Jeremy
  8478. \end{exercise}
  8479. \section{Patch Instructions}
  8480. The new instructions \key{cmpq} and \key{movzbq} have some special
  8481. restrictions that need to be handled in the \code{patch\_instructions}
  8482. pass.
  8483. %
  8484. The second argument of the \key{cmpq} instruction must not be an
  8485. immediate value (such as an integer). So, if you are comparing two
  8486. immediates, we recommend inserting a \key{movq} instruction to put the
  8487. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8488. one memory reference.
  8489. %
  8490. The second argument of the \key{movzbq} must be a register.
  8491. \begin{exercise}\normalfont\normalsize
  8492. %
  8493. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8494. %
  8495. {\if\edition\racketEd
  8496. Add the following entry to the list of \code{passes} in
  8497. \code{run-tests.rkt}, and then run this script to test your compiler.
  8498. \begin{lstlisting}
  8499. (list "patch_instructions" patch_instructions interp-x86-1)
  8500. \end{lstlisting}
  8501. \fi}
  8502. \end{exercise}
  8503. {\if\edition\pythonEd
  8504. \section{Prelude and Conclusion}
  8505. \label{sec:prelude-conclusion-cond}
  8506. The generation of the \code{main} function with its prelude and
  8507. conclusion must change to accommodate how the program now consists of
  8508. one or more basic blocks. After the prelude in \code{main}, jump to
  8509. the \code{start} block. Place the conclusion in a basic block labeled
  8510. with \code{conclusion}.
  8511. \fi}
  8512. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8513. \LangIf{} translated to x86, showing the results of
  8514. \code{explicate\_control}, \code{select\_instructions}, and the final
  8515. x86 assembly.
  8516. \begin{figure}[tbp]
  8517. \begin{tcolorbox}[colback=white]
  8518. {\if\edition\racketEd
  8519. \begin{tabular}{lll}
  8520. \begin{minipage}{0.4\textwidth}
  8521. % cond_test_20.rkt, eq_input.py
  8522. \begin{lstlisting}
  8523. (if (eq? (read) 1) 42 0)
  8524. \end{lstlisting}
  8525. $\Downarrow$
  8526. \begin{lstlisting}
  8527. start:
  8528. tmp7951 = (read);
  8529. if (eq? tmp7951 1)
  8530. goto block7952;
  8531. else
  8532. goto block7953;
  8533. block7952:
  8534. return 42;
  8535. block7953:
  8536. return 0;
  8537. \end{lstlisting}
  8538. $\Downarrow$
  8539. \begin{lstlisting}
  8540. start:
  8541. callq read_int
  8542. movq %rax, tmp7951
  8543. cmpq $1, tmp7951
  8544. je block7952
  8545. jmp block7953
  8546. block7953:
  8547. movq $0, %rax
  8548. jmp conclusion
  8549. block7952:
  8550. movq $42, %rax
  8551. jmp conclusion
  8552. \end{lstlisting}
  8553. \end{minipage}
  8554. &
  8555. $\Rightarrow\qquad$
  8556. \begin{minipage}{0.4\textwidth}
  8557. \begin{lstlisting}
  8558. start:
  8559. callq read_int
  8560. movq %rax, %rcx
  8561. cmpq $1, %rcx
  8562. je block7952
  8563. jmp block7953
  8564. block7953:
  8565. movq $0, %rax
  8566. jmp conclusion
  8567. block7952:
  8568. movq $42, %rax
  8569. jmp conclusion
  8570. .globl main
  8571. main:
  8572. pushq %rbp
  8573. movq %rsp, %rbp
  8574. pushq %r13
  8575. pushq %r12
  8576. pushq %rbx
  8577. pushq %r14
  8578. subq $0, %rsp
  8579. jmp start
  8580. conclusion:
  8581. addq $0, %rsp
  8582. popq %r14
  8583. popq %rbx
  8584. popq %r12
  8585. popq %r13
  8586. popq %rbp
  8587. retq
  8588. \end{lstlisting}
  8589. \end{minipage}
  8590. \end{tabular}
  8591. \fi}
  8592. {\if\edition\pythonEd
  8593. \begin{tabular}{lll}
  8594. \begin{minipage}{0.4\textwidth}
  8595. % cond_test_20.rkt, eq_input.py
  8596. \begin{lstlisting}
  8597. print(42 if input_int() == 1 else 0)
  8598. \end{lstlisting}
  8599. $\Downarrow$
  8600. \begin{lstlisting}
  8601. start:
  8602. tmp_0 = input_int()
  8603. if tmp_0 == 1:
  8604. goto block_3
  8605. else:
  8606. goto block_4
  8607. block_3:
  8608. tmp_1 = 42
  8609. goto block_2
  8610. block_4:
  8611. tmp_1 = 0
  8612. goto block_2
  8613. block_2:
  8614. print(tmp_1)
  8615. return 0
  8616. \end{lstlisting}
  8617. $\Downarrow$
  8618. \begin{lstlisting}
  8619. start:
  8620. callq read_int
  8621. movq %rax, tmp_0
  8622. cmpq 1, tmp_0
  8623. je block_3
  8624. jmp block_4
  8625. block_3:
  8626. movq 42, tmp_1
  8627. jmp block_2
  8628. block_4:
  8629. movq 0, tmp_1
  8630. jmp block_2
  8631. block_2:
  8632. movq tmp_1, %rdi
  8633. callq print_int
  8634. movq 0, %rax
  8635. jmp conclusion
  8636. \end{lstlisting}
  8637. \end{minipage}
  8638. &
  8639. $\Rightarrow\qquad$
  8640. \begin{minipage}{0.4\textwidth}
  8641. \begin{lstlisting}
  8642. .globl main
  8643. main:
  8644. pushq %rbp
  8645. movq %rsp, %rbp
  8646. subq $0, %rsp
  8647. jmp start
  8648. start:
  8649. callq read_int
  8650. movq %rax, %rcx
  8651. cmpq $1, %rcx
  8652. je block_3
  8653. jmp block_4
  8654. block_3:
  8655. movq $42, %rcx
  8656. jmp block_2
  8657. block_4:
  8658. movq $0, %rcx
  8659. jmp block_2
  8660. block_2:
  8661. movq %rcx, %rdi
  8662. callq print_int
  8663. movq $0, %rax
  8664. jmp conclusion
  8665. conclusion:
  8666. addq $0, %rsp
  8667. popq %rbp
  8668. retq
  8669. \end{lstlisting}
  8670. \end{minipage}
  8671. \end{tabular}
  8672. \fi}
  8673. \end{tcolorbox}
  8674. \caption{Example compilation of an \key{if} expression to x86, showing
  8675. the results of \code{explicate\_control},
  8676. \code{select\_instructions}, and the final x86 assembly code. }
  8677. \label{fig:if-example-x86}
  8678. \end{figure}
  8679. \begin{figure}[tbp]
  8680. \begin{tcolorbox}[colback=white]
  8681. {\if\edition\racketEd
  8682. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8683. \node (Lif-2) at (0,2) {\large \LangIf{}};
  8684. \node (Lif-3) at (3,2) {\large \LangIf{}};
  8685. \node (Lif-4) at (6,2) {\large \LangIf{}};
  8686. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  8687. \node (C1-1) at (0,0) {\large \LangCIf{}};
  8688. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  8689. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  8690. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  8691. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  8692. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  8693. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  8694. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8695. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8696. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  8697. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8698. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8699. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8700. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  8701. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  8702. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  8703. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  8704. \end{tikzpicture}
  8705. \fi}
  8706. {\if\edition\pythonEd
  8707. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  8708. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8709. \node (Lif-2) at (4,2) {\large \LangIf{}};
  8710. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  8711. \node (C-1) at (0,0) {\large \LangCIf{}};
  8712. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  8713. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  8714. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  8715. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8716. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8717. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  8718. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8719. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  8720. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8721. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  8722. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  8723. \end{tikzpicture}
  8724. \fi}
  8725. \end{tcolorbox}
  8726. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8727. \label{fig:Lif-passes}
  8728. \end{figure}
  8729. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8730. compilation of \LangIf{}.
  8731. \section{Challenge: Optimize Blocks and Remove Jumps}
  8732. \label{sec:opt-jumps}
  8733. We discuss two optional challenges that involve optimizing the
  8734. control-flow of the program.
  8735. \subsection{Optimize Blocks}
  8736. The algorithm for \code{explicate\_control} that we discussed in
  8737. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8738. blocks. It creates a basic block whenever a continuation \emph{might}
  8739. get used more than once (e.g., whenever the \code{cont} parameter is
  8740. passed into two or more recursive calls). However, some continuation
  8741. arguments may not be used at all. For example, consider the case for
  8742. the constant \TRUE{} in \code{explicate\_pred}, in which we discard the
  8743. \code{els} continuation.
  8744. %
  8745. {\if\edition\racketEd
  8746. The following example program falls into this
  8747. case, and it creates two unused blocks.
  8748. \begin{center}
  8749. \begin{tabular}{lll}
  8750. \begin{minipage}{0.4\textwidth}
  8751. % cond_test_82.rkt
  8752. \begin{lstlisting}
  8753. (let ([y (if #t
  8754. (read)
  8755. (if (eq? (read) 0)
  8756. 777
  8757. (let ([x (read)])
  8758. (+ 1 x))))])
  8759. (+ y 2))
  8760. \end{lstlisting}
  8761. \end{minipage}
  8762. &
  8763. $\Rightarrow$
  8764. &
  8765. \begin{minipage}{0.55\textwidth}
  8766. \begin{lstlisting}
  8767. start:
  8768. y = (read);
  8769. goto block_5;
  8770. block_5:
  8771. return (+ y 2);
  8772. block_6:
  8773. y = 777;
  8774. goto block_5;
  8775. block_7:
  8776. x = (read);
  8777. y = (+ 1 x2);
  8778. goto block_5;
  8779. \end{lstlisting}
  8780. \end{minipage}
  8781. \end{tabular}
  8782. \end{center}
  8783. \fi}
  8784. The question is, how can we decide whether to create a basic block?
  8785. \emph{Lazy evaluation}\index{subject}{lazy
  8786. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8787. delaying the creation of a basic block until the point in time at which
  8788. we know that it will be used.
  8789. %
  8790. {\if\edition\racketEd
  8791. %
  8792. Racket provides support for
  8793. lazy evaluation with the
  8794. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8795. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8796. \index{subject}{delay} creates a
  8797. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8798. expressions is postponed. When \key{(force}
  8799. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8800. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8801. result of $e_n$ is cached in the promise and returned. If \code{force}
  8802. is applied again to the same promise, then the cached result is
  8803. returned. If \code{force} is applied to an argument that is not a
  8804. promise, \code{force} simply returns the argument.
  8805. %
  8806. \fi}
  8807. %
  8808. {\if\edition\pythonEd
  8809. %
  8810. While Python does not provide direct support for lazy evaluation, it
  8811. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8812. by wrapping it inside a function with no parameters. We can
  8813. \emph{force} its evaluation by calling the function. However, in some
  8814. cases of \code{explicate\_pred}, etc., we will return a list of
  8815. statements and in other cases we will return a function that computes
  8816. a list of statements. We use the term \emph{promise} to refer to a
  8817. value that may be delayed. To uniformly deal with
  8818. promises, we define the following \code{force} function that checks
  8819. whether its input is delayed (i.e., whether it is a function) and then
  8820. either 1) calls the function, or 2) returns the input.
  8821. \begin{lstlisting}
  8822. def force(promise):
  8823. if isinstance(promise, types.FunctionType):
  8824. return promise()
  8825. else:
  8826. return promise
  8827. \end{lstlisting}
  8828. %
  8829. \fi}
  8830. We use promises for the input and output of the functions
  8831. \code{explicate\_pred}, \code{explicate\_assign},
  8832. %
  8833. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8834. %
  8835. So, instead of taking and returning \racket{$\Tail$
  8836. expressions}\python{lists of statements}, they take and return
  8837. promises. Furthermore, when we come to a situation in which a
  8838. continuation might be used more than once, as in the case for
  8839. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8840. that creates a basic block for each continuation (if there is not
  8841. already one) and then returns a \code{goto} statement to that basic
  8842. block. When we come to a situation in which we have a promise but need an
  8843. actual piece of code, for example, to create a larger piece of code with a
  8844. constructor such as \code{Seq}, then insert a call to \code{force}.
  8845. %
  8846. {\if\edition\racketEd
  8847. %
  8848. Also, we must modify the \code{create\_block} function to begin with
  8849. \code{delay} to create a promise. When forced, this promise forces the
  8850. original promise. If that returns a \code{Goto} (because the block was
  8851. already added to \code{basic-blocks}), then we return the
  8852. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  8853. return a \code{Goto} to the new label.
  8854. \begin{center}
  8855. \begin{minipage}{\textwidth}
  8856. \begin{lstlisting}
  8857. (define (create_block tail)
  8858. (delay
  8859. (define t (force tail))
  8860. (match t
  8861. [(Goto label) (Goto label)]
  8862. [else
  8863. (let ([label (gensym 'block)])
  8864. (set! basic-blocks (cons (cons label t) basic-blocks))
  8865. (Goto label))]))
  8866. \end{lstlisting}
  8867. \end{minipage}
  8868. \end{center}
  8869. \fi}
  8870. {\if\edition\pythonEd
  8871. %
  8872. Here is the new version of the \code{create\_block} auxiliary function
  8873. that works on promises and that checks whether the block consists of a
  8874. solitary \code{goto} statement.\\
  8875. \begin{minipage}{\textwidth}
  8876. \begin{lstlisting}
  8877. def create_block(promise, basic_blocks):
  8878. stmts = force(promise)
  8879. match stmts:
  8880. case [Goto(l)]:
  8881. return Goto(l)
  8882. case _:
  8883. label = label_name(generate_name('block'))
  8884. basic_blocks[label] = stmts
  8885. return Goto(label)
  8886. \end{lstlisting}
  8887. \end{minipage}
  8888. \fi}
  8889. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8890. improved \code{explicate\_control} on this example. As you can
  8891. see, the number of basic blocks has been reduced from four blocks (see
  8892. figure~\ref{fig:explicate-control-s1-38}) to two blocks.
  8893. \begin{figure}[tbp]
  8894. \begin{tcolorbox}[colback=white]
  8895. {\if\edition\racketEd
  8896. \begin{tabular}{lll}
  8897. \begin{minipage}{0.4\textwidth}
  8898. % cond_test_82.rkt
  8899. \begin{lstlisting}
  8900. (let ([y (if #t
  8901. (read)
  8902. (if (eq? (read) 0)
  8903. 777
  8904. (let ([x (read)])
  8905. (+ 1 x))))])
  8906. (+ y 2))
  8907. \end{lstlisting}
  8908. \end{minipage}
  8909. &
  8910. $\Rightarrow$
  8911. &
  8912. \begin{minipage}{0.55\textwidth}
  8913. \begin{lstlisting}
  8914. start:
  8915. y = (read);
  8916. goto block_5;
  8917. block_5:
  8918. return (+ y 2);
  8919. \end{lstlisting}
  8920. \end{minipage}
  8921. \end{tabular}
  8922. \fi}
  8923. {\if\edition\pythonEd
  8924. \begin{tabular}{lll}
  8925. \begin{minipage}{0.4\textwidth}
  8926. % cond_test_41.rkt
  8927. \begin{lstlisting}
  8928. x = input_int()
  8929. y = input_int()
  8930. print(y + 2 \
  8931. if (x == 0 \
  8932. if x < 1 \
  8933. else x == 2) \
  8934. else y + 10)
  8935. \end{lstlisting}
  8936. \end{minipage}
  8937. &
  8938. $\Rightarrow$
  8939. &
  8940. \begin{minipage}{0.55\textwidth}
  8941. \begin{lstlisting}
  8942. start:
  8943. x = input_int()
  8944. y = input_int()
  8945. if x < 1:
  8946. goto block_4
  8947. else:
  8948. goto block_5
  8949. block_4:
  8950. if x == 0:
  8951. goto block_2
  8952. else:
  8953. goto block_3
  8954. block_5:
  8955. if x == 2:
  8956. goto block_2
  8957. else:
  8958. goto block_3
  8959. block_2:
  8960. tmp_0 = y + 2
  8961. goto block_1
  8962. block_3:
  8963. tmp_0 = y + 10
  8964. goto block_1
  8965. block_1:
  8966. print(tmp_0)
  8967. return 0
  8968. \end{lstlisting}
  8969. \end{minipage}
  8970. \end{tabular}
  8971. \fi}
  8972. \end{tcolorbox}
  8973. \caption{Translation from \LangIf{} to \LangCIf{}
  8974. via the improved \code{explicate\_control}.}
  8975. \label{fig:explicate-control-challenge}
  8976. \end{figure}
  8977. %% Recall that in the example output of \code{explicate\_control} in
  8978. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8979. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8980. %% block. The first goal of this challenge assignment is to remove those
  8981. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8982. %% \code{explicate\_control} on the left and shows the result of bypassing
  8983. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8984. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8985. %% \code{block55}. The optimized code on the right of
  8986. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8987. %% \code{then} branch jumping directly to \code{block55}. The story is
  8988. %% similar for the \code{else} branch, as well as for the two branches in
  8989. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8990. %% have been optimized in this way, there are no longer any jumps to
  8991. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8992. %% \begin{figure}[tbp]
  8993. %% \begin{tabular}{lll}
  8994. %% \begin{minipage}{0.4\textwidth}
  8995. %% \begin{lstlisting}
  8996. %% block62:
  8997. %% tmp54 = (read);
  8998. %% if (eq? tmp54 2) then
  8999. %% goto block59;
  9000. %% else
  9001. %% goto block60;
  9002. %% block61:
  9003. %% tmp53 = (read);
  9004. %% if (eq? tmp53 0) then
  9005. %% goto block57;
  9006. %% else
  9007. %% goto block58;
  9008. %% block60:
  9009. %% goto block56;
  9010. %% block59:
  9011. %% goto block55;
  9012. %% block58:
  9013. %% goto block56;
  9014. %% block57:
  9015. %% goto block55;
  9016. %% block56:
  9017. %% return (+ 700 77);
  9018. %% block55:
  9019. %% return (+ 10 32);
  9020. %% start:
  9021. %% tmp52 = (read);
  9022. %% if (eq? tmp52 1) then
  9023. %% goto block61;
  9024. %% else
  9025. %% goto block62;
  9026. %% \end{lstlisting}
  9027. %% \end{minipage}
  9028. %% &
  9029. %% $\Rightarrow$
  9030. %% &
  9031. %% \begin{minipage}{0.55\textwidth}
  9032. %% \begin{lstlisting}
  9033. %% block62:
  9034. %% tmp54 = (read);
  9035. %% if (eq? tmp54 2) then
  9036. %% goto block55;
  9037. %% else
  9038. %% goto block56;
  9039. %% block61:
  9040. %% tmp53 = (read);
  9041. %% if (eq? tmp53 0) then
  9042. %% goto block55;
  9043. %% else
  9044. %% goto block56;
  9045. %% block56:
  9046. %% return (+ 700 77);
  9047. %% block55:
  9048. %% return (+ 10 32);
  9049. %% start:
  9050. %% tmp52 = (read);
  9051. %% if (eq? tmp52 1) then
  9052. %% goto block61;
  9053. %% else
  9054. %% goto block62;
  9055. %% \end{lstlisting}
  9056. %% \end{minipage}
  9057. %% \end{tabular}
  9058. %% \caption{Optimize jumps by removing trivial blocks.}
  9059. %% \label{fig:optimize-jumps}
  9060. %% \end{figure}
  9061. %% The name of this pass is \code{optimize-jumps}. We recommend
  9062. %% implementing this pass in two phases. The first phrase builds a hash
  9063. %% table that maps labels to possibly improved labels. The second phase
  9064. %% changes the target of each \code{goto} to use the improved label. If
  9065. %% the label is for a trivial block, then the hash table should map the
  9066. %% label to the first non-trivial block that can be reached from this
  9067. %% label by jumping through trivial blocks. If the label is for a
  9068. %% non-trivial block, then the hash table should map the label to itself;
  9069. %% we do not want to change jumps to non-trivial blocks.
  9070. %% The first phase can be accomplished by constructing an empty hash
  9071. %% table, call it \code{short-cut}, and then iterating over the control
  9072. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9073. %% then update the hash table, mapping the block's source to the target
  9074. %% of the \code{goto}. Also, the hash table may already have mapped some
  9075. %% labels to the block's source, to you must iterate through the hash
  9076. %% table and update all of those so that they instead map to the target
  9077. %% of the \code{goto}.
  9078. %% For the second phase, we recommend iterating through the $\Tail$ of
  9079. %% each block in the program, updating the target of every \code{goto}
  9080. %% according to the mapping in \code{short-cut}.
  9081. \begin{exercise}\normalfont\normalsize
  9082. Implement the improvements to the \code{explicate\_control} pass.
  9083. Check that it removes trivial blocks in a few example programs. Then
  9084. check that your compiler still passes all your tests.
  9085. \end{exercise}
  9086. \subsection{Remove Jumps}
  9087. There is an opportunity for removing jumps that is apparent in the
  9088. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9089. ends with a jump to \code{block\_5}, and there are no other jumps to
  9090. \code{block\_5} in the rest of the program. In this situation we can
  9091. avoid the runtime overhead of this jump by merging \code{block\_5}
  9092. into the preceding block, which in this case is the \code{start} block.
  9093. Figure~\ref{fig:remove-jumps} shows the output of
  9094. \code{allocate\_registers} on the left and the result of this
  9095. optimization on the right.
  9096. \begin{figure}[tbp]
  9097. \begin{tcolorbox}[colback=white]
  9098. {\if\edition\racketEd
  9099. \begin{tabular}{lll}
  9100. \begin{minipage}{0.5\textwidth}
  9101. % cond_test_82.rkt
  9102. \begin{lstlisting}
  9103. start:
  9104. callq read_int
  9105. movq %rax, %rcx
  9106. jmp block_5
  9107. block_5:
  9108. movq %rcx, %rax
  9109. addq $2, %rax
  9110. jmp conclusion
  9111. \end{lstlisting}
  9112. \end{minipage}
  9113. &
  9114. $\Rightarrow\qquad$
  9115. \begin{minipage}{0.4\textwidth}
  9116. \begin{lstlisting}
  9117. start:
  9118. callq read_int
  9119. movq %rax, %rcx
  9120. movq %rcx, %rax
  9121. addq $2, %rax
  9122. jmp conclusion
  9123. \end{lstlisting}
  9124. \end{minipage}
  9125. \end{tabular}
  9126. \fi}
  9127. {\if\edition\pythonEd
  9128. \begin{tabular}{lll}
  9129. \begin{minipage}{0.5\textwidth}
  9130. % cond_test_20.rkt
  9131. \begin{lstlisting}
  9132. start:
  9133. callq read_int
  9134. movq %rax, tmp_0
  9135. cmpq 1, tmp_0
  9136. je block_3
  9137. jmp block_4
  9138. block_3:
  9139. movq 42, tmp_1
  9140. jmp block_2
  9141. block_4:
  9142. movq 0, tmp_1
  9143. jmp block_2
  9144. block_2:
  9145. movq tmp_1, %rdi
  9146. callq print_int
  9147. movq 0, %rax
  9148. jmp conclusion
  9149. \end{lstlisting}
  9150. \end{minipage}
  9151. &
  9152. $\Rightarrow\qquad$
  9153. \begin{minipage}{0.4\textwidth}
  9154. \begin{lstlisting}
  9155. start:
  9156. callq read_int
  9157. movq %rax, tmp_0
  9158. cmpq 1, tmp_0
  9159. je block_3
  9160. movq 0, tmp_1
  9161. jmp block_2
  9162. block_3:
  9163. movq 42, tmp_1
  9164. jmp block_2
  9165. block_2:
  9166. movq tmp_1, %rdi
  9167. callq print_int
  9168. movq 0, %rax
  9169. jmp conclusion
  9170. \end{lstlisting}
  9171. \end{minipage}
  9172. \end{tabular}
  9173. \fi}
  9174. \end{tcolorbox}
  9175. \caption{Merging basic blocks by removing unnecessary jumps.}
  9176. \label{fig:remove-jumps}
  9177. \end{figure}
  9178. \begin{exercise}\normalfont\normalsize
  9179. %
  9180. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9181. into their preceding basic block, when there is only one preceding
  9182. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9183. %
  9184. {\if\edition\racketEd
  9185. In the \code{run-tests.rkt} script, add the following entry to the
  9186. list of \code{passes} between \code{allocate\_registers}
  9187. and \code{patch\_instructions}:
  9188. \begin{lstlisting}
  9189. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9190. \end{lstlisting}
  9191. \fi}
  9192. %
  9193. Run the script to test your compiler.
  9194. %
  9195. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9196. blocks on several test programs.
  9197. \end{exercise}
  9198. \section{Further Reading}
  9199. \label{sec:cond-further-reading}
  9200. The algorithm for the \code{explicate\_control} pass is based on the
  9201. \code{expose-basic-blocks} pass in the course notes of
  9202. \citet{Dybvig:2010aa}.
  9203. %
  9204. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  9205. \citet{Appel:2003fk}, and is related to translations into continuation
  9206. passing
  9207. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  9208. %
  9209. The treatment of conditionals in the \code{explicate\_control} pass is
  9210. similar to short-cut boolean
  9211. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  9212. and the case-of-case transformation~\citep{PeytonJones:1998}.
  9213. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9214. \chapter{Loops and Dataflow Analysis}
  9215. \label{ch:Lwhile}
  9216. \setcounter{footnote}{0}
  9217. % TODO: define R'_8
  9218. % TODO: multi-graph
  9219. {\if\edition\racketEd
  9220. %
  9221. In this chapter we study two features that are the hallmarks of
  9222. imperative programming languages: loops and assignments to local
  9223. variables. The following example demonstrates these new features by
  9224. computing the sum of the first five positive integers:
  9225. % similar to loop_test_1.rkt
  9226. \begin{lstlisting}
  9227. (let ([sum 0])
  9228. (let ([i 5])
  9229. (begin
  9230. (while (> i 0)
  9231. (begin
  9232. (set! sum (+ sum i))
  9233. (set! i (- i 1))))
  9234. sum)))
  9235. \end{lstlisting}
  9236. The \code{while} loop consists of a condition and a
  9237. body.\footnote{The \code{while} loop is not a built-in
  9238. feature of the Racket language, but Racket includes many looping
  9239. constructs and it is straightforward to define \code{while} as a
  9240. macro.} The body is evaluated repeatedly so long as the condition
  9241. remains true.
  9242. %
  9243. The \code{set!} consists of a variable and a right-hand side
  9244. expression. The \code{set!} updates value of the variable to the
  9245. value of the right-hand side.
  9246. %
  9247. The primary purpose of both the \code{while} loop and \code{set!} is
  9248. to cause side effects, so they do not give a meaningful result
  9249. value. Instead, their result is the \code{\#<void>} value. The
  9250. expression \code{(void)} is an explicit way to create the
  9251. \code{\#<void>} value, and it has type \code{Void}. The
  9252. \code{\#<void>} value can be passed around just like other values
  9253. inside an \LangLoop{} program, and it can be compared for equality with
  9254. another \code{\#<void>} value. However, there are no other operations
  9255. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  9256. Racket defines the \code{void?} predicate that returns \code{\#t}
  9257. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  9258. %
  9259. \footnote{Racket's \code{Void} type corresponds to what is often
  9260. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9261. by a single value \code{\#<void>}, which corresponds to \code{unit}
  9262. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  9263. %
  9264. With the addition of side effect-producing features such as
  9265. \code{while} loop and \code{set!}, it is helpful to include a language
  9266. feature for sequencing side effects: the \code{begin} expression. It
  9267. consists of one or more subexpressions that are evaluated
  9268. left to right.
  9269. %
  9270. \fi}
  9271. {\if\edition\pythonEd
  9272. %
  9273. In this chapter we study loops, one of the hallmarks of imperative
  9274. programming languages. The following example demonstrates the
  9275. \code{while} loop by computing the sum of the first five positive
  9276. integers.
  9277. \begin{lstlisting}
  9278. sum = 0
  9279. i = 5
  9280. while i > 0:
  9281. sum = sum + i
  9282. i = i - 1
  9283. print(sum)
  9284. \end{lstlisting}
  9285. The \code{while} loop consists of a condition expression and a body (a
  9286. sequence of statements). The body is evaluated repeatedly so long as
  9287. the condition remains true.
  9288. %
  9289. \fi}
  9290. \section{The \LangLoop{} Language}
  9291. \newcommand{\LwhileGrammarRacket}{
  9292. \begin{array}{lcl}
  9293. \Type &::=& \key{Void}\\
  9294. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9295. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9296. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9297. \end{array}
  9298. }
  9299. \newcommand{\LwhileASTRacket}{
  9300. \begin{array}{lcl}
  9301. \Type &::=& \key{Void}\\
  9302. \Exp &::=& \SETBANG{\Var}{\Exp}
  9303. \MID \BEGIN{\Exp^{*}}{\Exp}
  9304. \MID \WHILE{\Exp}{\Exp}
  9305. \MID \VOID{}
  9306. \end{array}
  9307. }
  9308. \newcommand{\LwhileGrammarPython}{
  9309. \begin{array}{rcl}
  9310. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9311. \end{array}
  9312. }
  9313. \newcommand{\LwhileASTPython}{
  9314. \begin{array}{lcl}
  9315. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9316. \end{array}
  9317. }
  9318. \begin{figure}[tp]
  9319. \centering
  9320. \begin{tcolorbox}[colback=white]
  9321. \small
  9322. {\if\edition\racketEd
  9323. \[
  9324. \begin{array}{l}
  9325. \gray{\LintGrammarRacket{}} \\ \hline
  9326. \gray{\LvarGrammarRacket{}} \\ \hline
  9327. \gray{\LifGrammarRacket{}} \\ \hline
  9328. \LwhileGrammarRacket \\
  9329. \begin{array}{lcl}
  9330. \LangLoopM{} &::=& \Exp
  9331. \end{array}
  9332. \end{array}
  9333. \]
  9334. \fi}
  9335. {\if\edition\pythonEd
  9336. \[
  9337. \begin{array}{l}
  9338. \gray{\LintGrammarPython} \\ \hline
  9339. \gray{\LvarGrammarPython} \\ \hline
  9340. \gray{\LifGrammarPython} \\ \hline
  9341. \LwhileGrammarPython \\
  9342. \begin{array}{rcl}
  9343. \LangLoopM{} &::=& \Stmt^{*}
  9344. \end{array}
  9345. \end{array}
  9346. \]
  9347. \fi}
  9348. \end{tcolorbox}
  9349. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  9350. \label{fig:Lwhile-concrete-syntax}
  9351. \end{figure}
  9352. \begin{figure}[tp]
  9353. \centering
  9354. \begin{tcolorbox}[colback=white]
  9355. \small
  9356. {\if\edition\racketEd
  9357. \[
  9358. \begin{array}{l}
  9359. \gray{\LintOpAST} \\ \hline
  9360. \gray{\LvarASTRacket{}} \\ \hline
  9361. \gray{\LifASTRacket{}} \\ \hline
  9362. \LwhileASTRacket{} \\
  9363. \begin{array}{lcl}
  9364. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9365. \end{array}
  9366. \end{array}
  9367. \]
  9368. \fi}
  9369. {\if\edition\pythonEd
  9370. \[
  9371. \begin{array}{l}
  9372. \gray{\LintASTPython} \\ \hline
  9373. \gray{\LvarASTPython} \\ \hline
  9374. \gray{\LifASTPython} \\ \hline
  9375. \LwhileASTPython \\
  9376. \begin{array}{lcl}
  9377. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9378. \end{array}
  9379. \end{array}
  9380. \]
  9381. \fi}
  9382. \end{tcolorbox}
  9383. \python{
  9384. \index{subject}{While@\texttt{While}}
  9385. }
  9386. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  9387. \label{fig:Lwhile-syntax}
  9388. \end{figure}
  9389. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  9390. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  9391. shows the definition of its abstract syntax.
  9392. %
  9393. The definitional interpreter for \LangLoop{} is shown in
  9394. figure~\ref{fig:interp-Lwhile}.
  9395. %
  9396. {\if\edition\racketEd
  9397. %
  9398. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9399. and \code{Void}, and we make changes to the cases for \code{Var} and
  9400. \code{Let} regarding variables. To support assignment to variables and
  9401. to make their lifetimes indefinite (see the second example in
  9402. section~\ref{sec:assignment-scoping}), we box the value that is bound
  9403. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9404. value.
  9405. %
  9406. Now we discuss the new cases. For \code{SetBang}, we find the
  9407. variable in the environment to obtain a boxed value, and then we change
  9408. it using \code{set-box!} to the result of evaluating the right-hand
  9409. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9410. %
  9411. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  9412. if the result is true, (2) evaluate the body.
  9413. The result value of a \code{while} loop is also \code{\#<void>}.
  9414. %
  9415. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9416. subexpressions \itm{es} for their effects and then evaluates
  9417. and returns the result from \itm{body}.
  9418. %
  9419. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9420. %
  9421. \fi}
  9422. {\if\edition\pythonEd
  9423. %
  9424. We add a new case for \code{While} in the \code{interp\_stmts}
  9425. function, where we repeatedly interpret the \code{body} so long as the
  9426. \code{test} expression remains true.
  9427. %
  9428. \fi}
  9429. \begin{figure}[tbp]
  9430. \begin{tcolorbox}[colback=white]
  9431. {\if\edition\racketEd
  9432. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9433. (define interp-Lwhile-class
  9434. (class interp-Lif-class
  9435. (super-new)
  9436. (define/override ((interp-exp env) e)
  9437. (define recur (interp-exp env))
  9438. (match e
  9439. [(Let x e body)
  9440. (define new-env (dict-set env x (box (recur e))))
  9441. ((interp-exp new-env) body)]
  9442. [(Var x) (unbox (dict-ref env x))]
  9443. [(SetBang x rhs)
  9444. (set-box! (dict-ref env x) (recur rhs))]
  9445. [(WhileLoop cnd body)
  9446. (define (loop)
  9447. (cond [(recur cnd) (recur body) (loop)]
  9448. [else (void)]))
  9449. (loop)]
  9450. [(Begin es body)
  9451. (for ([e es]) (recur e))
  9452. (recur body)]
  9453. [(Void) (void)]
  9454. [else ((super interp-exp env) e)]))
  9455. ))
  9456. (define (interp-Lwhile p)
  9457. (send (new interp-Lwhile-class) interp-program p))
  9458. \end{lstlisting}
  9459. \fi}
  9460. {\if\edition\pythonEd
  9461. \begin{lstlisting}
  9462. class InterpLwhile(InterpLif):
  9463. def interp_stmts(self, ss, env):
  9464. if len(ss) == 0:
  9465. return
  9466. match ss[0]:
  9467. case While(test, body, []):
  9468. while self.interp_exp(test, env):
  9469. self.interp_stmts(body, env)
  9470. return self.interp_stmts(ss[1:], env)
  9471. case _:
  9472. return super().interp_stmts(ss, env)
  9473. \end{lstlisting}
  9474. \fi}
  9475. \end{tcolorbox}
  9476. \caption{Interpreter for \LangLoop{}.}
  9477. \label{fig:interp-Lwhile}
  9478. \end{figure}
  9479. The definition of the type checker for \LangLoop{} is shown in
  9480. figure~\ref{fig:type-check-Lwhile}.
  9481. %
  9482. {\if\edition\racketEd
  9483. %
  9484. The type checking of the \code{SetBang} expression requires the type
  9485. of the variable and the right-hand side to agree. The result type is
  9486. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  9487. and the result type is \code{Void}. For \code{Begin}, the result type
  9488. is the type of its last subexpression.
  9489. %
  9490. \fi}
  9491. %
  9492. {\if\edition\pythonEd
  9493. %
  9494. A \code{while} loop is well typed if the type of the \code{test}
  9495. expression is \code{bool} and the statements in the \code{body} are
  9496. well typed.
  9497. %
  9498. \fi}
  9499. \begin{figure}[tbp]
  9500. \begin{tcolorbox}[colback=white]
  9501. {\if\edition\racketEd
  9502. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9503. (define type-check-Lwhile-class
  9504. (class type-check-Lif-class
  9505. (super-new)
  9506. (inherit check-type-equal?)
  9507. (define/override (type-check-exp env)
  9508. (lambda (e)
  9509. (define recur (type-check-exp env))
  9510. (match e
  9511. [(SetBang x rhs)
  9512. (define-values (rhs^ rhsT) (recur rhs))
  9513. (define varT (dict-ref env x))
  9514. (check-type-equal? rhsT varT e)
  9515. (values (SetBang x rhs^) 'Void)]
  9516. [(WhileLoop cnd body)
  9517. (define-values (cnd^ Tc) (recur cnd))
  9518. (check-type-equal? Tc 'Boolean e)
  9519. (define-values (body^ Tbody) ((type-check-exp env) body))
  9520. (values (WhileLoop cnd^ body^) 'Void)]
  9521. [(Begin es body)
  9522. (define-values (es^ ts)
  9523. (for/lists (l1 l2) ([e es]) (recur e)))
  9524. (define-values (body^ Tbody) (recur body))
  9525. (values (Begin es^ body^) Tbody)]
  9526. [else ((super type-check-exp env) e)])))
  9527. ))
  9528. (define (type-check-Lwhile p)
  9529. (send (new type-check-Lwhile-class) type-check-program p))
  9530. \end{lstlisting}
  9531. \fi}
  9532. {\if\edition\pythonEd
  9533. \begin{lstlisting}
  9534. class TypeCheckLwhile(TypeCheckLif):
  9535. def type_check_stmts(self, ss, env):
  9536. if len(ss) == 0:
  9537. return
  9538. match ss[0]:
  9539. case While(test, body, []):
  9540. test_t = self.type_check_exp(test, env)
  9541. check_type_equal(bool, test_t, test)
  9542. body_t = self.type_check_stmts(body, env)
  9543. return self.type_check_stmts(ss[1:], env)
  9544. case _:
  9545. return super().type_check_stmts(ss, env)
  9546. \end{lstlisting}
  9547. \fi}
  9548. \end{tcolorbox}
  9549. \caption{Type checker for the \LangLoop{} language.}
  9550. \label{fig:type-check-Lwhile}
  9551. \end{figure}
  9552. {\if\edition\racketEd
  9553. %
  9554. At first glance, the translation of these language features to x86
  9555. seems straightforward because the \LangCIf{} intermediate language
  9556. already supports all the ingredients that we need: assignment,
  9557. \code{goto}, conditional branching, and sequencing. However, there are
  9558. complications that arise, which we discuss in the next section. After
  9559. that we introduce the changes necessary to the existing passes.
  9560. %
  9561. \fi}
  9562. {\if\edition\pythonEd
  9563. %
  9564. At first glance, the translation of \code{while} loops to x86 seems
  9565. straightforward because the \LangCIf{} intermediate language already
  9566. supports \code{goto} and conditional branching. However, there are
  9567. complications that arise which we discuss in the next section. After
  9568. that we introduce the changes necessary to the existing passes.
  9569. %
  9570. \fi}
  9571. \section{Cyclic Control Flow and Dataflow Analysis}
  9572. \label{sec:dataflow-analysis}
  9573. Up until this point, the programs generated in
  9574. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9575. \code{while} loop introduces a cycle. Does that matter?
  9576. %
  9577. Indeed, it does. Recall that for register allocation, the compiler
  9578. performs liveness analysis to determine which variables can share the
  9579. same register. To accomplish this, we analyzed the control-flow graph
  9580. in reverse topological order
  9581. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9582. well defined only for acyclic graphs.
  9583. Let us return to the example of computing the sum of the first five
  9584. positive integers. Here is the program after instruction selection but
  9585. before register allocation.
  9586. \begin{center}
  9587. {\if\edition\racketEd
  9588. \begin{minipage}{0.45\textwidth}
  9589. \begin{lstlisting}
  9590. (define (main) : Integer
  9591. mainstart:
  9592. movq $0, sum
  9593. movq $5, i
  9594. jmp block5
  9595. block5:
  9596. movq i, tmp3
  9597. cmpq tmp3, $0
  9598. jl block7
  9599. jmp block8
  9600. \end{lstlisting}
  9601. \end{minipage}
  9602. \begin{minipage}{0.45\textwidth}
  9603. \begin{lstlisting}
  9604. block7:
  9605. addq i, sum
  9606. movq $1, tmp4
  9607. negq tmp4
  9608. addq tmp4, i
  9609. jmp block5
  9610. block8:
  9611. movq $27, %rax
  9612. addq sum, %rax
  9613. jmp mainconclusion
  9614. )
  9615. \end{lstlisting}
  9616. \end{minipage}
  9617. \fi}
  9618. {\if\edition\pythonEd
  9619. \begin{minipage}{0.45\textwidth}
  9620. \begin{lstlisting}
  9621. mainstart:
  9622. movq $0, sum
  9623. movq $5, i
  9624. jmp block5
  9625. block5:
  9626. cmpq $0, i
  9627. jg block7
  9628. jmp block8
  9629. \end{lstlisting}
  9630. \end{minipage}
  9631. \begin{minipage}{0.45\textwidth}
  9632. \begin{lstlisting}
  9633. block7:
  9634. addq i, sum
  9635. subq $1, i
  9636. jmp block5
  9637. block8:
  9638. movq sum, %rdi
  9639. callq print_int
  9640. movq $0, %rax
  9641. jmp mainconclusion
  9642. \end{lstlisting}
  9643. \end{minipage}
  9644. \fi}
  9645. \end{center}
  9646. Recall that liveness analysis works backward, starting at the end
  9647. of each function. For this example we could start with \code{block8}
  9648. because we know what is live at the beginning of the conclusion:
  9649. only \code{rax} and \code{rsp}. So the live-before set
  9650. for \code{block8} is \code{\{rsp,sum\}}.
  9651. %
  9652. Next we might try to analyze \code{block5} or \code{block7}, but
  9653. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9654. we are stuck.
  9655. The way out of this impasse is to realize that we can compute an
  9656. underapproximation of each live-before set by starting with empty
  9657. live-after sets. By \emph{underapproximation}, we mean that the set
  9658. contains only variables that are live for some execution of the
  9659. program, but the set may be missing some variables that are live.
  9660. Next, the underapproximations for each block can be improved by (1)
  9661. updating the live-after set for each block using the approximate
  9662. live-before sets from the other blocks, and (2) performing liveness
  9663. analysis again on each block. In fact, by iterating this process, the
  9664. underapproximations eventually become the correct solutions!
  9665. %
  9666. This approach of iteratively analyzing a control-flow graph is
  9667. applicable to many static analysis problems and goes by the name
  9668. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9669. \citet{Kildall:1973vn} in his PhD thesis at the University of
  9670. Washington.
  9671. Let us apply this approach to the previously presented example. We use
  9672. the empty set for the initial live-before set for each block. Let
  9673. $m_0$ be the following mapping from label names to sets of locations
  9674. (variables and registers):
  9675. \begin{center}
  9676. \begin{lstlisting}
  9677. mainstart: {}, block5: {}, block7: {}, block8: {}
  9678. \end{lstlisting}
  9679. \end{center}
  9680. Using the above live-before approximations, we determine the
  9681. live-after for each block and then apply liveness analysis to each
  9682. block. This produces our next approximation $m_1$ of the live-before
  9683. sets.
  9684. \begin{center}
  9685. \begin{lstlisting}
  9686. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9687. \end{lstlisting}
  9688. \end{center}
  9689. For the second round, the live-after for \code{mainstart} is the
  9690. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  9691. the liveness analysis for \code{mainstart} computes the empty set. The
  9692. live-after for \code{block5} is the union of the live-before sets for
  9693. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9694. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9695. sum\}}. The live-after for \code{block7} is the live-before for
  9696. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9697. So the liveness analysis for \code{block7} remains \code{\{i,
  9698. sum\}}. Together these yield the following approximation $m_2$ of
  9699. the live-before sets:
  9700. \begin{center}
  9701. \begin{lstlisting}
  9702. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9703. \end{lstlisting}
  9704. \end{center}
  9705. In the preceding iteration, only \code{block5} changed, so we can
  9706. limit our attention to \code{mainstart} and \code{block7}, the two
  9707. blocks that jump to \code{block5}. As a result, the live-before sets
  9708. for \code{mainstart} and \code{block7} are updated to include
  9709. \code{rsp}, yielding the following approximation $m_3$:
  9710. \begin{center}
  9711. \begin{lstlisting}
  9712. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9713. \end{lstlisting}
  9714. \end{center}
  9715. Because \code{block7} changed, we analyze \code{block5} once more, but
  9716. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9717. our approximations have converged, so $m_3$ is the solution.
  9718. This iteration process is guaranteed to converge to a solution by the
  9719. Kleene fixed-point theorem, a general theorem about functions on
  9720. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9721. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9722. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  9723. join operator
  9724. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9725. ordering}\index{subject}{join}\footnote{Technically speaking, we
  9726. will be working with join semilattices.} When two elements are
  9727. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  9728. as much information as $m_i$, so we can think of $m_j$ as a
  9729. better-than-or-equal-to approximation in relation to $m_i$. The
  9730. bottom element $\bot$ represents the complete lack of information,
  9731. that is, the worst approximation. The join operator takes two lattice
  9732. elements and combines their information; that is, it produces the
  9733. least upper bound of the two.\index{subject}{least upper bound}
  9734. A dataflow analysis typically involves two lattices: one lattice to
  9735. represent abstract states and another lattice that aggregates the
  9736. abstract states of all the blocks in the control-flow graph. For
  9737. liveness analysis, an abstract state is a set of locations. We form
  9738. the lattice $L$ by taking its elements to be sets of locations, the
  9739. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9740. set, and the join operator to be set union.
  9741. %
  9742. We form a second lattice $M$ by taking its elements to be mappings
  9743. from the block labels to sets of locations (elements of $L$). We
  9744. order the mappings point-wise, using the ordering of $L$. So, given any
  9745. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9746. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9747. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9748. to the empty set; that is, $\bot_M(\ell) = \emptyset$.
  9749. We can think of one iteration of liveness analysis applied to the
  9750. whole program as being a function $f$ on the lattice $M$. It takes a
  9751. mapping as input and computes a new mapping.
  9752. \[
  9753. f(m_i) = m_{i+1}
  9754. \]
  9755. Next let us think for a moment about what a final solution $m_s$
  9756. should look like. If we perform liveness analysis using the solution
  9757. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9758. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9759. \[
  9760. f(m_s) = m_s
  9761. \]
  9762. Furthermore, the solution should include only locations that are
  9763. forced to be there by performing liveness analysis on the program, so
  9764. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9765. The Kleene fixed-point theorem states that if a function $f$ is
  9766. monotone (better inputs produce better outputs), then the least fixed
  9767. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9768. chain} obtained by starting at $\bot$ and iterating $f$, as
  9769. follows:\index{subject}{Kleene fixed-point theorem}
  9770. \[
  9771. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9772. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9773. \]
  9774. When a lattice contains only finitely long ascending chains, then
  9775. every Kleene chain tops out at some fixed point after some number of
  9776. iterations of $f$.
  9777. \[
  9778. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9779. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9780. \]
  9781. The liveness analysis is indeed a monotone function and the lattice
  9782. $M$ has finitely long ascending chains because there are only a
  9783. finite number of variables and blocks in the program. Thus we are
  9784. guaranteed that iteratively applying liveness analysis to all blocks
  9785. in the program will eventually produce the least fixed point solution.
  9786. Next let us consider dataflow analysis in general and discuss the
  9787. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  9788. %
  9789. The algorithm has four parameters: the control-flow graph \code{G}, a
  9790. function \code{transfer} that applies the analysis to one block, and the
  9791. \code{bottom} and \code{join} operators for the lattice of abstract
  9792. states. The \code{analyze\_dataflow} function is formulated as a
  9793. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  9794. function come from the predecessor nodes in the control-flow
  9795. graph. However, liveness analysis is a \emph{backward} dataflow
  9796. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9797. function with the transpose of the control-flow graph.
  9798. The algorithm begins by creating the bottom mapping, represented by a
  9799. hash table. It then pushes all the nodes in the control-flow graph
  9800. onto the work list (a queue). The algorithm repeats the \code{while}
  9801. loop as long as there are items in the work list. In each iteration, a
  9802. node is popped from the work list and processed. The \code{input} for
  9803. the node is computed by taking the join of the abstract states of all
  9804. the predecessor nodes. The \code{transfer} function is then applied to
  9805. obtain the \code{output} abstract state. If the output differs from
  9806. the previous state for this block, the mapping for this block is
  9807. updated and its successor nodes are pushed onto the work list.
  9808. \begin{figure}[tb]
  9809. \begin{tcolorbox}[colback=white]
  9810. {\if\edition\racketEd
  9811. \begin{lstlisting}
  9812. (define (analyze_dataflow G transfer bottom join)
  9813. (define mapping (make-hash))
  9814. (for ([v (in-vertices G)])
  9815. (dict-set! mapping v bottom))
  9816. (define worklist (make-queue))
  9817. (for ([v (in-vertices G)])
  9818. (enqueue! worklist v))
  9819. (define trans-G (transpose G))
  9820. (while (not (queue-empty? worklist))
  9821. (define node (dequeue! worklist))
  9822. (define input (for/fold ([state bottom])
  9823. ([pred (in-neighbors trans-G node)])
  9824. (join state (dict-ref mapping pred))))
  9825. (define output (transfer node input))
  9826. (cond [(not (equal? output (dict-ref mapping node)))
  9827. (dict-set! mapping node output)
  9828. (for ([v (in-neighbors G node)])
  9829. (enqueue! worklist v))]))
  9830. mapping)
  9831. \end{lstlisting}
  9832. \fi}
  9833. {\if\edition\pythonEd
  9834. \begin{lstlisting}
  9835. def analyze_dataflow(G, transfer, bottom, join):
  9836. trans_G = transpose(G)
  9837. mapping = dict((v, bottom) for v in G.vertices())
  9838. worklist = deque(G.vertices)
  9839. while worklist:
  9840. node = worklist.pop()
  9841. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  9842. input = reduce(join, inputs, bottom)
  9843. output = transfer(node, input)
  9844. if output != mapping[node]:
  9845. mapping[node] = output
  9846. worklist.extend(G.adjacent(node))
  9847. \end{lstlisting}
  9848. \fi}
  9849. \end{tcolorbox}
  9850. \caption{Generic work list algorithm for dataflow analysis}
  9851. \label{fig:generic-dataflow}
  9852. \end{figure}
  9853. {\if\edition\racketEd
  9854. \section{Mutable Variables and Remove Complex Operands}
  9855. There is a subtle interaction between the
  9856. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9857. and the left-to-right order of evaluation of Racket. Consider the
  9858. following example:
  9859. \begin{lstlisting}
  9860. (let ([x 2])
  9861. (+ x (begin (set! x 40) x)))
  9862. \end{lstlisting}
  9863. The result of this program is \code{42} because the first read from
  9864. \code{x} produces \code{2} and the second produces \code{40}. However,
  9865. if we naively apply the \code{remove\_complex\_operands} pass to this
  9866. example we obtain the following program whose result is \code{80}!
  9867. \begin{lstlisting}
  9868. (let ([x 2])
  9869. (let ([tmp (begin (set! x 40) x)])
  9870. (+ x tmp)))
  9871. \end{lstlisting}
  9872. The problem is that with mutable variables, the ordering between
  9873. reads and writes is important, and the
  9874. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9875. before the first read of \code{x}.
  9876. We recommend solving this problem by giving special treatment to reads
  9877. from mutable variables, that is, variables that occur on the left-hand
  9878. side of a \code{set!}. We mark each read from a mutable variable with
  9879. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9880. that the read operation is effectful in that it can produce different
  9881. results at different points in time. Let's apply this idea to the
  9882. following variation that also involves a variable that is not mutated:
  9883. % loop_test_24.rkt
  9884. \begin{lstlisting}
  9885. (let ([x 2])
  9886. (let ([y 0])
  9887. (+ y (+ x (begin (set! x 40) x)))))
  9888. \end{lstlisting}
  9889. We first analyze this program to discover that variable \code{x}
  9890. is mutable but \code{y} is not. We then transform the program as
  9891. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  9892. \begin{lstlisting}
  9893. (let ([x 2])
  9894. (let ([y 0])
  9895. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9896. \end{lstlisting}
  9897. Now that we have a clear distinction between reads from mutable and
  9898. immutable variables, we can apply the \code{remove\_complex\_operands}
  9899. pass, where reads from immutable variables are still classified as
  9900. atomic expressions but reads from mutable variables are classified as
  9901. complex. Thus, \code{remove\_complex\_operands} yields the following
  9902. program:\\
  9903. \begin{minipage}{\textwidth}
  9904. \begin{lstlisting}
  9905. (let ([x 2])
  9906. (let ([y 0])
  9907. (+ y (let ([t1 (get! x)])
  9908. (let ([t2 (begin (set! x 40) (get! x))])
  9909. (+ t1 t2))))))
  9910. \end{lstlisting}
  9911. \end{minipage}
  9912. The temporary variable \code{t1} gets the value of \code{x} before the
  9913. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9914. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9915. do not generate a temporary variable for the occurrence of \code{y}
  9916. because it's an immutable variable. We want to avoid such unnecessary
  9917. extra temporaries because they would needless increase the number of
  9918. variables, making it more likely for some of them to be spilled. The
  9919. result of this program is \code{42}, the same as the result prior to
  9920. \code{remove\_complex\_operands}.
  9921. The approach that we've sketched requires only a small
  9922. modification to \code{remove\_complex\_operands} to handle
  9923. \code{get!}. However, it requires a new pass, called
  9924. \code{uncover-get!}, that we discuss in
  9925. section~\ref{sec:uncover-get-bang}.
  9926. As an aside, this problematic interaction between \code{set!} and the
  9927. pass \code{remove\_complex\_operands} is particular to Racket and not
  9928. its predecessor, the Scheme language. The key difference is that
  9929. Scheme does not specify an order of evaluation for the arguments of an
  9930. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9931. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9932. would be correct results for the example program. Interestingly,
  9933. Racket is implemented on top of the Chez Scheme
  9934. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9935. presented in this section (using extra \code{let} bindings to control
  9936. the order of evaluation) is used in the translation from Racket to
  9937. Scheme~\citep{Flatt:2019tb}.
  9938. \fi} % racket
  9939. Having discussed the complications that arise from adding support for
  9940. assignment and loops, we turn to discussing the individual compilation
  9941. passes.
  9942. {\if\edition\racketEd
  9943. \section{Uncover \texttt{get!}}
  9944. \label{sec:uncover-get-bang}
  9945. The goal of this pass is to mark uses of mutable variables so that
  9946. \code{remove\_complex\_operands} can treat them as complex expressions
  9947. and thereby preserve their ordering relative to the side effects in
  9948. other operands. So, the first step is to collect all the mutable
  9949. variables. We recommend creating an auxiliary function for this,
  9950. named \code{collect-set!}, that recursively traverses expressions,
  9951. returning the set of all variables that occur on the left-hand side of a
  9952. \code{set!}. Here's an excerpt of its implementation.
  9953. \begin{center}
  9954. \begin{minipage}{\textwidth}
  9955. \begin{lstlisting}
  9956. (define (collect-set! e)
  9957. (match e
  9958. [(Var x) (set)]
  9959. [(Int n) (set)]
  9960. [(Let x rhs body)
  9961. (set-union (collect-set! rhs) (collect-set! body))]
  9962. [(SetBang var rhs)
  9963. (set-union (set var) (collect-set! rhs))]
  9964. ...))
  9965. \end{lstlisting}
  9966. \end{minipage}
  9967. \end{center}
  9968. By placing this pass after \code{uniquify}, we need not worry about
  9969. variable shadowing, and our logic for \code{Let} can remain simple, as
  9970. in this excerpt.
  9971. The second step is to mark the occurrences of the mutable variables
  9972. with the new \code{GetBang} AST node (\code{get!} in concrete
  9973. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9974. function, which takes two parameters: the set of mutable variables
  9975. \code{set!-vars} and the expression \code{e} to be processed. The
  9976. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9977. mutable variable or leaves it alone if not.
  9978. \begin{center}
  9979. \begin{minipage}{\textwidth}
  9980. \begin{lstlisting}
  9981. (define ((uncover-get!-exp set!-vars) e)
  9982. (match e
  9983. [(Var x)
  9984. (if (set-member? set!-vars x)
  9985. (GetBang x)
  9986. (Var x))]
  9987. ...))
  9988. \end{lstlisting}
  9989. \end{minipage}
  9990. \end{center}
  9991. To wrap things up, define the \code{uncover-get!} function for
  9992. processing a whole program, using \code{collect-set!} to obtain the
  9993. set of mutable variables and then \code{uncover-get!-exp} to replace
  9994. their occurrences with \code{GetBang}.
  9995. \fi}
  9996. \section{Remove Complex Operands}
  9997. \label{sec:rco-loop}
  9998. {\if\edition\racketEd
  9999. %
  10000. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10001. \code{while} are all complex expressions. The subexpressions of
  10002. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10003. %
  10004. \fi}
  10005. {\if\edition\pythonEd
  10006. %
  10007. The change needed for this pass is to add a case for the \code{while}
  10008. statement. The condition of a \code{while} loop is allowed to be a
  10009. complex expression, just like the condition of the \code{if}
  10010. statement.
  10011. %
  10012. \fi}
  10013. %
  10014. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10015. \LangLoopANF{} of this pass.
  10016. \newcommand{\LwhileMonadASTRacket}{
  10017. \begin{array}{rcl}
  10018. \Atm &::=& \VOID{} \\
  10019. \Exp &::=& \GETBANG{\Var}
  10020. \MID \SETBANG{\Var}{\Exp}
  10021. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10022. &\MID& \WHILE{\Exp}{\Exp}
  10023. \end{array}
  10024. }
  10025. \newcommand{\LwhileMonadASTPython}{
  10026. \begin{array}{rcl}
  10027. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10028. \end{array}
  10029. }
  10030. \begin{figure}[tp]
  10031. \centering
  10032. \begin{tcolorbox}[colback=white]
  10033. \small
  10034. {\if\edition\racketEd
  10035. \[
  10036. \begin{array}{l}
  10037. \gray{\LvarMonadASTRacket} \\ \hline
  10038. \gray{\LifMonadASTRacket} \\ \hline
  10039. \LwhileMonadASTRacket \\
  10040. \begin{array}{rcl}
  10041. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10042. \end{array}
  10043. \end{array}
  10044. \]
  10045. \fi}
  10046. {\if\edition\pythonEd
  10047. \[
  10048. \begin{array}{l}
  10049. \gray{\LvarMonadASTPython} \\ \hline
  10050. \gray{\LifMonadASTPython} \\ \hline
  10051. \LwhileMonadASTPython \\
  10052. \begin{array}{rcl}
  10053. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10054. \end{array}
  10055. \end{array}
  10056. %% \begin{array}{rcl}
  10057. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  10058. %% \Exp &::=& \Atm \MID \READ{} \\
  10059. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  10060. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  10061. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  10062. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10063. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10064. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  10065. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10066. %% \end{array}
  10067. \]
  10068. \fi}
  10069. \end{tcolorbox}
  10070. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10071. \label{fig:Lwhile-anf-syntax}
  10072. \end{figure}
  10073. {\if\edition\racketEd
  10074. %
  10075. As usual, when a complex expression appears in a grammar position that
  10076. needs to be atomic, such as the argument of a primitive operator, we
  10077. must introduce a temporary variable and bind it to the complex
  10078. expression. This approach applies, unchanged, to handle the new
  10079. language forms. For example, in the following code there are two
  10080. \code{begin} expressions appearing as arguments to the \code{+}
  10081. operator. The output of \code{rco\_exp} is then shown, in which the
  10082. \code{begin} expressions have been bound to temporary
  10083. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10084. allowed to have arbitrary expressions in their right-hand side
  10085. expression, so it is fine to place \code{begin} there.
  10086. %
  10087. \begin{center}
  10088. \begin{tabular}{lcl}
  10089. \begin{minipage}{0.4\textwidth}
  10090. \begin{lstlisting}
  10091. (let ([x2 10])
  10092. (let ([y3 0])
  10093. (+ (+ (begin
  10094. (set! y3 (read))
  10095. (get! x2))
  10096. (begin
  10097. (set! x2 (read))
  10098. (get! y3)))
  10099. (get! x2))))
  10100. \end{lstlisting}
  10101. \end{minipage}
  10102. &
  10103. $\Rightarrow$
  10104. &
  10105. \begin{minipage}{0.4\textwidth}
  10106. \begin{lstlisting}
  10107. (let ([x2 10])
  10108. (let ([y3 0])
  10109. (let ([tmp4 (begin
  10110. (set! y3 (read))
  10111. x2)])
  10112. (let ([tmp5 (begin
  10113. (set! x2 (read))
  10114. y3)])
  10115. (let ([tmp6 (+ tmp4 tmp5)])
  10116. (let ([tmp7 x2])
  10117. (+ tmp6 tmp7)))))))
  10118. \end{lstlisting}
  10119. \end{minipage}
  10120. \end{tabular}
  10121. \end{center}
  10122. \fi}
  10123. \section{Explicate Control \racket{and \LangCLoop{}}}
  10124. \label{sec:explicate-loop}
  10125. \newcommand{\CloopASTRacket}{
  10126. \begin{array}{lcl}
  10127. \Atm &::=& \VOID \\
  10128. \Stmt &::=& \READ{}
  10129. \end{array}
  10130. }
  10131. {\if\edition\racketEd
  10132. Recall that in the \code{explicate\_control} pass we define one helper
  10133. function for each kind of position in the program. For the \LangVar{}
  10134. language of integers and variables, we needed assignment and tail
  10135. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10136. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10137. another kind of position: effect position. Except for the last
  10138. subexpression, the subexpressions inside a \code{begin} are evaluated
  10139. only for their effect. Their result values are discarded. We can
  10140. generate better code by taking this fact into account.
  10141. The output language of \code{explicate\_control} is \LangCLoop{}
  10142. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10143. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10144. and that \code{read} may appear as a statement. The most significant
  10145. difference between the programs generated by \code{explicate\_control}
  10146. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10147. chapter is that the control-flow graphs of the latter may contain
  10148. cycles.
  10149. \begin{figure}[tp]
  10150. \begin{tcolorbox}[colback=white]
  10151. \small
  10152. \[
  10153. \begin{array}{l}
  10154. \gray{\CvarASTRacket} \\ \hline
  10155. \gray{\CifASTRacket} \\ \hline
  10156. \CloopASTRacket \\
  10157. \begin{array}{lcl}
  10158. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10159. \end{array}
  10160. \end{array}
  10161. \]
  10162. \end{tcolorbox}
  10163. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10164. \label{fig:c7-syntax}
  10165. \end{figure}
  10166. The new auxiliary function \code{explicate\_effect} takes an
  10167. expression (in an effect position) and the code for its
  10168. continuation. The function returns a $\Tail$ that includes the
  10169. generated code for the input expression followed by the
  10170. continuation. If the expression is obviously pure, that is, never
  10171. causes side effects, then the expression can be removed, so the result
  10172. is just the continuation.
  10173. %
  10174. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10175. interesting; the generated code is depicted in the following diagram:
  10176. \begin{center}
  10177. \begin{minipage}{0.3\textwidth}
  10178. \xymatrix{
  10179. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10180. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10181. & *+[F]{\txt{\itm{cont}}} \\
  10182. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10183. }
  10184. \end{minipage}
  10185. \end{center}
  10186. We start by creating a fresh label $\itm{loop}$ for the top of the
  10187. loop. Next, recursively process the \itm{body} (in effect position)
  10188. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10189. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10190. \itm{body'} as the \emph{then} branch and the continuation block as the
  10191. \emph{else} branch. The result should be added to the dictionary of
  10192. \code{basic-blocks} with the label \itm{loop}. The result for the
  10193. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10194. The auxiliary functions for tail, assignment, and predicate positions
  10195. need to be updated. The three new language forms, \code{while},
  10196. \code{set!}, and \code{begin}, can appear in assignment and tail
  10197. positions. Only \code{begin} may appear in predicate positions; the
  10198. other two have result type \code{Void}.
  10199. \fi}
  10200. %
  10201. {\if\edition\pythonEd
  10202. %
  10203. The output of this pass is the language \LangCIf{}. No new language
  10204. features are needed in the output because a \code{while} loop can be
  10205. expressed in terms of \code{goto} and \code{if} statements, which are
  10206. already in \LangCIf{}.
  10207. %
  10208. Add a case for the \code{while} statement to the
  10209. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10210. the condition expression.
  10211. %
  10212. \fi}
  10213. {\if\edition\racketEd
  10214. \section{Select Instructions}
  10215. \label{sec:select-instructions-loop}
  10216. Only two small additions are needed in the \code{select\_instructions}
  10217. pass to handle the changes to \LangCLoop{}. First, to handle the
  10218. addition of \VOID{} we simply translate it to \code{0}. Second,
  10219. \code{read} may appear as a stand-alone statement instead of
  10220. appearing only on the right-hand side of an assignment statement. The code
  10221. generation is nearly identical to the one for assignment; just leave
  10222. off the instruction for moving the result into the left-hand side.
  10223. \fi}
  10224. \section{Register Allocation}
  10225. \label{sec:register-allocation-loop}
  10226. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  10227. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  10228. which complicates the liveness analysis needed for register
  10229. allocation.
  10230. %
  10231. We recommend using the generic \code{analyze\_dataflow} function that
  10232. was presented at the end of section~\ref{sec:dataflow-analysis} to
  10233. perform liveness analysis, replacing the code in
  10234. \code{uncover\_live} that processed the basic blocks in topological
  10235. order (section~\ref{sec:liveness-analysis-Lif}).
  10236. The \code{analyze\_dataflow} function has the following four parameters.
  10237. \begin{enumerate}
  10238. \item The first parameter \code{G} should be passed the transpose
  10239. of the control-flow graph.
  10240. \item The second parameter \code{transfer} should be passed a function
  10241. that applies liveness analysis to a basic block. It takes two
  10242. parameters: the label for the block to analyze and the live-after
  10243. set for that block. The transfer function should return the
  10244. live-before set for the block.
  10245. %
  10246. \racket{Also, as a side effect, it should update the block's
  10247. $\itm{info}$ with the liveness information for each instruction.}
  10248. %
  10249. \python{Also, as a side-effect, it should update the live-before and
  10250. live-after sets for each instruction.}
  10251. %
  10252. To implement the \code{transfer} function, you should be able to
  10253. reuse the code you already have for analyzing basic blocks.
  10254. \item The third and fourth parameters of \code{analyze\_dataflow} are
  10255. \code{bottom} and \code{join} for the lattice of abstract states,
  10256. that is, sets of locations. For liveness analysis, the bottom of the
  10257. lattice is the empty set, and the join operator is set union.
  10258. \end{enumerate}
  10259. \begin{figure}[p]
  10260. \begin{tcolorbox}[colback=white]
  10261. {\if\edition\racketEd
  10262. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10263. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10264. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10265. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10266. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10267. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  10268. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10269. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10270. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  10271. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  10272. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10273. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10274. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  10275. \path[->,bend left=15] (Lfun) edge [above] node
  10276. {\ttfamily\footnotesize shrink} (Lfun-2);
  10277. \path[->,bend left=15] (Lfun-2) edge [above] node
  10278. {\ttfamily\footnotesize uniquify} (F1-4);
  10279. \path[->,bend left=15] (F1-4) edge [above] node
  10280. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10281. \path[->,bend left=15] (F1-5) edge [left] node
  10282. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10283. \path[->,bend left=10] (F1-6) edge [above] node
  10284. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10285. \path[->,bend left=15] (C3-2) edge [right] node
  10286. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10287. \path[->,bend right=15] (x86-2) edge [right] node
  10288. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10289. \path[->,bend right=15] (x86-2-1) edge [below] node
  10290. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  10291. \path[->,bend right=15] (x86-2-2) edge [right] node
  10292. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  10293. \path[->,bend left=15] (x86-3) edge [above] node
  10294. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10295. \path[->,bend left=15] (x86-4) edge [right] node
  10296. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10297. \end{tikzpicture}
  10298. \fi}
  10299. {\if\edition\pythonEd
  10300. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  10301. \node (Lfun) at (0,2) {\large \LangLoop{}};
  10302. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  10303. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  10304. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10305. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  10306. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  10307. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  10308. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  10309. \path[->,bend left=15] (Lfun) edge [above] node
  10310. {\ttfamily\footnotesize shrink} (Lfun-2);
  10311. \path[->,bend left=15] (Lfun-2) edge [above] node
  10312. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  10313. \path[->,bend left=10] (F1-6) edge [right] node
  10314. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10315. \path[->,bend right=15] (C3-2) edge [right] node
  10316. {\ttfamily\footnotesize select\_instructions} (x86-2);
  10317. \path[->,bend right=15] (x86-2) edge [below] node
  10318. {\ttfamily\footnotesize assign\_homes} (x86-3);
  10319. \path[->,bend left=15] (x86-3) edge [above] node
  10320. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  10321. \path[->,bend right=15] (x86-4) edge [below] node
  10322. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  10323. \end{tikzpicture}
  10324. \fi}
  10325. \end{tcolorbox}
  10326. \caption{Diagram of the passes for \LangLoop{}.}
  10327. \label{fig:Lwhile-passes}
  10328. \end{figure}
  10329. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10330. for the compilation of \LangLoop{}.
  10331. % Further Reading: dataflow analysis
  10332. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10333. \chapter{Tuples and Garbage Collection}
  10334. \label{ch:Lvec}
  10335. \index{subject}{tuple}
  10336. \index{subject}{vector}
  10337. \index{subject}{allocate}
  10338. \index{subject}{heap allocate}
  10339. \setcounter{footnote}{0}
  10340. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10341. %% all the IR grammars are spelled out! \\ --Jeremy}
  10342. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10343. %% the root stack. \\ --Jeremy}
  10344. In this chapter we study the implementation of tuples\racket{, called
  10345. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10346. in which each element may have a different type.
  10347. %
  10348. This language feature is the first to use the computer's
  10349. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  10350. indefinite; that is, a tuple lives forever from the programmer's
  10351. viewpoint. Of course, from an implementer's viewpoint, it is important
  10352. to reclaim the space associated with a tuple when it is no longer
  10353. needed, which is why we also study \emph{garbage collection}
  10354. \index{subject}{garbage collection} techniques in this chapter.
  10355. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  10356. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10357. language (chapter~\ref{ch:Lwhile}) with tuples.
  10358. %
  10359. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10360. copying live tuples back and forth between two halves of the heap. The
  10361. garbage collector requires coordination with the compiler so that it
  10362. can find all the live tuples.
  10363. %
  10364. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10365. discuss the necessary changes and additions to the compiler passes,
  10366. including a new compiler pass named \code{expose\_allocation}.
  10367. \section{The \LangVec{} Language}
  10368. \label{sec:r3}
  10369. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  10370. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  10371. the definition of the abstract syntax.
  10372. %
  10373. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10374. creating a tuple, \code{vector-ref} for reading an element of a
  10375. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10376. \code{vector-length} for obtaining the number of elements of a
  10377. tuple.}
  10378. %
  10379. \python{The \LangVec{} language adds 1) tuple creation via a
  10380. comma-separated list of expressions, 2) accessing an element of a
  10381. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10382. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10383. operator, and 4) obtaining the number of elements (the length) of a
  10384. tuple. In this chapter, we restrict access indices to constant
  10385. integers.}
  10386. %
  10387. The following program shows an example use of tuples. It creates a tuple
  10388. \code{t} containing the elements \code{40},
  10389. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10390. contains just \code{2}. The element at index $1$ of \code{t} is
  10391. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  10392. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10393. to which we add \code{2}, the element at index $0$ of the tuple.
  10394. The result of the program is \code{42}.
  10395. %
  10396. {\if\edition\racketEd
  10397. \begin{lstlisting}
  10398. (let ([t (vector 40 #t (vector 2))])
  10399. (if (vector-ref t 1)
  10400. (+ (vector-ref t 0)
  10401. (vector-ref (vector-ref t 2) 0))
  10402. 44))
  10403. \end{lstlisting}
  10404. \fi}
  10405. {\if\edition\pythonEd
  10406. \begin{lstlisting}
  10407. t = 40, True, (2,)
  10408. print( t[0] + t[2][0] if t[1] else 44 )
  10409. \end{lstlisting}
  10410. \fi}
  10411. \newcommand{\LtupGrammarRacket}{
  10412. \begin{array}{lcl}
  10413. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10414. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10415. \MID \LP\key{vector-length}\;\Exp\RP \\
  10416. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10417. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10418. \end{array}
  10419. }
  10420. \newcommand{\LtupASTRacket}{
  10421. \begin{array}{lcl}
  10422. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10423. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10424. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10425. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  10426. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10427. \end{array}
  10428. }
  10429. \newcommand{\LtupGrammarPython}{
  10430. \begin{array}{rcl}
  10431. \itm{cmp} &::= & \key{is} \\
  10432. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10433. \end{array}
  10434. }
  10435. \newcommand{\LtupASTPython}{
  10436. \begin{array}{lcl}
  10437. \itm{cmp} &::= & \code{Is()} \\
  10438. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10439. &\MID& \LEN{\Exp}
  10440. \end{array}
  10441. }
  10442. \begin{figure}[tbp]
  10443. \centering
  10444. \begin{tcolorbox}[colback=white]
  10445. \small
  10446. {\if\edition\racketEd
  10447. \[
  10448. \begin{array}{l}
  10449. \gray{\LintGrammarRacket{}} \\ \hline
  10450. \gray{\LvarGrammarRacket{}} \\ \hline
  10451. \gray{\LifGrammarRacket{}} \\ \hline
  10452. \gray{\LwhileGrammarRacket} \\ \hline
  10453. \LtupGrammarRacket \\
  10454. \begin{array}{lcl}
  10455. \LangVecM{} &::=& \Exp
  10456. \end{array}
  10457. \end{array}
  10458. \]
  10459. \fi}
  10460. {\if\edition\pythonEd
  10461. \[
  10462. \begin{array}{l}
  10463. \gray{\LintGrammarPython{}} \\ \hline
  10464. \gray{\LvarGrammarPython{}} \\ \hline
  10465. \gray{\LifGrammarPython{}} \\ \hline
  10466. \gray{\LwhileGrammarPython} \\ \hline
  10467. \LtupGrammarPython \\
  10468. \begin{array}{rcl}
  10469. \LangVecM{} &::=& \Stmt^{*}
  10470. \end{array}
  10471. \end{array}
  10472. \]
  10473. \fi}
  10474. \end{tcolorbox}
  10475. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10476. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  10477. \label{fig:Lvec-concrete-syntax}
  10478. \end{figure}
  10479. \begin{figure}[tp]
  10480. \centering
  10481. \begin{tcolorbox}[colback=white]
  10482. \small
  10483. {\if\edition\racketEd
  10484. \[
  10485. \begin{array}{l}
  10486. \gray{\LintOpAST} \\ \hline
  10487. \gray{\LvarASTRacket{}} \\ \hline
  10488. \gray{\LifASTRacket{}} \\ \hline
  10489. \gray{\LwhileASTRacket{}} \\ \hline
  10490. \LtupASTRacket{} \\
  10491. \begin{array}{lcl}
  10492. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10493. \end{array}
  10494. \end{array}
  10495. \]
  10496. \fi}
  10497. {\if\edition\pythonEd
  10498. \[
  10499. \begin{array}{l}
  10500. \gray{\LintASTPython} \\ \hline
  10501. \gray{\LvarASTPython} \\ \hline
  10502. \gray{\LifASTPython} \\ \hline
  10503. \gray{\LwhileASTPython} \\ \hline
  10504. \LtupASTPython \\
  10505. \begin{array}{lcl}
  10506. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10507. \end{array}
  10508. \end{array}
  10509. \]
  10510. \fi}
  10511. \end{tcolorbox}
  10512. \caption{The abstract syntax of \LangVec{}.}
  10513. \label{fig:Lvec-syntax}
  10514. \end{figure}
  10515. Tuples raise several interesting new issues. First, variable binding
  10516. performs a shallow copy in dealing with tuples, which means that
  10517. different variables can refer to the same tuple; that is, two
  10518. variables can be \emph{aliases}\index{subject}{alias} for the same
  10519. entity. Consider the following example, in which \code{t1} and
  10520. \code{t2} refer to the same tuple value and \code{t3} refers to a
  10521. different tuple value with equal elements. The result of the
  10522. program is \code{42}.
  10523. \begin{center}
  10524. \begin{minipage}{0.96\textwidth}
  10525. {\if\edition\racketEd
  10526. \begin{lstlisting}
  10527. (let ([t1 (vector 3 7)])
  10528. (let ([t2 t1])
  10529. (let ([t3 (vector 3 7)])
  10530. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10531. 42
  10532. 0))))
  10533. \end{lstlisting}
  10534. \fi}
  10535. {\if\edition\pythonEd
  10536. \begin{lstlisting}
  10537. t1 = 3, 7
  10538. t2 = t1
  10539. t3 = 3, 7
  10540. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10541. \end{lstlisting}
  10542. \fi}
  10543. \end{minipage}
  10544. \end{center}
  10545. {\if\edition\racketEd
  10546. Whether two variables are aliased or not affects what happens
  10547. when the underlying tuple is mutated\index{subject}{mutation}.
  10548. Consider the following example in which \code{t1} and \code{t2}
  10549. again refer to the same tuple value.
  10550. \begin{center}
  10551. \begin{minipage}{0.96\textwidth}
  10552. \begin{lstlisting}
  10553. (let ([t1 (vector 3 7)])
  10554. (let ([t2 t1])
  10555. (let ([_ (vector-set! t2 0 42)])
  10556. (vector-ref t1 0))))
  10557. \end{lstlisting}
  10558. \end{minipage}
  10559. \end{center}
  10560. The mutation through \code{t2} is visible in referencing the tuple
  10561. from \code{t1}, so the result of this program is \code{42}.
  10562. \fi}
  10563. The next issue concerns the lifetime of tuples. When does a tuple's
  10564. lifetime end? Notice that \LangVec{} does not include an operation
  10565. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10566. to any notion of static scoping.
  10567. %
  10568. {\if\edition\racketEd
  10569. %
  10570. For example, the following program returns \code{42} even though the
  10571. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10572. that reads from the vector to which it was bound.
  10573. \begin{center}
  10574. \begin{minipage}{0.96\textwidth}
  10575. \begin{lstlisting}
  10576. (let ([v (vector (vector 44))])
  10577. (let ([x (let ([w (vector 42)])
  10578. (let ([_ (vector-set! v 0 w)])
  10579. 0))])
  10580. (+ x (vector-ref (vector-ref v 0) 0))))
  10581. \end{lstlisting}
  10582. \end{minipage}
  10583. \end{center}
  10584. \fi}
  10585. %
  10586. {\if\edition\pythonEd
  10587. %
  10588. For example, the following program returns \code{42} even though the
  10589. variable \code{x} goes out of scope when the function returns, prior
  10590. to reading the tuple element at index zero. (We study the compilation
  10591. of functions in chapter~\ref{ch:Lfun}.)
  10592. %
  10593. \begin{center}
  10594. \begin{minipage}{0.96\textwidth}
  10595. \begin{lstlisting}
  10596. def f():
  10597. x = 42, 43
  10598. return x
  10599. t = f()
  10600. print( t[0] )
  10601. \end{lstlisting}
  10602. \end{minipage}
  10603. \end{center}
  10604. \fi}
  10605. %
  10606. From the perspective of programmer-observable behavior, tuples live
  10607. forever. However, if they really lived forever then many long-running
  10608. programs would run out of memory. To solve this problem, the
  10609. language's runtime system performs automatic garbage collection.
  10610. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10611. \LangVec{} language.
  10612. %
  10613. \racket{We define the \code{vector}, \code{vector-ref},
  10614. \code{vector-set!}, and \code{vector-length} operations for
  10615. \LangVec{} in terms of the corresponding operations in Racket. One
  10616. subtle point is that the \code{vector-set!} operation returns the
  10617. \code{\#<void>} value.}
  10618. %
  10619. \python{We represent tuples with Python lists in the interpreter
  10620. because we need to write to them
  10621. (section~\ref{sec:expose-allocation}). (Python tuples are
  10622. immutable.) We define element access, the \code{is} operator, and
  10623. the \code{len} operator for \LangVec{} in terms of the corresponding
  10624. operations in Python.}
  10625. \begin{figure}[tbp]
  10626. \begin{tcolorbox}[colback=white]
  10627. {\if\edition\racketEd
  10628. \begin{lstlisting}
  10629. (define interp-Lvec-class
  10630. (class interp-Lwhile-class
  10631. (super-new)
  10632. (define/override (interp-op op)
  10633. (match op
  10634. ['eq? (lambda (v1 v2)
  10635. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10636. (and (boolean? v1) (boolean? v2))
  10637. (and (vector? v1) (vector? v2))
  10638. (and (void? v1) (void? v2)))
  10639. (eq? v1 v2)]))]
  10640. ['vector vector]
  10641. ['vector-length vector-length]
  10642. ['vector-ref vector-ref]
  10643. ['vector-set! vector-set!]
  10644. [else (super interp-op op)]
  10645. ))
  10646. (define/override ((interp-exp env) e)
  10647. (match e
  10648. [(HasType e t) ((interp-exp env) e)]
  10649. [else ((super interp-exp env) e)]
  10650. ))
  10651. ))
  10652. (define (interp-Lvec p)
  10653. (send (new interp-Lvec-class) interp-program p))
  10654. \end{lstlisting}
  10655. \fi}
  10656. %
  10657. {\if\edition\pythonEd
  10658. \begin{lstlisting}
  10659. class InterpLtup(InterpLwhile):
  10660. def interp_cmp(self, cmp):
  10661. match cmp:
  10662. case Is():
  10663. return lambda x, y: x is y
  10664. case _:
  10665. return super().interp_cmp(cmp)
  10666. def interp_exp(self, e, env):
  10667. match e:
  10668. case Tuple(es, Load()):
  10669. return tuple([self.interp_exp(e, env) for e in es])
  10670. case Subscript(tup, index, Load()):
  10671. t = self.interp_exp(tup, env)
  10672. n = self.interp_exp(index, env)
  10673. return t[n]
  10674. case _:
  10675. return super().interp_exp(e, env)
  10676. \end{lstlisting}
  10677. \fi}
  10678. \end{tcolorbox}
  10679. \caption{Interpreter for the \LangVec{} language.}
  10680. \label{fig:interp-Lvec}
  10681. \end{figure}
  10682. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10683. \LangVec{}.
  10684. %
  10685. The type of a tuple is a
  10686. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  10687. type for each of its elements.
  10688. %
  10689. \racket{To create the s-expression for the \code{Vector} type, we use the
  10690. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10691. operator} \code{,@} to insert the list \code{t*} without its usual
  10692. start and end parentheses. \index{subject}{unquote-splicing}}
  10693. %
  10694. The type of accessing the ith element of a tuple is the ith element
  10695. type of the tuple's type, if there is one. If not, an error is
  10696. signaled. Note that the index \code{i} is required to be a constant
  10697. integer (and not, for example, a call to
  10698. \racket{\code{read}}\python{input\_int}) so that the type checker
  10699. can determine the element's type given the tuple type.
  10700. %
  10701. \racket{
  10702. Regarding writing an element to a tuple, the element's type must
  10703. be equal to the ith element type of the tuple's type.
  10704. The result type is \code{Void}.}
  10705. %% When allocating a tuple,
  10706. %% we need to know which elements of the tuple are themselves tuples for
  10707. %% the purposes of garbage collection. We can obtain this information
  10708. %% during type checking. The type checker shown in
  10709. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10710. %% expression; it also
  10711. %% %
  10712. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10713. %% where $T$ is the tuple's type.
  10714. %
  10715. %records the type of each tuple expression in a new field named \code{has\_type}.
  10716. \begin{figure}[tp]
  10717. \begin{tcolorbox}[colback=white]
  10718. {\if\edition\racketEd
  10719. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10720. (define type-check-Lvec-class
  10721. (class type-check-Lif-class
  10722. (super-new)
  10723. (inherit check-type-equal?)
  10724. (define/override (type-check-exp env)
  10725. (lambda (e)
  10726. (define recur (type-check-exp env))
  10727. (match e
  10728. [(Prim 'vector es)
  10729. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10730. (define t `(Vector ,@t*))
  10731. (values (Prim 'vector e*) t)]
  10732. [(Prim 'vector-ref (list e1 (Int i)))
  10733. (define-values (e1^ t) (recur e1))
  10734. (match t
  10735. [`(Vector ,ts ...)
  10736. (unless (and (0 . <= . i) (i . < . (length ts)))
  10737. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10738. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10739. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10740. [(Prim 'vector-set! (list e1 (Int i) elt) )
  10741. (define-values (e-vec t-vec) (recur e1))
  10742. (define-values (e-elt^ t-elt) (recur elt))
  10743. (match t-vec
  10744. [`(Vector ,ts ...)
  10745. (unless (and (0 . <= . i) (i . < . (length ts)))
  10746. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10747. (check-type-equal? (list-ref ts i) t-elt e)
  10748. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  10749. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10750. [(Prim 'vector-length (list e))
  10751. (define-values (e^ t) (recur e))
  10752. (match t
  10753. [`(Vector ,ts ...)
  10754. (values (Prim 'vector-length (list e^)) 'Integer)]
  10755. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10756. [(Prim 'eq? (list arg1 arg2))
  10757. (define-values (e1 t1) (recur arg1))
  10758. (define-values (e2 t2) (recur arg2))
  10759. (match* (t1 t2)
  10760. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10761. [(other wise) (check-type-equal? t1 t2 e)])
  10762. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10763. [else ((super type-check-exp env) e)]
  10764. )))
  10765. ))
  10766. (define (type-check-Lvec p)
  10767. (send (new type-check-Lvec-class) type-check-program p))
  10768. \end{lstlisting}
  10769. \fi}
  10770. {\if\edition\pythonEd
  10771. \begin{lstlisting}
  10772. class TypeCheckLtup(TypeCheckLwhile):
  10773. def type_check_exp(self, e, env):
  10774. match e:
  10775. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10776. l = self.type_check_exp(left, env)
  10777. r = self.type_check_exp(right, env)
  10778. check_type_equal(l, r, e)
  10779. return bool
  10780. case Tuple(es, Load()):
  10781. ts = [self.type_check_exp(e, env) for e in es]
  10782. e.has_type = TupleType(ts)
  10783. return e.has_type
  10784. case Subscript(tup, Constant(i), Load()):
  10785. tup_ty = self.type_check_exp(tup, env)
  10786. i_ty = self.type_check_exp(Constant(i), env)
  10787. check_type_equal(i_ty, int, i)
  10788. match tup_ty:
  10789. case TupleType(ts):
  10790. return ts[i]
  10791. case _:
  10792. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10793. case _:
  10794. return super().type_check_exp(e, env)
  10795. \end{lstlisting}
  10796. \fi}
  10797. \end{tcolorbox}
  10798. \caption{Type checker for the \LangVec{} language.}
  10799. \label{fig:type-check-Lvec}
  10800. \end{figure}
  10801. \section{Garbage Collection}
  10802. \label{sec:GC}
  10803. Garbage collection is a runtime technique for reclaiming space on the
  10804. heap that will not be used in the future of the running program. We
  10805. use the term \emph{object}\index{subject}{object} to refer to any
  10806. value that is stored in the heap, which for now includes only
  10807. tuples.%
  10808. %
  10809. \footnote{The term \emph{object} as it is used in the context of
  10810. object-oriented programming has a more specific meaning than the
  10811. way in which we use the term here.}
  10812. %
  10813. Unfortunately, it is impossible to know precisely which objects will
  10814. be accessed in the future and which will not. Instead, garbage
  10815. collectors overapproximate the set of objects that will be accessed by
  10816. identifying which objects can possibly be accessed. The running
  10817. program can directly access objects that are in registers and on the
  10818. procedure call stack. It can also transitively access the elements of
  10819. tuples, starting with a tuple whose address is in a register or on the
  10820. procedure call stack. We define the \emph{root
  10821. set}\index{subject}{root set} to be all the tuple addresses that are
  10822. in registers or on the procedure call stack. We define the \emph{live
  10823. objects}\index{subject}{live objects} to be the objects that are
  10824. reachable from the root set. Garbage collectors reclaim the space that
  10825. is allocated to objects that are no longer live. That means that some
  10826. objects may not get reclaimed as soon as they could be, but at least
  10827. garbage collectors do not reclaim the space dedicated to objects that
  10828. will be accessed in the future! The programmer can influence which
  10829. objects get reclaimed by causing them to become unreachable.
  10830. So the goal of the garbage collector is twofold:
  10831. \begin{enumerate}
  10832. \item to preserve all the live objects, and
  10833. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  10834. \end{enumerate}
  10835. \subsection{Two-Space Copying Collector}
  10836. Here we study a relatively simple algorithm for garbage collection
  10837. that is the basis of many state-of-the-art garbage
  10838. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10839. particular, we describe a two-space copying
  10840. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10841. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10842. collector} \index{subject}{two-space copying collector}
  10843. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10844. what happens in a two-space collector, showing two time steps, prior
  10845. to garbage collection (on the top) and after garbage collection (on
  10846. the bottom). In a two-space collector, the heap is divided into two
  10847. parts named the FromSpace\index{subject}{FromSpace} and the
  10848. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10849. FromSpace until there is not enough room for the next allocation
  10850. request. At that point, the garbage collector goes to work to make
  10851. room for the next allocation.
  10852. A copying collector makes more room by copying all the live objects
  10853. from the FromSpace into the ToSpace and then performs a sleight of
  10854. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10855. as the new ToSpace. In the example shown in
  10856. figure~\ref{fig:copying-collector}, the root set consists of three
  10857. pointers, one in a register and two on the stack. All the live
  10858. objects have been copied to the ToSpace (the right-hand side of
  10859. figure~\ref{fig:copying-collector}) in a way that preserves the
  10860. pointer relationships. For example, the pointer in the register still
  10861. points to a tuple that in turn points to two other tuples. There are
  10862. four tuples that are not reachable from the root set and therefore do
  10863. not get copied into the ToSpace.
  10864. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  10865. created by a well-typed program in \LangVec{} because it contains a
  10866. cycle. However, creating cycles will be possible once we get to
  10867. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  10868. to deal with cycles to begin with, so we will not need to revisit this
  10869. issue.
  10870. \begin{figure}[tbp]
  10871. \centering
  10872. \begin{tcolorbox}[colback=white]
  10873. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10874. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10875. \\[5ex]
  10876. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10877. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10878. \end{tcolorbox}
  10879. \caption{A copying collector in action.}
  10880. \label{fig:copying-collector}
  10881. \end{figure}
  10882. \subsection{Graph Copying via Cheney's Algorithm}
  10883. \label{sec:cheney}
  10884. \index{subject}{Cheney's algorithm}
  10885. Let us take a closer look at the copying of the live objects. The
  10886. allocated objects and pointers can be viewed as a graph, and we need to
  10887. copy the part of the graph that is reachable from the root set. To
  10888. make sure that we copy all the reachable vertices in the graph, we need
  10889. an exhaustive graph traversal algorithm, such as depth-first search or
  10890. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10891. such algorithms take into account the possibility of cycles by marking
  10892. which vertices have already been visited, so to ensure termination
  10893. of the algorithm. These search algorithms also use a data structure
  10894. such as a stack or queue as a to-do list to keep track of the vertices
  10895. that need to be visited. We use breadth-first search and a trick
  10896. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10897. and copying tuples into the ToSpace.
  10898. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10899. copy progresses. The queue is represented by a chunk of contiguous
  10900. memory at the beginning of the ToSpace, using two pointers to track
  10901. the front and the back of the queue, called the \emph{free pointer}
  10902. and the \emph{scan pointer}, respectively. The algorithm starts by
  10903. copying all tuples that are immediately reachable from the root set
  10904. into the ToSpace to form the initial queue. When we copy a tuple, we
  10905. mark the old tuple to indicate that it has been visited. We discuss
  10906. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  10907. that any pointers inside the copied tuples in the queue still point
  10908. back to the FromSpace. Once the initial queue has been created, the
  10909. algorithm enters a loop in which it repeatedly processes the tuple at
  10910. the front of the queue and pops it off the queue. To process a tuple,
  10911. the algorithm copies all the objects that are directly reachable from it
  10912. to the ToSpace, placing them at the back of the queue. The algorithm
  10913. then updates the pointers in the popped tuple so that they point to the
  10914. newly copied objects.
  10915. \begin{figure}[tbp]
  10916. \centering
  10917. \begin{tcolorbox}[colback=white]
  10918. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10919. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10920. \end{tcolorbox}
  10921. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10922. \label{fig:cheney}
  10923. \end{figure}
  10924. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  10925. tuple whose second element is $42$ to the back of the queue. The other
  10926. pointer goes to a tuple that has already been copied, so we do not
  10927. need to copy it again, but we do need to update the pointer to the new
  10928. location. This can be accomplished by storing a \emph{forwarding
  10929. pointer}\index{subject}{forwarding pointer} to the new location in the
  10930. old tuple, when we initially copied the tuple into the
  10931. ToSpace. This completes one step of the algorithm. The algorithm
  10932. continues in this way until the queue is empty; that is, when the scan
  10933. pointer catches up with the free pointer.
  10934. \subsection{Data Representation}
  10935. \label{sec:data-rep-gc}
  10936. The garbage collector places some requirements on the data
  10937. representations used by our compiler. First, the garbage collector
  10938. needs to distinguish between pointers and other kinds of data such as
  10939. integers. The following are several ways to accomplish this:
  10940. \begin{enumerate}
  10941. \item Attach a tag to each object that identifies what type of
  10942. object it is~\citep{McCarthy:1960dz}.
  10943. \item Store different types of objects in different
  10944. regions~\citep{Steele:1977ab}.
  10945. \item Use type information from the program to either (a) generate
  10946. type-specific code for collecting, or (b) generate tables that
  10947. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10948. \end{enumerate}
  10949. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10950. need to tag objects in any case, so option 1 is a natural choice for those
  10951. languages. However, \LangVec{} is a statically typed language, so it
  10952. would be unfortunate to require tags on every object, especially small
  10953. and pervasive objects like integers and Booleans. Option 3 is the
  10954. best-performing choice for statically typed languages, but it comes with
  10955. a relatively high implementation complexity. To keep this chapter
  10956. within a reasonable scope of complexity, we recommend a combination of options
  10957. 1 and 2, using separate strategies for the stack and the heap.
  10958. Regarding the stack, we recommend using a separate stack for pointers,
  10959. which we call the \emph{root stack}\index{subject}{root stack}
  10960. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  10961. That is, when a local variable needs to be spilled and is of type
  10962. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  10963. root stack instead of putting it on the procedure call
  10964. stack. Furthermore, we always spill tuple-typed variables if they are
  10965. live during a call to the collector, thereby ensuring that no pointers
  10966. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10967. reproduces the example shown in figure~\ref{fig:copying-collector} and
  10968. contrasts it with the data layout using a root stack. The root stack
  10969. contains the two pointers from the regular stack and also the pointer
  10970. in the second register.
  10971. \begin{figure}[tbp]
  10972. \centering
  10973. \begin{tcolorbox}[colback=white]
  10974. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10975. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10976. \end{tcolorbox}
  10977. \caption{Maintaining a root stack to facilitate garbage collection.}
  10978. \label{fig:shadow-stack}
  10979. \end{figure}
  10980. The problem of distinguishing between pointers and other kinds of data
  10981. also arises inside each tuple on the heap. We solve this problem by
  10982. attaching a tag, an extra 64 bits, to each
  10983. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  10984. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  10985. Note that we have drawn the bits in a big-endian way, from right to left,
  10986. with bit location 0 (the least significant bit) on the far right,
  10987. which corresponds to the direction of the x86 shifting instructions
  10988. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10989. is dedicated to specifying which elements of the tuple are pointers,
  10990. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  10991. indicates that there is a pointer, and a 0 bit indicates some other kind of
  10992. data. The pointer mask starts at bit location 7. We limit tuples to a
  10993. maximum size of fifty elements, so we need 50 bits for the pointer
  10994. mask.%
  10995. %
  10996. \footnote{A production-quality compiler would handle
  10997. arbitrarily sized tuples and use a more complex approach.}
  10998. %
  10999. The tag also contains two other pieces of information. The length of
  11000. the tuple (number of elements) is stored in bits at locations 1 through
  11001. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11002. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11003. has not yet been copied. If the bit has value 0, then the entire tag
  11004. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11005. zero in any case, because our tuples are 8-byte aligned.)
  11006. \begin{figure}[tbp]
  11007. \centering
  11008. \begin{tcolorbox}[colback=white]
  11009. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11010. \end{tcolorbox}
  11011. \caption{Representation of tuples in the heap.}
  11012. \label{fig:tuple-rep}
  11013. \end{figure}
  11014. \subsection{Implementation of the Garbage Collector}
  11015. \label{sec:organize-gz}
  11016. \index{subject}{prelude}
  11017. An implementation of the copying collector is provided in the
  11018. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11019. interface to the garbage collector that is used by the compiler. The
  11020. \code{initialize} function creates the FromSpace, ToSpace, and root
  11021. stack and should be called in the prelude of the \code{main}
  11022. function. The arguments of \code{initialize} are the root stack size
  11023. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11024. good choice for both. The \code{initialize} function puts the address
  11025. of the beginning of the FromSpace into the global variable
  11026. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11027. the address that is one past the last element of the FromSpace. We use
  11028. half-open intervals to represent chunks of
  11029. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11030. points to the first element of the root stack.
  11031. As long as there is room left in the FromSpace, your generated code
  11032. can allocate tuples simply by moving the \code{free\_ptr} forward.
  11033. %
  11034. The amount of room left in the FromSpace is the difference between the
  11035. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11036. function should be called when there is not enough room left in the
  11037. FromSpace for the next allocation. The \code{collect} function takes
  11038. a pointer to the current top of the root stack (one past the last item
  11039. that was pushed) and the number of bytes that need to be
  11040. allocated. The \code{collect} function performs the copying collection
  11041. and leaves the heap in a state such that there is enough room for the
  11042. next allocation.
  11043. \begin{figure}[tbp]
  11044. \begin{tcolorbox}[colback=white]
  11045. \begin{lstlisting}
  11046. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11047. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11048. int64_t* free_ptr;
  11049. int64_t* fromspace_begin;
  11050. int64_t* fromspace_end;
  11051. int64_t** rootstack_begin;
  11052. \end{lstlisting}
  11053. \end{tcolorbox}
  11054. \caption{The compiler's interface to the garbage collector.}
  11055. \label{fig:gc-header}
  11056. \end{figure}
  11057. %% \begin{exercise}
  11058. %% In the file \code{runtime.c} you will find the implementation of
  11059. %% \code{initialize} and a partial implementation of \code{collect}.
  11060. %% The \code{collect} function calls another function, \code{cheney},
  11061. %% to perform the actual copy, and that function is left to the reader
  11062. %% to implement. The following is the prototype for \code{cheney}.
  11063. %% \begin{lstlisting}
  11064. %% static void cheney(int64_t** rootstack_ptr);
  11065. %% \end{lstlisting}
  11066. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11067. %% rootstack (which is an array of pointers). The \code{cheney} function
  11068. %% also communicates with \code{collect} through the global
  11069. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11070. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11071. %% the ToSpace:
  11072. %% \begin{lstlisting}
  11073. %% static int64_t* tospace_begin;
  11074. %% static int64_t* tospace_end;
  11075. %% \end{lstlisting}
  11076. %% The job of the \code{cheney} function is to copy all the live
  11077. %% objects (reachable from the root stack) into the ToSpace, update
  11078. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11079. %% update the root stack so that it points to the objects in the
  11080. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11081. %% and ToSpace.
  11082. %% \end{exercise}
  11083. The introduction of garbage collection has a nontrivial impact on our
  11084. compiler passes. We introduce a new compiler pass named
  11085. \code{expose\_allocation} that elaborates the code for allocating
  11086. tuples. We also make significant changes to
  11087. \code{select\_instructions}, \code{build\_interference},
  11088. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11089. make minor changes in several more passes.
  11090. The following program serves as our running example. It creates
  11091. two tuples, one nested inside the other. Both tuples have length
  11092. one. The program accesses the element in the inner tuple.
  11093. % tests/vectors_test_17.rkt
  11094. {\if\edition\racketEd
  11095. \begin{lstlisting}
  11096. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11097. \end{lstlisting}
  11098. \fi}
  11099. {\if\edition\pythonEd
  11100. \begin{lstlisting}
  11101. print( ((42,),)[0][0] )
  11102. \end{lstlisting}
  11103. \fi}
  11104. %% {\if\edition\racketEd
  11105. %% \section{Shrink}
  11106. %% \label{sec:shrink-Lvec}
  11107. %% Recall that the \code{shrink} pass translates the primitives operators
  11108. %% into a smaller set of primitives.
  11109. %% %
  11110. %% This pass comes after type checking, and the type checker adds a
  11111. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11112. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11113. %% \fi}
  11114. \section{Expose Allocation}
  11115. \label{sec:expose-allocation}
  11116. The pass \code{expose\_allocation} lowers tuple creation into making a
  11117. conditional call to the collector followed by allocating the
  11118. appropriate amount of memory and initializing it. We choose to place
  11119. the \code{expose\_allocation} pass before
  11120. \code{remove\_complex\_operands} because it generates
  11121. code that contains complex operands.
  11122. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11123. that replaces tuple creation with new lower-level forms that we use in the
  11124. translation of tuple creation.
  11125. %
  11126. {\if\edition\racketEd
  11127. \[
  11128. \begin{array}{lcl}
  11129. \Exp &::=& \cdots
  11130. \MID (\key{collect} \,\itm{int})
  11131. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11132. \MID (\key{global-value} \,\itm{name})
  11133. \end{array}
  11134. \]
  11135. \fi}
  11136. {\if\edition\pythonEd
  11137. \[
  11138. \begin{array}{lcl}
  11139. \Exp &::=& \cdots\\
  11140. &\MID& \key{collect}(\itm{int})
  11141. \MID \key{allocate}(\itm{int},\itm{type})
  11142. \MID \key{global\_value}(\itm{name}) \\
  11143. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  11144. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11145. \end{array}
  11146. \]
  11147. \fi}
  11148. %
  11149. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11150. make sure that there are $n$ bytes ready to be allocated. During
  11151. instruction selection, the \CCOLLECT{$n$} form will become a call to
  11152. the \code{collect} function in \code{runtime.c}.
  11153. %
  11154. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11155. space at the front for the 64-bit tag), but the elements are not
  11156. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11157. of the tuple:
  11158. %
  11159. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11160. %
  11161. where $\Type_i$ is the type of the $i$th element.
  11162. %
  11163. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11164. variable, such as \code{free\_ptr}.
  11165. %
  11166. \python{The \code{begin} form is an expression that executes a
  11167. sequence of statements and then produces the value of the expression
  11168. at the end.}
  11169. \racket{
  11170. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11171. can be obtained by running the
  11172. \code{type-check-Lvec-has-type} type checker immediately before the
  11173. \code{expose\_allocation} pass. This version of the type checker
  11174. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11175. around each tuple creation. The concrete syntax
  11176. for \code{HasType} is \code{has-type}.}
  11177. The following shows the transformation of tuple creation into (1) a
  11178. sequence of temporary variable bindings for the initializing
  11179. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11180. \code{allocate}, and (4) the initialization of the tuple. The
  11181. \itm{len} placeholder refers to the length of the tuple, and
  11182. \itm{bytes} is the total number of bytes that need to be allocated for
  11183. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11184. %
  11185. \python{The \itm{type} needed for the second argument of the
  11186. \code{allocate} form can be obtained from the \code{has\_type} field
  11187. of the tuple AST node, which is stored there by running the type
  11188. checker for \LangVec{} immediately before this pass.}
  11189. %
  11190. \begin{center}
  11191. \begin{minipage}{\textwidth}
  11192. {\if\edition\racketEd
  11193. \begin{lstlisting}
  11194. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11195. |$\Longrightarrow$|
  11196. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11197. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11198. (global-value fromspace_end))
  11199. (void)
  11200. (collect |\itm{bytes}|))])
  11201. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11202. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11203. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11204. |$v$|) ... )))) ...)
  11205. \end{lstlisting}
  11206. \fi}
  11207. {\if\edition\pythonEd
  11208. \begin{lstlisting}
  11209. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11210. |$\Longrightarrow$|
  11211. begin:
  11212. |$x_0$| = |$e_0$|
  11213. |$\vdots$|
  11214. |$x_{n-1}$| = |$e_{n-1}$|
  11215. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  11216. 0
  11217. else:
  11218. collect(|\itm{bytes}|)
  11219. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  11220. |$v$|[0] = |$x_0$|
  11221. |$\vdots$|
  11222. |$v$|[|$n-1$|] = |$x_{n-1}$|
  11223. |$v$|
  11224. \end{lstlisting}
  11225. \fi}
  11226. \end{minipage}
  11227. \end{center}
  11228. %
  11229. \noindent The sequencing of the initializing expressions
  11230. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, because
  11231. they may trigger garbage collection and we cannot have an allocated
  11232. but uninitialized tuple on the heap during a collection.
  11233. Figure~\ref{fig:expose-alloc-output} shows the output of the
  11234. \code{expose\_allocation} pass on our running example.
  11235. \begin{figure}[tbp]
  11236. \begin{tcolorbox}[colback=white]
  11237. % tests/s2_17.rkt
  11238. {\if\edition\racketEd
  11239. \begin{lstlisting}
  11240. (vector-ref
  11241. (vector-ref
  11242. (let ([vecinit6
  11243. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  11244. (global-value fromspace_end))
  11245. (void)
  11246. (collect 16))])
  11247. (let ([alloc2 (allocate 1 (Vector Integer))])
  11248. (let ([_3 (vector-set! alloc2 0 42)])
  11249. alloc2)))])
  11250. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  11251. (global-value fromspace_end))
  11252. (void)
  11253. (collect 16))])
  11254. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  11255. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  11256. alloc5))))
  11257. 0)
  11258. 0)
  11259. \end{lstlisting}
  11260. \fi}
  11261. {\if\edition\pythonEd
  11262. \begin{lstlisting}
  11263. print( |$T_1$|[0][0] )
  11264. \end{lstlisting}
  11265. where $T_1$ is
  11266. \begin{lstlisting}
  11267. begin:
  11268. tmp.1 = |$T_2$|
  11269. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11270. 0
  11271. else:
  11272. collect(16)
  11273. tmp.2 = allocate(1, TupleType(TupleType([int])))
  11274. tmp.2[0] = tmp.1
  11275. tmp.2
  11276. \end{lstlisting}
  11277. and $T_2$ is
  11278. \begin{lstlisting}
  11279. begin:
  11280. tmp.3 = 42
  11281. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  11282. 0
  11283. else:
  11284. collect(16)
  11285. tmp.4 = allocate(1, TupleType([int]))
  11286. tmp.4[0] = tmp.3
  11287. tmp.4
  11288. \end{lstlisting}
  11289. \fi}
  11290. \end{tcolorbox}
  11291. \caption{Output of the \code{expose\_allocation} pass.}
  11292. \label{fig:expose-alloc-output}
  11293. \end{figure}
  11294. \section{Remove Complex Operands}
  11295. \label{sec:remove-complex-opera-Lvec}
  11296. {\if\edition\racketEd
  11297. %
  11298. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  11299. should be treated as complex operands.
  11300. %
  11301. \fi}
  11302. %
  11303. {\if\edition\pythonEd
  11304. %
  11305. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  11306. and tuple access should be treated as complex operands. The
  11307. sub-expressions of tuple access must be atomic.
  11308. %
  11309. \fi}
  11310. %% A new case for
  11311. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11312. %% handled carefully to prevent the \code{Prim} node from being separated
  11313. %% from its enclosing \code{HasType}.
  11314. Figure~\ref{fig:Lvec-anf-syntax}
  11315. shows the grammar for the output language \LangAllocANF{} of this
  11316. pass, which is \LangAlloc{} in monadic normal form.
  11317. \newcommand{\LtupMonadASTRacket}{
  11318. \begin{array}{rcl}
  11319. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11320. \MID \GLOBALVALUE{\Var}
  11321. \end{array}
  11322. }
  11323. \newcommand{\LtupMonadASTPython}{
  11324. \begin{array}{rcl}
  11325. \Exp &::=& \GET{\Atm}{\Atm} \\
  11326. &\MID& \LEN{\Atm}\\
  11327. &\MID& \ALLOCATE{\Int}{\Type}
  11328. \MID \GLOBALVALUE{\Var} \\
  11329. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11330. &\MID& \COLLECT{\Int}
  11331. \end{array}
  11332. }
  11333. \begin{figure}[tp]
  11334. \centering
  11335. \begin{tcolorbox}[colback=white]
  11336. \small
  11337. {\if\edition\racketEd
  11338. \[
  11339. \begin{array}{l}
  11340. \gray{\LvarMonadASTRacket} \\ \hline
  11341. \gray{\LifMonadASTRacket} \\ \hline
  11342. \gray{\LwhileMonadASTRacket} \\ \hline
  11343. \LtupMonadASTRacket \\
  11344. \begin{array}{rcl}
  11345. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11346. \end{array}
  11347. \end{array}
  11348. \]
  11349. \fi}
  11350. {\if\edition\pythonEd
  11351. \[
  11352. \begin{array}{l}
  11353. \gray{\LvarMonadASTPython} \\ \hline
  11354. \gray{\LifMonadASTPython} \\ \hline
  11355. \gray{\LwhileMonadASTPython} \\ \hline
  11356. \LtupMonadASTPython \\
  11357. \begin{array}{rcl}
  11358. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11359. \end{array}
  11360. \end{array}
  11361. \]
  11362. \fi}
  11363. \end{tcolorbox}
  11364. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11365. \label{fig:Lvec-anf-syntax}
  11366. \end{figure}
  11367. \section{Explicate Control and the \LangCVec{} language}
  11368. \label{sec:explicate-control-r3}
  11369. \newcommand{\CtupASTRacket}{
  11370. \begin{array}{lcl}
  11371. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11372. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11373. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11374. &\MID& \VECLEN{\Atm} \\
  11375. &\MID& \GLOBALVALUE{\Var} \\
  11376. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11377. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11378. \end{array}
  11379. }
  11380. \newcommand{\CtupASTPython}{
  11381. \begin{array}{lcl}
  11382. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11383. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11384. \Stmt &::=& \COLLECT{\Int} \\
  11385. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11386. \end{array}
  11387. }
  11388. \begin{figure}[tp]
  11389. \begin{tcolorbox}[colback=white]
  11390. \small
  11391. {\if\edition\racketEd
  11392. \[
  11393. \begin{array}{l}
  11394. \gray{\CvarASTRacket} \\ \hline
  11395. \gray{\CifASTRacket} \\ \hline
  11396. \gray{\CloopASTRacket} \\ \hline
  11397. \CtupASTRacket \\
  11398. \begin{array}{lcl}
  11399. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11400. \end{array}
  11401. \end{array}
  11402. \]
  11403. \fi}
  11404. {\if\edition\pythonEd
  11405. \[
  11406. \begin{array}{l}
  11407. \gray{\CifASTPython} \\ \hline
  11408. \CtupASTPython \\
  11409. \begin{array}{lcl}
  11410. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11411. \end{array}
  11412. \end{array}
  11413. \]
  11414. \fi}
  11415. \end{tcolorbox}
  11416. \caption{The abstract syntax of \LangCVec{}, extending
  11417. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11418. (figure~\ref{fig:c1-syntax})}.}
  11419. \label{fig:c2-syntax}
  11420. \end{figure}
  11421. The output of \code{explicate\_control} is a program in the
  11422. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  11423. shows the definition of the abstract syntax.
  11424. %
  11425. %% \racket{(The concrete syntax is defined in
  11426. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11427. %
  11428. The new expressions of \LangCVec{} include \key{allocate},
  11429. %
  11430. \racket{\key{vector-ref}, and \key{vector-set!},}
  11431. %
  11432. \python{accessing tuple elements,}
  11433. %
  11434. and \key{global\_value}.
  11435. %
  11436. \python{\LangCVec{} also includes the \code{collect} statement and
  11437. assignment to a tuple element.}
  11438. %
  11439. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11440. %
  11441. The \code{explicate\_control} pass can treat these new forms much like
  11442. the other forms that we've already encountered. The output of the
  11443. \code{explicate\_control} pass on the running example is shown on the
  11444. left side of figure~\ref{fig:select-instr-output-gc} in the next
  11445. section.
  11446. \section{Select Instructions and the \LangXGlobal{} Language}
  11447. \label{sec:select-instructions-gc}
  11448. \index{subject}{instruction selection}
  11449. %% void (rep as zero)
  11450. %% allocate
  11451. %% collect (callq collect)
  11452. %% vector-ref
  11453. %% vector-set!
  11454. %% vector-length
  11455. %% global (postpone)
  11456. In this pass we generate x86 code for most of the new operations that
  11457. were needed to compile tuples, including \code{Allocate},
  11458. \code{Collect}, and accessing tuple elements.
  11459. %
  11460. We compile \code{GlobalValue} to \code{Global} because the latter has a
  11461. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  11462. \ref{fig:x86-2}). \index{subject}{x86}
  11463. The tuple read and write forms translate into \code{movq}
  11464. instructions. (The $+1$ in the offset serves to move past the tag at the
  11465. beginning of the tuple representation.)
  11466. %
  11467. \begin{center}
  11468. \begin{minipage}{\textwidth}
  11469. {\if\edition\racketEd
  11470. \begin{lstlisting}
  11471. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11472. |$\Longrightarrow$|
  11473. movq |$\itm{tup}'$|, %r11
  11474. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11475. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11476. |$\Longrightarrow$|
  11477. movq |$\itm{tup}'$|, %r11
  11478. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11479. movq $0, |$\itm{lhs'}$|
  11480. \end{lstlisting}
  11481. \fi}
  11482. {\if\edition\pythonEd
  11483. \begin{lstlisting}
  11484. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11485. |$\Longrightarrow$|
  11486. movq |$\itm{tup}'$|, %r11
  11487. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11488. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11489. |$\Longrightarrow$|
  11490. movq |$\itm{tup}'$|, %r11
  11491. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11492. \end{lstlisting}
  11493. \fi}
  11494. \end{minipage}
  11495. \end{center}
  11496. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11497. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11498. are obtained by translating from \LangCVec{} to x86.
  11499. %
  11500. The move of $\itm{tup}'$ to
  11501. register \code{r11} ensures that offset expression
  11502. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11503. removing \code{r11} from consideration by the register allocating.
  11504. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  11505. \code{rax}. Then the generated code for tuple assignment would be
  11506. \begin{lstlisting}
  11507. movq |$\itm{tup}'$|, %rax
  11508. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11509. \end{lstlisting}
  11510. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11511. \code{patch\_instructions} would insert a move through \code{rax}
  11512. as follows:
  11513. \begin{lstlisting}
  11514. movq |$\itm{tup}'$|, %rax
  11515. movq |$\itm{rhs}'$|, %rax
  11516. movq %rax, |$8(n+1)$|(%rax)
  11517. \end{lstlisting}
  11518. However, this sequence of instructions does not work, because we're
  11519. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11520. $\itm{rhs}'$) at the same time!
  11521. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11522. be translated into a sequence of instructions that read the tag of the
  11523. tuple and extract the 6 bits that represent the tuple length, which
  11524. are the bits starting at index 1 and going up to and including bit 6.
  11525. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11526. (shift right) can be used to accomplish this.
  11527. We compile the \code{allocate} form to operations on the
  11528. \code{free\_ptr}, as shown next. This approach is called
  11529. \emph{inline allocation} because it implements allocation without a
  11530. function call by simply incrementing the allocation pointer. It is much
  11531. more efficient than calling a function for each allocation. The
  11532. address in the \code{free\_ptr} is the next free address in the
  11533. FromSpace, so we copy it into \code{r11} and then move it forward by
  11534. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11535. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11536. the tag. We then initialize the \itm{tag} and finally copy the
  11537. address in \code{r11} to the left-hand side. Refer to
  11538. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11539. %
  11540. \racket{We recommend using the Racket operations
  11541. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11542. during compilation.}
  11543. %
  11544. \python{We recommend using the bitwise-or operator \code{|} and the
  11545. shift-left operator \code{<<} to compute the tag during
  11546. compilation.}
  11547. %
  11548. The type annotation in the \code{allocate} form is used to determine
  11549. the pointer mask region of the tag.
  11550. %
  11551. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11552. address of the \code{free\_ptr} global variable using a special
  11553. instruction-pointer-relative addressing mode of the x86-64 processor.
  11554. In particular, the assembler computes the distance $d$ between the
  11555. address of \code{free\_ptr} and where the \code{rip} would be at that
  11556. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11557. \code{$d$(\%rip)}, which at runtime will compute the address of
  11558. \code{free\_ptr}.
  11559. %
  11560. {\if\edition\racketEd
  11561. \begin{lstlisting}
  11562. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11563. |$\Longrightarrow$|
  11564. movq free_ptr(%rip), %r11
  11565. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11566. movq $|$\itm{tag}$|, 0(%r11)
  11567. movq %r11, |$\itm{lhs}'$|
  11568. \end{lstlisting}
  11569. \fi}
  11570. {\if\edition\pythonEd
  11571. \begin{lstlisting}
  11572. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11573. |$\Longrightarrow$|
  11574. movq free_ptr(%rip), %r11
  11575. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11576. movq $|$\itm{tag}$|, 0(%r11)
  11577. movq %r11, |$\itm{lhs}'$|
  11578. \end{lstlisting}
  11579. \fi}
  11580. %
  11581. The \code{collect} form is compiled to a call to the \code{collect}
  11582. function in the runtime. The arguments to \code{collect} are (1) the
  11583. top of the root stack, and (2) the number of bytes that need to be
  11584. allocated. We use another dedicated register, \code{r15}, to store
  11585. the pointer to the top of the root stack. Therefore \code{r15} is not
  11586. available for use by the register allocator.
  11587. %
  11588. {\if\edition\racketEd
  11589. \begin{lstlisting}
  11590. (collect |$\itm{bytes}$|)
  11591. |$\Longrightarrow$|
  11592. movq %r15, %rdi
  11593. movq $|\itm{bytes}|, %rsi
  11594. callq collect
  11595. \end{lstlisting}
  11596. \fi}
  11597. {\if\edition\pythonEd
  11598. \begin{lstlisting}
  11599. collect(|$\itm{bytes}$|)
  11600. |$\Longrightarrow$|
  11601. movq %r15, %rdi
  11602. movq $|\itm{bytes}|, %rsi
  11603. callq collect
  11604. \end{lstlisting}
  11605. \fi}
  11606. \newcommand{\GrammarXGlobal}{
  11607. \begin{array}{lcl}
  11608. \Arg &::=& \itm{label} \key{(\%rip)}
  11609. \end{array}
  11610. }
  11611. \newcommand{\ASTXGlobalRacket}{
  11612. \begin{array}{lcl}
  11613. \Arg &::=& \GLOBAL{\itm{label}}
  11614. \end{array}
  11615. }
  11616. \begin{figure}[tp]
  11617. \begin{tcolorbox}[colback=white]
  11618. \[
  11619. \begin{array}{l}
  11620. \gray{\GrammarXInt} \\ \hline
  11621. \gray{\GrammarXIf} \\ \hline
  11622. \GrammarXGlobal \\
  11623. \begin{array}{lcl}
  11624. \LangXGlobalM{} &::= & \key{.globl main} \\
  11625. & & \key{main:} \; \Instr^{*}
  11626. \end{array}
  11627. \end{array}
  11628. \]
  11629. \end{tcolorbox}
  11630. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  11631. \label{fig:x86-2-concrete}
  11632. \end{figure}
  11633. \begin{figure}[tp]
  11634. \begin{tcolorbox}[colback=white]
  11635. \small
  11636. \[
  11637. \begin{array}{l}
  11638. \gray{\ASTXIntRacket} \\ \hline
  11639. \gray{\ASTXIfRacket} \\ \hline
  11640. \ASTXGlobalRacket \\
  11641. \begin{array}{lcl}
  11642. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11643. \end{array}
  11644. \end{array}
  11645. \]
  11646. \end{tcolorbox}
  11647. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  11648. \label{fig:x86-2}
  11649. \end{figure}
  11650. The definitions of the concrete and abstract syntax of the
  11651. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  11652. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  11653. of global variables.
  11654. %
  11655. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11656. \code{select\_instructions} pass on the running example.
  11657. \begin{figure}[tbp]
  11658. \centering
  11659. \begin{tcolorbox}[colback=white]
  11660. % tests/s2_17.rkt
  11661. \begin{tabular}{lll}
  11662. \begin{minipage}{0.5\textwidth}
  11663. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11664. start:
  11665. tmp9 = (global-value free_ptr);
  11666. tmp0 = (+ tmp9 16);
  11667. tmp1 = (global-value fromspace_end);
  11668. if (< tmp0 tmp1)
  11669. goto block0;
  11670. else
  11671. goto block1;
  11672. block0:
  11673. _4 = (void);
  11674. goto block9;
  11675. block1:
  11676. (collect 16)
  11677. goto block9;
  11678. block9:
  11679. alloc2 = (allocate 1 (Vector Integer));
  11680. _3 = (vector-set! alloc2 0 42);
  11681. vecinit6 = alloc2;
  11682. tmp2 = (global-value free_ptr);
  11683. tmp3 = (+ tmp2 16);
  11684. tmp4 = (global-value fromspace_end);
  11685. if (< tmp3 tmp4)
  11686. goto block7;
  11687. else
  11688. goto block8;
  11689. block7:
  11690. _8 = (void);
  11691. goto block6;
  11692. block8:
  11693. (collect 16)
  11694. goto block6;
  11695. block6:
  11696. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11697. _7 = (vector-set! alloc5 0 vecinit6);
  11698. tmp5 = (vector-ref alloc5 0);
  11699. return (vector-ref tmp5 0);
  11700. \end{lstlisting}
  11701. \end{minipage}
  11702. &$\Rightarrow$&
  11703. \begin{minipage}{0.4\textwidth}
  11704. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11705. start:
  11706. movq free_ptr(%rip), tmp9
  11707. movq tmp9, tmp0
  11708. addq $16, tmp0
  11709. movq fromspace_end(%rip), tmp1
  11710. cmpq tmp1, tmp0
  11711. jl block0
  11712. jmp block1
  11713. block0:
  11714. movq $0, _4
  11715. jmp block9
  11716. block1:
  11717. movq %r15, %rdi
  11718. movq $16, %rsi
  11719. callq collect
  11720. jmp block9
  11721. block9:
  11722. movq free_ptr(%rip), %r11
  11723. addq $16, free_ptr(%rip)
  11724. movq $3, 0(%r11)
  11725. movq %r11, alloc2
  11726. movq alloc2, %r11
  11727. movq $42, 8(%r11)
  11728. movq $0, _3
  11729. movq alloc2, vecinit6
  11730. movq free_ptr(%rip), tmp2
  11731. movq tmp2, tmp3
  11732. addq $16, tmp3
  11733. movq fromspace_end(%rip), tmp4
  11734. cmpq tmp4, tmp3
  11735. jl block7
  11736. jmp block8
  11737. block7:
  11738. movq $0, _8
  11739. jmp block6
  11740. block8:
  11741. movq %r15, %rdi
  11742. movq $16, %rsi
  11743. callq collect
  11744. jmp block6
  11745. block6:
  11746. movq free_ptr(%rip), %r11
  11747. addq $16, free_ptr(%rip)
  11748. movq $131, 0(%r11)
  11749. movq %r11, alloc5
  11750. movq alloc5, %r11
  11751. movq vecinit6, 8(%r11)
  11752. movq $0, _7
  11753. movq alloc5, %r11
  11754. movq 8(%r11), tmp5
  11755. movq tmp5, %r11
  11756. movq 8(%r11), %rax
  11757. jmp conclusion
  11758. \end{lstlisting}
  11759. \end{minipage}
  11760. \end{tabular}
  11761. \end{tcolorbox}
  11762. \caption{Output of the \code{explicate\_control} (\emph{left}) and
  11763. \code{select\_instructions} (\emph{right}) passes on the running
  11764. example.}
  11765. \label{fig:select-instr-output-gc}
  11766. \end{figure}
  11767. \clearpage
  11768. \section{Register Allocation}
  11769. \label{sec:reg-alloc-gc}
  11770. \index{subject}{register allocation}
  11771. As discussed previously in this chapter, the garbage collector needs to
  11772. access all the pointers in the root set, that is, all variables that
  11773. are tuples. It will be the responsibility of the register allocator
  11774. to make sure that
  11775. \begin{enumerate}
  11776. \item the root stack is used for spilling tuple-typed variables, and
  11777. \item if a tuple-typed variable is live during a call to the
  11778. collector, it must be spilled to ensure that it is visible to the
  11779. collector.
  11780. \end{enumerate}
  11781. The latter responsibility can be handled during construction of the
  11782. interference graph, by adding interference edges between the call-live
  11783. tuple-typed variables and all the callee-saved registers. (They
  11784. already interfere with the caller-saved registers.)
  11785. %
  11786. \racket{The type information for variables is in the \code{Program}
  11787. form, so we recommend adding another parameter to the
  11788. \code{build\_interference} function to communicate this alist.}
  11789. %
  11790. \python{The type information for variables is generated by the type
  11791. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11792. the \code{CProgram} AST mode. You'll need to propagate that
  11793. information so that it is available in this pass.}
  11794. The spilling of tuple-typed variables to the root stack can be handled
  11795. after graph coloring, in choosing how to assign the colors
  11796. (integers) to registers and stack locations. The
  11797. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11798. changes to also record the number of spills to the root stack.
  11799. % build-interference
  11800. %
  11801. % callq
  11802. % extra parameter for var->type assoc. list
  11803. % update 'program' and 'if'
  11804. % allocate-registers
  11805. % allocate spilled vectors to the rootstack
  11806. % don't change color-graph
  11807. % TODO:
  11808. %\section{Patch Instructions}
  11809. %[mention that global variables are memory references]
  11810. \section{Prelude and Conclusion}
  11811. \label{sec:print-x86-gc}
  11812. \label{sec:prelude-conclusion-x86-gc}
  11813. \index{subject}{prelude}\index{subject}{conclusion}
  11814. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11815. \code{prelude\_and\_conclusion} pass on the running example. In the
  11816. prelude of the \code{main} function, we allocate space
  11817. on the root stack to make room for the spills of tuple-typed
  11818. variables. We do so by incrementing the root stack pointer (\code{r15}),
  11819. taking care that the root stack grows up instead of down. For the
  11820. running example, there was just one spill, so we increment \code{r15}
  11821. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11822. One issue that deserves special care is that there may be a call to
  11823. \code{collect} prior to the initializing assignments for all the
  11824. variables in the root stack. We do not want the garbage collector to
  11825. mistakenly determine that some uninitialized variable is a pointer that
  11826. needs to be followed. Thus, we zero out all locations on the root
  11827. stack in the prelude of \code{main}. In
  11828. figure~\ref{fig:print-x86-output-gc}, the instruction
  11829. %
  11830. \lstinline{movq $0, 0(%r15)}
  11831. %
  11832. is sufficient to accomplish this task because there is only one spill.
  11833. In general, we have to clear as many words as there are spills of
  11834. tuple-typed variables. The garbage collector tests each root to see
  11835. if it is null prior to dereferencing it.
  11836. \begin{figure}[htbp]
  11837. % TODO: Python Version -Jeremy
  11838. \begin{tcolorbox}[colback=white]
  11839. \begin{minipage}[t]{0.5\textwidth}
  11840. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11841. .globl main
  11842. main:
  11843. pushq %rbp
  11844. movq %rsp, %rbp
  11845. subq $0, %rsp
  11846. movq $65536, %rdi
  11847. movq $65536, %rsi
  11848. callq initialize
  11849. movq rootstack_begin(%rip), %r15
  11850. movq $0, 0(%r15)
  11851. addq $8, %r15
  11852. jmp start
  11853. conclusion:
  11854. subq $8, %r15
  11855. addq $0, %rsp
  11856. popq %rbp
  11857. retq
  11858. \end{lstlisting}
  11859. \end{minipage}
  11860. \end{tcolorbox}
  11861. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11862. \label{fig:print-x86-output-gc}
  11863. \end{figure}
  11864. \begin{figure}[tbp]
  11865. \begin{tcolorbox}[colback=white]
  11866. {\if\edition\racketEd
  11867. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11868. \node (Lvec) at (0,2) {\large \LangVec{}};
  11869. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11870. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11871. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  11872. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  11873. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  11874. \node (C2-4) at (0,0) {\large \LangCVec{}};
  11875. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  11876. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  11877. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  11878. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  11879. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  11880. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  11881. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11882. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11883. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  11884. \path[->,bend left=15] (Lvec-4) edge [right] node
  11885. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11886. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  11887. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11888. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  11889. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11890. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11891. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11892. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11893. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11894. \end{tikzpicture}
  11895. \fi}
  11896. {\if\edition\pythonEd
  11897. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  11898. \node (Lvec) at (0,2) {\large \LangVec{}};
  11899. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  11900. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  11901. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  11902. \node (C2-4) at (0,0) {\large \LangCVec{}};
  11903. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  11904. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  11905. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  11906. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  11907. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11908. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  11909. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  11910. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11911. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  11912. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  11913. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11914. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11915. \end{tikzpicture}
  11916. \fi}
  11917. \end{tcolorbox}
  11918. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11919. \label{fig:Lvec-passes}
  11920. \end{figure}
  11921. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11922. for the compilation of \LangVec{}.
  11923. \clearpage
  11924. {\if\edition\racketEd
  11925. \section{Challenge: Simple Structures}
  11926. \label{sec:simple-structures}
  11927. \index{subject}{struct}
  11928. \index{subject}{structure}
  11929. The language \LangStruct{} extends \LangVec{} with support for simple
  11930. structures. The definition of its concrete syntax is shown in
  11931. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  11932. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  11933. in Typed Racket is a user-defined data type that contains named fields
  11934. and that is heap allocated, similarly to a vector. The following is an
  11935. example of a structure definition, in this case the definition of a
  11936. \code{point} type:
  11937. \begin{lstlisting}
  11938. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11939. \end{lstlisting}
  11940. \newcommand{\LstructGrammarRacket}{
  11941. \begin{array}{lcl}
  11942. \Type &::=& \Var \\
  11943. \Exp &::=& (\Var\;\Exp \ldots)\\
  11944. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11945. \end{array}
  11946. }
  11947. \newcommand{\LstructASTRacket}{
  11948. \begin{array}{lcl}
  11949. \Type &::=& \VAR{\Var} \\
  11950. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11951. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11952. \end{array}
  11953. }
  11954. \begin{figure}[tbp]
  11955. \centering
  11956. \begin{tcolorbox}[colback=white]
  11957. \[
  11958. \begin{array}{l}
  11959. \gray{\LintGrammarRacket{}} \\ \hline
  11960. \gray{\LvarGrammarRacket{}} \\ \hline
  11961. \gray{\LifGrammarRacket{}} \\ \hline
  11962. \gray{\LwhileGrammarRacket} \\ \hline
  11963. \gray{\LtupGrammarRacket} \\ \hline
  11964. \LstructGrammarRacket \\
  11965. \begin{array}{lcl}
  11966. \LangStruct{} &::=& \Def \ldots \; \Exp
  11967. \end{array}
  11968. \end{array}
  11969. \]
  11970. \end{tcolorbox}
  11971. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11972. (figure~\ref{fig:Lvec-concrete-syntax}).}
  11973. \label{fig:Lstruct-concrete-syntax}
  11974. \end{figure}
  11975. \begin{figure}[tbp]
  11976. \centering
  11977. \begin{tcolorbox}[colback=white]
  11978. \small
  11979. \[
  11980. \begin{array}{l}
  11981. \gray{\LintASTRacket{}} \\ \hline
  11982. \gray{\LvarASTRacket{}} \\ \hline
  11983. \gray{\LifASTRacket{}} \\ \hline
  11984. \gray{\LwhileASTRacket} \\ \hline
  11985. \gray{\LtupASTRacket} \\ \hline
  11986. \LstructASTRacket \\
  11987. \begin{array}{lcl}
  11988. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11989. \end{array}
  11990. \end{array}
  11991. \]
  11992. \end{tcolorbox}
  11993. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11994. (figure~\ref{fig:Lvec-syntax}).}
  11995. \label{fig:Lstruct-syntax}
  11996. \end{figure}
  11997. An instance of a structure is created using function-call syntax, with
  11998. the name of the structure in the function position, as follows:
  11999. \begin{lstlisting}
  12000. (point 7 12)
  12001. \end{lstlisting}
  12002. Function-call syntax is also used to read a field of a structure. The
  12003. function name is formed by the structure name, a dash, and the field
  12004. name. The following example uses \code{point-x} and \code{point-y} to
  12005. access the \code{x} and \code{y} fields of two point instances:
  12006. \begin{center}
  12007. \begin{lstlisting}
  12008. (let ([pt1 (point 7 12)])
  12009. (let ([pt2 (point 4 3)])
  12010. (+ (- (point-x pt1) (point-x pt2))
  12011. (- (point-y pt1) (point-y pt2)))))
  12012. \end{lstlisting}
  12013. \end{center}
  12014. Similarly, to write to a field of a structure, use its set function,
  12015. whose name starts with \code{set-}, followed by the structure name,
  12016. then a dash, then the field name, and finally with an exclamation
  12017. mark. The following example uses \code{set-point-x!} to change the
  12018. \code{x} field from \code{7} to \code{42}:
  12019. \begin{center}
  12020. \begin{lstlisting}
  12021. (let ([pt (point 7 12)])
  12022. (let ([_ (set-point-x! pt 42)])
  12023. (point-x pt)))
  12024. \end{lstlisting}
  12025. \end{center}
  12026. \begin{exercise}\normalfont\normalsize
  12027. Create a type checker for \LangStruct{} by extending the type
  12028. checker for \LangVec{}. Extend your compiler with support for simple
  12029. structures, compiling \LangStruct{} to x86 assembly code. Create
  12030. five new test cases that use structures and, test your compiler.
  12031. \end{exercise}
  12032. % TODO: create an interpreter for L_struct
  12033. \clearpage
  12034. \fi}
  12035. \section{Challenge: Arrays}
  12036. \label{sec:arrays}
  12037. % TODO mention trapped-error
  12038. In this chapter we have studied tuples, that is, heterogeneous
  12039. sequences of elements whose length is determined at compile time. This
  12040. challenge is also about sequences, but this time the length is
  12041. determined at runtime and all the elements have the same type (they
  12042. are homogeneous). We use the term \emph{array} for this latter kind of
  12043. sequence.
  12044. %
  12045. \racket{
  12046. The Racket language does not distinguish between tuples and arrays;
  12047. they are both represented by vectors. However, Typed Racket
  12048. distinguishes between tuples and arrays: the \code{Vector} type is for
  12049. tuples, and the \code{Vectorof} type is for arrays.}
  12050. \python{
  12051. Arrays correspond to the \code{list} type in Python language.
  12052. }
  12053. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  12054. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  12055. presents the definition of the abstract syntax, extending \LangVec{}
  12056. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  12057. %
  12058. \racket{\code{make-vector} primitive operator for creating an array,
  12059. whose arguments are the length of the array and an initial value for
  12060. all the elements in the array.}
  12061. \python{bracket notation for creating an array literal.}
  12062. \racket{
  12063. The \code{vector-length},
  12064. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  12065. for tuples become overloaded for use with arrays.}
  12066. \python{
  12067. The subscript operator becomes overloaded for use with arrays and tuples
  12068. and now may appear on the left-hand side of an assignment.
  12069. Note that the index of the subscript, when applied to an array, may be an
  12070. arbitrary expression and not just a constant integer.
  12071. The \code{len} function is also applicable to arrays.
  12072. }
  12073. %
  12074. We include integer multiplication in \LangArray{}, because it is
  12075. useful in many examples involving arrays such as computing the
  12076. inner product of two arrays (figure~\ref{fig:inner_product}).
  12077. \newcommand{\LarrayGrammarRacket}{
  12078. \begin{array}{lcl}
  12079. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12080. \Exp &::=& \CMUL{\Exp}{\Exp}
  12081. \MID \CMAKEVEC{\Exp}{\Exp}
  12082. \end{array}
  12083. }
  12084. \newcommand{\LarrayASTRacket}{
  12085. \begin{array}{lcl}
  12086. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  12087. \Exp &::=& \MUL{\Exp}{\Exp}
  12088. \MID \MAKEVEC{\Exp}{\Exp}
  12089. \end{array}
  12090. }
  12091. \newcommand{\LarrayGrammarPython}{
  12092. \begin{array}{lcl}
  12093. \Type &::=& \key{list}\LS\Type\RS \\
  12094. \Exp &::=& \CMUL{\Exp}{\Exp}
  12095. \MID \CGET{\Exp}{\Exp}
  12096. \MID \LS \Exp \code{,} \ldots \RS \\
  12097. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  12098. \end{array}
  12099. }
  12100. \newcommand{\LarrayASTPython}{
  12101. \begin{array}{lcl}
  12102. \Type &::=& \key{ListType}\LP\Type\RP \\
  12103. \Exp &::=& \MUL{\Exp}{\Exp}
  12104. \MID \GET{\Exp}{\Exp} \\
  12105. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  12106. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  12107. \end{array}
  12108. }
  12109. \begin{figure}[tp]
  12110. \centering
  12111. \begin{tcolorbox}[colback=white]
  12112. \small
  12113. {\if\edition\racketEd
  12114. \[
  12115. \begin{array}{l}
  12116. \gray{\LintGrammarRacket{}} \\ \hline
  12117. \gray{\LvarGrammarRacket{}} \\ \hline
  12118. \gray{\LifGrammarRacket{}} \\ \hline
  12119. \gray{\LwhileGrammarRacket} \\ \hline
  12120. \gray{\LtupGrammarRacket} \\ \hline
  12121. \LarrayGrammarRacket \\
  12122. \begin{array}{lcl}
  12123. \LangArray{} &::=& \Exp
  12124. \end{array}
  12125. \end{array}
  12126. \]
  12127. \fi}
  12128. {\if\edition\pythonEd
  12129. \[
  12130. \begin{array}{l}
  12131. \gray{\LintGrammarPython{}} \\ \hline
  12132. \gray{\LvarGrammarPython{}} \\ \hline
  12133. \gray{\LifGrammarPython{}} \\ \hline
  12134. \gray{\LwhileGrammarPython} \\ \hline
  12135. \gray{\LtupGrammarPython} \\ \hline
  12136. \LarrayGrammarPython \\
  12137. \begin{array}{rcl}
  12138. \LangArrayM{} &::=& \Stmt^{*}
  12139. \end{array}
  12140. \end{array}
  12141. \]
  12142. \fi}
  12143. \end{tcolorbox}
  12144. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12145. \label{fig:Lvecof-concrete-syntax}
  12146. \end{figure}
  12147. \begin{figure}[tp]
  12148. \centering
  12149. \begin{tcolorbox}[colback=white]
  12150. \small
  12151. {\if\edition\racketEd
  12152. \[
  12153. \begin{array}{l}
  12154. \gray{\LintASTRacket{}} \\ \hline
  12155. \gray{\LvarASTRacket{}} \\ \hline
  12156. \gray{\LifASTRacket{}} \\ \hline
  12157. \gray{\LwhileASTRacket} \\ \hline
  12158. \gray{\LtupASTRacket} \\ \hline
  12159. \LarrayASTRacket \\
  12160. \begin{array}{lcl}
  12161. \LangArray{} &::=& \Exp
  12162. \end{array}
  12163. \end{array}
  12164. \]
  12165. \fi}
  12166. {\if\edition\pythonEd
  12167. \[
  12168. \begin{array}{l}
  12169. \gray{\LintASTPython{}} \\ \hline
  12170. \gray{\LvarASTPython{}} \\ \hline
  12171. \gray{\LifASTPython{}} \\ \hline
  12172. \gray{\LwhileASTPython} \\ \hline
  12173. \gray{\LtupASTPython} \\ \hline
  12174. \LarrayASTPython \\
  12175. \begin{array}{rcl}
  12176. \LangArrayM{} &::=& \Stmt^{*}
  12177. \end{array}
  12178. \end{array}
  12179. \]
  12180. \fi}
  12181. \end{tcolorbox}
  12182. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12183. \label{fig:Lvecof-syntax}
  12184. \end{figure}
  12185. \begin{figure}[tp]
  12186. \begin{tcolorbox}[colback=white]
  12187. {\if\edition\racketEd
  12188. % TODO: remove the function from the following example, like the python version -Jeremy
  12189. \begin{lstlisting}
  12190. (let ([A (make-vector 2 2)])
  12191. (let ([B (make-vector 2 3)])
  12192. (let ([i 0])
  12193. (let ([prod 0])
  12194. (begin
  12195. (while (< i n)
  12196. (begin
  12197. (set! prod (+ prod (* (vector-ref A i)
  12198. (vector-ref B i))))
  12199. (set! i (+ i 1))))
  12200. prod)))))
  12201. \end{lstlisting}
  12202. \fi}
  12203. {\if\edition\pythonEd
  12204. \begin{lstlisting}
  12205. A = [2, 2]
  12206. B = [3, 3]
  12207. i = 0
  12208. prod = 0
  12209. while i != len(A):
  12210. prod = prod + A[i] * B[i]
  12211. i = i + 1
  12212. print( prod )
  12213. \end{lstlisting}
  12214. \fi}
  12215. \end{tcolorbox}
  12216. \caption{Example program that computes the inner product.}
  12217. \label{fig:inner_product}
  12218. \end{figure}
  12219. {\if\edition\racketEd
  12220. %
  12221. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  12222. checker for \LangArray{}. The result type of
  12223. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  12224. of the initializing expression. The length expression is required to
  12225. have type \code{Integer}. The type checking of the operators
  12226. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  12227. updated to handle the situation in which the vector has type
  12228. \code{Vectorof}. In these cases we translate the operators to their
  12229. \code{vectorof} form so that later passes can easily distinguish
  12230. between operations on tuples versus arrays. We override the
  12231. \code{operator-types} method to provide the type signature for
  12232. multiplication: it takes two integers and returns an integer. \fi}
  12233. {\if\edition\pythonEd
  12234. %
  12235. The type checker for \LangArray{} is defined in
  12236. figure~\ref{fig:type-check-Lvecof}. The result type of a list literal
  12237. is \code{list[T]} where \code{T} is the type of the initializing
  12238. expressions. The type checking of the \code{len} function and the
  12239. subscript operator is updated to handle lists. The type checker now
  12240. also handles a subscript on the left-hand side of an assignment.
  12241. Regarding multiplication, it takes two integers and returns an
  12242. integer.
  12243. %
  12244. \fi}
  12245. \begin{figure}[tbp]
  12246. \begin{tcolorbox}[colback=white]
  12247. {\if\edition\racketEd
  12248. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12249. (define type-check-Lvecof-class
  12250. (class type-check-Lvec-class
  12251. (super-new)
  12252. (inherit check-type-equal?)
  12253. (define/override (operator-types)
  12254. (append '((* . ((Integer Integer) . Integer)))
  12255. (super operator-types)))
  12256. (define/override (type-check-exp env)
  12257. (lambda (e)
  12258. (define recur (type-check-exp env))
  12259. (match e
  12260. [(Prim 'make-vector (list e1 e2))
  12261. (define-values (e1^ t1) (recur e1))
  12262. (define-values (e2^ elt-type) (recur e2))
  12263. (define vec-type `(Vectorof ,elt-type))
  12264. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  12265. [(Prim 'vector-ref (list e1 e2))
  12266. (define-values (e1^ t1) (recur e1))
  12267. (define-values (e2^ t2) (recur e2))
  12268. (match* (t1 t2)
  12269. [(`(Vectorof ,elt-type) 'Integer)
  12270. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  12271. [(other wise) ((super type-check-exp env) e)])]
  12272. [(Prim 'vector-set! (list e1 e2 e3) )
  12273. (define-values (e-vec t-vec) (recur e1))
  12274. (define-values (e2^ t2) (recur e2))
  12275. (define-values (e-arg^ t-arg) (recur e3))
  12276. (match t-vec
  12277. [`(Vectorof ,elt-type)
  12278. (check-type-equal? elt-type t-arg e)
  12279. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  12280. [else ((super type-check-exp env) e)])]
  12281. [(Prim 'vector-length (list e1))
  12282. (define-values (e1^ t1) (recur e1))
  12283. (match t1
  12284. [`(Vectorof ,t)
  12285. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  12286. [else ((super type-check-exp env) e)])]
  12287. [else ((super type-check-exp env) e)])))
  12288. ))
  12289. (define (type-check-Lvecof p)
  12290. (send (new type-check-Lvecof-class) type-check-program p))
  12291. \end{lstlisting}
  12292. \fi}
  12293. {\if\edition\pythonEd
  12294. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12295. class TypeCheckLarray(TypeCheckLtup):
  12296. def type_check_exp(self, e, env):
  12297. match e:
  12298. case ast.List(es, Load()):
  12299. ts = [self.type_check_exp(e, env) for e in es]
  12300. elt_ty = ts[0]
  12301. for (ty, elt) in zip(ts, es):
  12302. self.check_type_equal(elt_ty, ty, elt)
  12303. e.has_type = ListType(elt_ty)
  12304. return e.has_type
  12305. case Call(Name('len'), [tup]):
  12306. tup_t = self.type_check_exp(tup, env)
  12307. tup.has_type = tup_t
  12308. match tup_t:
  12309. case TupleType(ts):
  12310. return IntType()
  12311. case ListType(ty):
  12312. return IntType()
  12313. case _:
  12314. raise Exception('len expected a tuple, not ' + repr(tup_t))
  12315. case Subscript(tup, index, Load()):
  12316. tup_ty = self.type_check_exp(tup, env)
  12317. index_ty = self.type_check_exp(index, env)
  12318. self.check_type_equal(index_ty, IntType(), index)
  12319. match tup_ty:
  12320. case TupleType(ts):
  12321. match index:
  12322. case Constant(i):
  12323. return ts[i]
  12324. case _:
  12325. raise Exception('subscript required constant integer index')
  12326. case ListType(ty):
  12327. return ty
  12328. case _:
  12329. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  12330. case BinOp(left, Mult(), right):
  12331. l = self.type_check_exp(left, env)
  12332. self.check_type_equal(l, IntType(), left)
  12333. r = self.type_check_exp(right, env)
  12334. self.check_type_equal(r, IntType(), right)
  12335. return IntType()
  12336. case _:
  12337. return super().type_check_exp(e, env)
  12338. def type_check_stmts(self, ss, env):
  12339. if len(ss) == 0:
  12340. return VoidType()
  12341. match ss[0]:
  12342. case Assign([Subscript(tup, index, Store())], value):
  12343. tup_t = self.type_check_exp(tup, env)
  12344. value_t = self.type_check_exp(value, env)
  12345. index_ty = self.type_check_exp(index, env)
  12346. self.check_type_equal(index_ty, IntType(), index)
  12347. match tup_t:
  12348. case ListType(ty):
  12349. self.check_type_equal(ty, value_t, ss[0])
  12350. case TupleType(ts):
  12351. return self.type_check_stmts(ss, env)
  12352. case _:
  12353. raise Exception('type_check_stmts: '
  12354. 'expected tuple or list, not ' + repr(tup_t))
  12355. return self.type_check_stmts(ss[1:], env)
  12356. case _:
  12357. return super().type_check_stmts(ss, env)
  12358. \end{lstlisting}
  12359. \fi}
  12360. \end{tcolorbox}
  12361. \caption{Type checker for the \LangArray{} language.}
  12362. \label{fig:type-check-Lvecof}
  12363. \end{figure}
  12364. The definition of the interpreter for \LangArray{} is shown in
  12365. figure~\ref{fig:interp-Lvecof}.
  12366. \racket{The \code{make-vector} operator is
  12367. interpreted using Racket's \code{make-vector} function,
  12368. and multiplication is interpreted using \code{fx*},
  12369. which is multiplication for \code{fixnum} integers.
  12370. In the \code{resolve} pass (Section~\ref{sec:array-resolution})
  12371. we translate array access operations
  12372. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  12373. which we interpret using \code{vector} operations with additional
  12374. bounds checks that signal a \code{trapped-error}.
  12375. }
  12376. %
  12377. \python{We implement list creation with a Python list comprehension
  12378. and multiplication is implemented with Python multiplication. We
  12379. add a case to handle a subscript on the left-hand side of
  12380. assignment. Other uses of subscript can be handled by the existing
  12381. code for tuples.}
  12382. \begin{figure}[tbp]
  12383. \begin{tcolorbox}[colback=white]
  12384. {\if\edition\racketEd
  12385. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12386. (define interp-Lvecof-class
  12387. (class interp-Lvec-class
  12388. (super-new)
  12389. (define/override (interp-op op)
  12390. (match op
  12391. ['make-vector make-vector]
  12392. ['vectorof-length vector-length]
  12393. ['vectorof-ref
  12394. (lambda (v i)
  12395. (if (< i (vector-length v))
  12396. (vector-ref v i)
  12397. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  12398. ['vectorof-set!
  12399. (lambda (v i e)
  12400. (if (< i (vector-length v))
  12401. (vector-set! v i e)
  12402. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  12403. [else (super interp-op op)]))
  12404. ))
  12405. (define (interp-Lvecof p)
  12406. (send (new interp-Lvecof-class) interp-program p))
  12407. \end{lstlisting}
  12408. \fi}
  12409. {\if\edition\pythonEd
  12410. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12411. class InterpLarray(InterpLtup):
  12412. def interp_exp(self, e, env):
  12413. match e:
  12414. case ast.List(es, Load()):
  12415. return [self.interp_exp(e, env) for e in es]
  12416. case BinOp(left, Mult(), right):
  12417. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  12418. return l * r
  12419. case _:
  12420. return super().interp_exp(e, env)
  12421. def interp_stmts(self, ss, env):
  12422. if len(ss) == 0:
  12423. return
  12424. match ss[0]:
  12425. case Assign([Subscript(lst, index)], value):
  12426. lst = self.interp_exp(lst, env)
  12427. index = self.interp_exp(index, env)
  12428. lst[index] = self.interp_exp(value, env)
  12429. return self.interp_stmts(ss[1:], env)
  12430. case _:
  12431. return super().interp_stmts(ss, env)
  12432. \end{lstlisting}
  12433. \fi}
  12434. \end{tcolorbox}
  12435. \caption{Interpreter for \LangArray{}.}
  12436. \label{fig:interp-Lvecof}
  12437. \end{figure}
  12438. \subsection{Data Representation}
  12439. \label{sec:array-rep}
  12440. Just as with tuples, we store arrays on the heap, which means that the
  12441. garbage collector will need to inspect arrays. An immediate thought is
  12442. to use the same representation for arrays that we use for tuples.
  12443. However, we limit tuples to a length of fifty so that their length and
  12444. pointer mask can fit into the 64-bit tag at the beginning of each
  12445. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  12446. millions of elements, so we need more bits to store the length.
  12447. However, because arrays are homogeneous, we need only 1 bit for the
  12448. pointer mask instead of 1 bit per array element. Finally, the
  12449. garbage collector must be able to distinguish between tuples
  12450. and arrays, so we need to reserve one bit for that purpose. We
  12451. arrive at the following layout for the 64-bit tag at the beginning of
  12452. an array:
  12453. \begin{itemize}
  12454. \item The right-most bit is the forwarding bit, just as in a tuple.
  12455. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  12456. that it is not.
  12457. \item The next bit to the left is the pointer mask. A $0$ indicates
  12458. that none of the elements are pointers to the heap, and a $1$
  12459. indicates that all the elements are pointers.
  12460. \item The next $60$ bits store the length of the array.
  12461. \item The bit at position $62$ distinguishes between a tuple ($0$)
  12462. and an array ($1$).
  12463. \item The left-most bit is reserved as explained in
  12464. chapter~\ref{ch:Lgrad}.
  12465. \end{itemize}
  12466. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  12467. %% differentiate the kinds of values that have been injected into the
  12468. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  12469. %% to indicate that the value is an array.
  12470. In the following subsections we provide hints regarding how to update
  12471. the passes to handle arrays.
  12472. \subsection{Overload Resolution}
  12473. \label{sec:array-resolution}
  12474. As noted previously, with the addition of arrays, several operators
  12475. have become \emph{overloaded}; that is, they can be applied to values
  12476. of more than one type. In this case, the element access and length
  12477. operators can be applied to both tuples and arrays. This kind of
  12478. overloading is quite common in programming languages, so many
  12479. compilers perform \emph{overload resolution}\index{subject}{overload
  12480. resolution} to handle it. The idea is to translate each overloaded
  12481. operator into different operators for the different types.
  12482. Implement a new pass named \code{resolve}.
  12483. Translate the reading of an array element
  12484. into a call to
  12485. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  12486. and the writing of an array element to
  12487. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  12488. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  12489. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  12490. When these operators are applied to tuples, leave them as is.
  12491. %
  12492. \python{The type checker for \LangArray{} adds a \code{has\_type}
  12493. field which can be inspected to determine whether the operator
  12494. is applied to a tuple or an array.}
  12495. \subsection{Bounds Checking}
  12496. Recall that the interpreter for \LangArray{} signals a
  12497. \code{trapped-error} when there is an array access that is out of
  12498. bounds. Therefore your compiler is obliged to also catch these errors
  12499. during execution and halt, signaling an error. We recommend inserting
  12500. a new pass named \code{check\_bounds} that inserts code around each
  12501. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  12502. \python{subscript} operation to ensure that the index is greater than
  12503. or equal to zero and less than the array's length. If not, the program
  12504. should halt, for which we recommend using a new primitive operation
  12505. named \code{exit}.
  12506. %% \subsection{Reveal Casts}
  12507. %% The array-access operators \code{vectorof-ref} and
  12508. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  12509. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  12510. %% that the type checker cannot tell whether the index will be in bounds,
  12511. %% so the bounds check must be performed at run time. Recall that the
  12512. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  12513. %% an \code{If} around a vector reference for update to check whether
  12514. %% the index is less than the length. You should do the same for
  12515. %% \code{vectorof-ref} and \code{vectorof-set!} .
  12516. %% In addition, the handling of the \code{any-vector} operators in
  12517. %% \code{reveal-casts} needs to be updated to account for arrays that are
  12518. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  12519. %% generated code should test whether the tag is for tuples (\code{010})
  12520. %% or arrays (\code{110}) and then dispatch to either
  12521. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  12522. %% we add a case in \code{select\_instructions} to generate the
  12523. %% appropriate instructions for accessing the array length from the
  12524. %% header of an array.
  12525. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  12526. %% the generated code needs to check that the index is less than the
  12527. %% vector length, so like the code for \code{any-vector-length}, check
  12528. %% the tag to determine whether to use \code{any-vector-length} or
  12529. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  12530. %% is complete, the generated code can use \code{any-vector-ref} and
  12531. %% \code{any-vector-set!} for both tuples and arrays because the
  12532. %% instructions used for those operators do not look at the tag at the
  12533. %% front of the tuple or array.
  12534. \subsection{Expose Allocation}
  12535. This pass should translate array creation into lower-level
  12536. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  12537. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  12538. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  12539. array. The \code{AllocateArray} AST node allocates an array of the
  12540. length specified by the $\Exp$ (of type \INTTY), but does not
  12541. initialize the elements of the array. Generate code in this pass to
  12542. initialize the elements analogous to the case for tuples.
  12543. {\if\edition\racketEd
  12544. \section{Uncover \texttt{get!}}
  12545. \label{sec:uncover-get-bang-vecof}
  12546. Add cases for \code{AllocateArray} to \code{collect-set!} and
  12547. \code{uncover-get!-exp}.
  12548. \fi}
  12549. \subsection{Remove Complex Operands}
  12550. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  12551. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  12552. complex, and its subexpression must be atomic.
  12553. \subsection{Explicate Control}
  12554. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  12555. \code{explicate\_assign}.
  12556. \subsection{Select Instructions}
  12557. Generate instructions for \code{AllocateArray} similar to those for
  12558. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  12559. except that the tag at the front of the array should instead use the
  12560. representation discussed in section~\ref{sec:array-rep}.
  12561. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  12562. extract the length from the tag.
  12563. The instructions generated for accessing an element of an array differ
  12564. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  12565. that the index is not a constant so you need to generate instructions
  12566. that compute the offset at runtime.
  12567. Compile the \code{exit} primitive into a call to the \code{exit}
  12568. function of the C standard library, with an argument of $255$.
  12569. %% Also, note that assignment to an array element may appear in
  12570. %% as a stand-alone statement, so make sure to handle that situation in
  12571. %% this pass.
  12572. %% Finally, the instructions for \code{any-vectorof-length} should be
  12573. %% similar to those for \code{vectorof-length}, except that one must
  12574. %% first project the array by writing zeroes into the $3$-bit tag
  12575. \begin{exercise}\normalfont\normalsize
  12576. Implement a compiler for the \LangArray{} language by extending your
  12577. compiler for \LangLoop{}. Test your compiler on a half dozen new
  12578. programs, including the one shown in figure~\ref{fig:inner_product}
  12579. and also a program that multiplies two matrices. Note that although
  12580. matrices are two-dimensional arrays, they can be encoded into
  12581. one-dimensional arrays by laying out each row in the array, one after
  12582. the next.
  12583. \end{exercise}
  12584. {\if\edition\racketEd
  12585. \section{Challenge: Generational Collection}
  12586. The copying collector described in section~\ref{sec:GC} can incur
  12587. significant runtime overhead because the call to \code{collect} takes
  12588. time proportional to all the live data. One way to reduce this
  12589. overhead is to reduce how much data is inspected in each call to
  12590. \code{collect}. In particular, researchers have observed that recently
  12591. allocated data is more likely to become garbage then data that has
  12592. survived one or more previous calls to \code{collect}. This insight
  12593. motivated the creation of \emph{generational garbage collectors}
  12594. \index{subject}{generational garbage collector} that
  12595. (1) segregate data according to its age into two or more generations;
  12596. (2) allocate less space for younger generations, so collecting them is
  12597. faster, and more space for the older generations; and (3) perform
  12598. collection on the younger generations more frequently than on older
  12599. generations~\citep{Wilson:1992fk}.
  12600. For this challenge assignment, the goal is to adapt the copying
  12601. collector implemented in \code{runtime.c} to use two generations, one
  12602. for young data and one for old data. Each generation consists of a
  12603. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12604. \code{collect} function to use the two generations:
  12605. \begin{enumerate}
  12606. \item Copy the young generation's FromSpace to its ToSpace and then
  12607. switch the role of the ToSpace and FromSpace
  12608. \item If there is enough space for the requested number of bytes in
  12609. the young FromSpace, then return from \code{collect}.
  12610. \item If there is not enough space in the young FromSpace for the
  12611. requested bytes, then move the data from the young generation to the
  12612. old one with the following steps:
  12613. \begin{enumerate}
  12614. \item[a.] If there is enough room in the old FromSpace, copy the young
  12615. FromSpace to the old FromSpace and then return.
  12616. \item[b.] If there is not enough room in the old FromSpace, then collect
  12617. the old generation by copying the old FromSpace to the old ToSpace
  12618. and swap the roles of the old FromSpace and ToSpace.
  12619. \item[c.] If there is enough room now, copy the young FromSpace to the
  12620. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12621. and ToSpace for the old generation. Copy the young FromSpace and
  12622. the old FromSpace into the larger FromSpace for the old
  12623. generation and then return.
  12624. \end{enumerate}
  12625. \end{enumerate}
  12626. We recommend that you generalize the \code{cheney} function so that it
  12627. can be used for all the copies mentioned: between the young FromSpace
  12628. and ToSpace, between the old FromSpace and ToSpace, and between the
  12629. young FromSpace and old FromSpace. This can be accomplished by adding
  12630. parameters to \code{cheney} that replace its use of the global
  12631. variables \code{fromspace\_begin}, \code{fromspace\_end},
  12632. \code{tospace\_begin}, and \code{tospace\_end}.
  12633. Note that the collection of the young generation does not traverse the
  12634. old generation. This introduces a potential problem: there may be
  12635. young data that is reachable only through pointers in the old
  12636. generation. If these pointers are not taken into account, the
  12637. collector could throw away young data that is live! One solution,
  12638. called \emph{pointer recording}, is to maintain a set of all the
  12639. pointers from the old generation into the new generation and consider
  12640. this set as part of the root set. To maintain this set, the compiler
  12641. must insert extra instructions around every \code{vector-set!}. If the
  12642. vector being modified is in the old generation, and if the value being
  12643. written is a pointer into the new generation, then that pointer must
  12644. be added to the set. Also, if the value being overwritten was a
  12645. pointer into the new generation, then that pointer should be removed
  12646. from the set.
  12647. \begin{exercise}\normalfont\normalsize
  12648. Adapt the \code{collect} function in \code{runtime.c} to implement
  12649. generational garbage collection, as outlined in this section.
  12650. Update the code generation for \code{vector-set!} to implement
  12651. pointer recording. Make sure that your new compiler and runtime
  12652. execute without error on your test suite.
  12653. \end{exercise}
  12654. \fi}
  12655. \section{Further Reading}
  12656. \citet{Appel90} describes many data representation approaches,
  12657. including the ones used in the compilation of Standard ML.
  12658. There are many alternatives to copying collectors (and their bigger
  12659. siblings, the generational collectors) with regard to garbage
  12660. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12661. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12662. collectors are that allocation is fast (just a comparison and pointer
  12663. increment), there is no fragmentation, cyclic garbage is collected,
  12664. and the time complexity of collection depends only on the amount of
  12665. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12666. main disadvantages of a two-space copying collector is that it uses a
  12667. lot of extra space and takes a long time to perform the copy, though
  12668. these problems are ameliorated in generational collectors.
  12669. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12670. small objects and generate a lot of garbage, so copying and
  12671. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12672. Garbage collection is an active research topic, especially concurrent
  12673. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12674. developing new techniques and revisiting old
  12675. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12676. meet every year at the International Symposium on Memory Management to
  12677. present these findings.
  12678. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12679. \chapter{Functions}
  12680. \label{ch:Lfun}
  12681. \index{subject}{function}
  12682. \setcounter{footnote}{0}
  12683. This chapter studies the compilation of a subset of \racket{Typed
  12684. Racket}\python{Python} in which only top-level function definitions
  12685. are allowed. This kind of function appears in the C programming
  12686. language, and it serves as an important stepping-stone to implementing
  12687. lexically scoped functions in the form of \key{lambda} abstractions,
  12688. which is the topic of chapter~\ref{ch:Llambda}.
  12689. \section{The \LangFun{} Language}
  12690. The concrete syntax and abstract syntax for function definitions and
  12691. function application are shown in
  12692. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  12693. which we define the \LangFun{} language. Programs in \LangFun{} begin
  12694. with zero or more function definitions. The function names from these
  12695. definitions are in scope for the entire program, including all the
  12696. function definitions, and therefore the ordering of function
  12697. definitions does not matter.
  12698. %
  12699. \python{The abstract syntax for function parameters in
  12700. figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12701. consists of a parameter name and its type. This design differs from
  12702. Python's \code{ast} module, which has a more complex structure for
  12703. function parameters to handle keyword parameters,
  12704. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12705. complex Python abstract syntax into the simpler syntax of
  12706. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12707. \code{FunctionDef} constructor are for decorators and a type
  12708. comment, neither of which are used by our compiler. We recommend
  12709. replacing them with \code{None} in the \code{shrink} pass.
  12710. }
  12711. %
  12712. The concrete syntax for function application
  12713. \index{subject}{function application}
  12714. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  12715. where the first expression
  12716. must evaluate to a function and the remaining expressions are the arguments. The
  12717. abstract syntax for function application is
  12718. $\APPLY{\Exp}{\Exp^*}$.
  12719. %% The syntax for function application does not include an explicit
  12720. %% keyword, which is error prone when using \code{match}. To alleviate
  12721. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12722. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12723. Functions are first-class in the sense that a function pointer
  12724. \index{subject}{function pointer} is data and can be stored in memory or passed
  12725. as a parameter to another function. Thus, there is a function
  12726. type, written
  12727. {\if\edition\racketEd
  12728. \begin{lstlisting}
  12729. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12730. \end{lstlisting}
  12731. \fi}
  12732. {\if\edition\pythonEd
  12733. \begin{lstlisting}
  12734. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12735. \end{lstlisting}
  12736. \fi}
  12737. %
  12738. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12739. through $\Type_n$ and whose return type is $\Type_R$. The main
  12740. limitation of these functions (with respect to
  12741. \racket{Racket}\python{Python} functions) is that they are not
  12742. lexically scoped. That is, the only external entities that can be
  12743. referenced from inside a function body are other globally defined
  12744. functions. The syntax of \LangFun{} prevents function definitions from
  12745. being nested inside each other.
  12746. \newcommand{\LfunGrammarRacket}{
  12747. \begin{array}{lcl}
  12748. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12749. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12750. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12751. \end{array}
  12752. }
  12753. \newcommand{\LfunASTRacket}{
  12754. \begin{array}{lcl}
  12755. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12756. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12757. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12758. \end{array}
  12759. }
  12760. \newcommand{\LfunGrammarPython}{
  12761. \begin{array}{lcl}
  12762. \Type &::=& \key{int}
  12763. \MID \key{bool} \MID \key{void}
  12764. \MID \key{tuple}\LS \Type^+ \RS
  12765. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12766. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12767. \Stmt &::=& \CRETURN{\Exp} \\
  12768. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12769. \end{array}
  12770. }
  12771. \newcommand{\LfunASTPython}{
  12772. \begin{array}{lcl}
  12773. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  12774. \MID \key{TupleType}\LS\Type^+\RS\\
  12775. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12776. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12777. \Stmt &::=& \RETURN{\Exp} \\
  12778. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  12779. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12780. \end{array}
  12781. }
  12782. \begin{figure}[tp]
  12783. \centering
  12784. \begin{tcolorbox}[colback=white]
  12785. \small
  12786. {\if\edition\racketEd
  12787. \[
  12788. \begin{array}{l}
  12789. \gray{\LintGrammarRacket{}} \\ \hline
  12790. \gray{\LvarGrammarRacket{}} \\ \hline
  12791. \gray{\LifGrammarRacket{}} \\ \hline
  12792. \gray{\LwhileGrammarRacket} \\ \hline
  12793. \gray{\LtupGrammarRacket} \\ \hline
  12794. \LfunGrammarRacket \\
  12795. \begin{array}{lcl}
  12796. \LangFunM{} &::=& \Def \ldots \; \Exp
  12797. \end{array}
  12798. \end{array}
  12799. \]
  12800. \fi}
  12801. {\if\edition\pythonEd
  12802. \[
  12803. \begin{array}{l}
  12804. \gray{\LintGrammarPython{}} \\ \hline
  12805. \gray{\LvarGrammarPython{}} \\ \hline
  12806. \gray{\LifGrammarPython{}} \\ \hline
  12807. \gray{\LwhileGrammarPython} \\ \hline
  12808. \gray{\LtupGrammarPython} \\ \hline
  12809. \LfunGrammarPython \\
  12810. \begin{array}{rcl}
  12811. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12812. \end{array}
  12813. \end{array}
  12814. \]
  12815. \fi}
  12816. \end{tcolorbox}
  12817. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  12818. \label{fig:Lfun-concrete-syntax}
  12819. \end{figure}
  12820. \begin{figure}[tp]
  12821. \centering
  12822. \begin{tcolorbox}[colback=white]
  12823. \small
  12824. {\if\edition\racketEd
  12825. \[
  12826. \begin{array}{l}
  12827. \gray{\LintOpAST} \\ \hline
  12828. \gray{\LvarASTRacket{}} \\ \hline
  12829. \gray{\LifASTRacket{}} \\ \hline
  12830. \gray{\LwhileASTRacket{}} \\ \hline
  12831. \gray{\LtupASTRacket{}} \\ \hline
  12832. \LfunASTRacket \\
  12833. \begin{array}{lcl}
  12834. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12835. \end{array}
  12836. \end{array}
  12837. \]
  12838. \fi}
  12839. {\if\edition\pythonEd
  12840. \[
  12841. \begin{array}{l}
  12842. \gray{\LintASTPython{}} \\ \hline
  12843. \gray{\LvarASTPython{}} \\ \hline
  12844. \gray{\LifASTPython{}} \\ \hline
  12845. \gray{\LwhileASTPython} \\ \hline
  12846. \gray{\LtupASTPython} \\ \hline
  12847. \LfunASTPython \\
  12848. \begin{array}{rcl}
  12849. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12850. \end{array}
  12851. \end{array}
  12852. \]
  12853. \fi}
  12854. \end{tcolorbox}
  12855. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  12856. \label{fig:Lfun-syntax}
  12857. \end{figure}
  12858. The program shown in figure~\ref{fig:Lfun-function-example} is a
  12859. representative example of defining and using functions in \LangFun{}.
  12860. We define a function \code{map} that applies some other function
  12861. \code{f} to both elements of a tuple and returns a new tuple
  12862. containing the results. We also define a function \code{inc}. The
  12863. program applies \code{map} to \code{inc} and
  12864. %
  12865. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12866. %
  12867. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12868. %
  12869. from which we return \code{42}.
  12870. \begin{figure}[tbp]
  12871. \begin{tcolorbox}[colback=white]
  12872. {\if\edition\racketEd
  12873. \begin{lstlisting}
  12874. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12875. : (Vector Integer Integer)
  12876. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12877. (define (inc [x : Integer]) : Integer
  12878. (+ x 1))
  12879. (vector-ref (map inc (vector 0 41)) 1)
  12880. \end{lstlisting}
  12881. \fi}
  12882. {\if\edition\pythonEd
  12883. \begin{lstlisting}
  12884. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12885. return f(v[0]), f(v[1])
  12886. def inc(x : int) -> int:
  12887. return x + 1
  12888. print( map(inc, (0, 41))[1] )
  12889. \end{lstlisting}
  12890. \fi}
  12891. \end{tcolorbox}
  12892. \caption{Example of using functions in \LangFun{}.}
  12893. \label{fig:Lfun-function-example}
  12894. \end{figure}
  12895. The definitional interpreter for \LangFun{} is shown in
  12896. figure~\ref{fig:interp-Lfun}. The case for the
  12897. %
  12898. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12899. %
  12900. AST is responsible for setting up the mutual recursion between the
  12901. top-level function definitions.
  12902. %
  12903. \racket{We use the classic back-patching
  12904. \index{subject}{back-patching} approach that uses mutable variables
  12905. and makes two passes over the function
  12906. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12907. top-level environment using a mutable cons cell for each function
  12908. definition. Note that the \code{lambda} value for each function is
  12909. incomplete; it does not yet include the environment. Once the
  12910. top-level environment has been constructed, we iterate over it and
  12911. update the \code{lambda} values to use the top-level environment.}
  12912. %
  12913. \python{We create a dictionary named \code{env} and fill it in
  12914. by mapping each function name to a new \code{Function} value,
  12915. each of which stores a reference to the \code{env}.
  12916. (We define the class \code{Function} for this purpose.)}
  12917. %
  12918. To interpret a function \racket{application}\python{call}, we match
  12919. the result of the function expression to obtain a function value. We
  12920. then extend the function's environment with the mapping of parameters to
  12921. argument values. Finally, we interpret the body of the function in
  12922. this extended environment.
  12923. \begin{figure}[tp]
  12924. \begin{tcolorbox}[colback=white]
  12925. {\if\edition\racketEd
  12926. \begin{lstlisting}
  12927. (define interp-Lfun-class
  12928. (class interp-Lvec-class
  12929. (super-new)
  12930. (define/override ((interp-exp env) e)
  12931. (define recur (interp-exp env))
  12932. (match e
  12933. [(Apply fun args)
  12934. (define fun-val (recur fun))
  12935. (define arg-vals (for/list ([e args]) (recur e)))
  12936. (match fun-val
  12937. [`(function (,xs ...) ,body ,fun-env)
  12938. (define params-args (for/list ([x xs] [arg arg-vals])
  12939. (cons x (box arg))))
  12940. (define new-env (append params-args fun-env))
  12941. ((interp-exp new-env) body)]
  12942. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12943. [else ((super interp-exp env) e)]
  12944. ))
  12945. (define/public (interp-def d)
  12946. (match d
  12947. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12948. (cons f (box `(function ,xs ,body ())))]))
  12949. (define/override (interp-program p)
  12950. (match p
  12951. [(ProgramDefsExp info ds body)
  12952. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12953. (for/list ([f (in-dict-values top-level)])
  12954. (set-box! f (match (unbox f)
  12955. [`(function ,xs ,body ())
  12956. `(function ,xs ,body ,top-level)])))
  12957. ((interp-exp top-level) body))]))
  12958. ))
  12959. (define (interp-Lfun p)
  12960. (send (new interp-Lfun-class) interp-program p))
  12961. \end{lstlisting}
  12962. \fi}
  12963. {\if\edition\pythonEd
  12964. \begin{lstlisting}
  12965. class InterpLfun(InterpLtup):
  12966. def apply_fun(self, fun, args, e):
  12967. match fun:
  12968. case Function(name, xs, body, env):
  12969. new_env = env.copy().update(zip(xs, args))
  12970. return self.interp_stmts(body, new_env)
  12971. case _:
  12972. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12973. def interp_exp(self, e, env):
  12974. match e:
  12975. case Call(Name('input_int'), []):
  12976. return super().interp_exp(e, env)
  12977. case Call(func, args):
  12978. f = self.interp_exp(func, env)
  12979. vs = [self.interp_exp(arg, env) for arg in args]
  12980. return self.apply_fun(f, vs, e)
  12981. case _:
  12982. return super().interp_exp(e, env)
  12983. def interp_stmts(self, ss, env):
  12984. if len(ss) == 0:
  12985. return
  12986. match ss[0]:
  12987. case Return(value):
  12988. return self.interp_exp(value, env)
  12989. case FunctionDef(name, params, bod, dl, returns, comment):
  12990. ps = [x for (x,t) in params]
  12991. env[name] = Function(name, ps, bod, env)
  12992. return self.interp_stmts(ss[1:], env)
  12993. case _:
  12994. return super().interp_stmts(ss, env)
  12995. def interp(self, p):
  12996. match p:
  12997. case Module(ss):
  12998. env = {}
  12999. self.interp_stmts(ss, env)
  13000. if 'main' in env.keys():
  13001. self.apply_fun(env['main'], [], None)
  13002. case _:
  13003. raise Exception('interp: unexpected ' + repr(p))
  13004. \end{lstlisting}
  13005. \fi}
  13006. \end{tcolorbox}
  13007. \caption{Interpreter for the \LangFun{} language.}
  13008. \label{fig:interp-Lfun}
  13009. \end{figure}
  13010. %\margincomment{TODO: explain type checker}
  13011. The type checker for \LangFun{} is shown in
  13012. figure~\ref{fig:type-check-Lfun}.
  13013. %
  13014. \python{(We omit the code that parses function parameters into the
  13015. simpler abstract syntax.)}
  13016. %
  13017. Similarly to the interpreter, the case for the
  13018. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13019. %
  13020. AST is responsible for setting up the mutual recursion between the
  13021. top-level function definitions. We begin by create a mapping
  13022. \code{env} from every function name to its type. We then type check
  13023. the program using this mapping.
  13024. %
  13025. In the case for function \racket{application}\python{call}, we match
  13026. the type of the function expression to a function type and check that
  13027. the types of the argument expressions are equal to the function's
  13028. parameter types. The type of the \racket{application}\python{call} as
  13029. a whole is the return type from the function type.
  13030. \begin{figure}[tp]
  13031. \begin{tcolorbox}[colback=white]
  13032. {\if\edition\racketEd
  13033. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13034. (define type-check-Lfun-class
  13035. (class type-check-Lvec-class
  13036. (super-new)
  13037. (inherit check-type-equal?)
  13038. (define/public (type-check-apply env e es)
  13039. (define-values (e^ ty) ((type-check-exp env) e))
  13040. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  13041. ((type-check-exp env) e)))
  13042. (match ty
  13043. [`(,ty^* ... -> ,rt)
  13044. (for ([arg-ty ty*] [param-ty ty^*])
  13045. (check-type-equal? arg-ty param-ty (Apply e es)))
  13046. (values e^ e* rt)]))
  13047. (define/override (type-check-exp env)
  13048. (lambda (e)
  13049. (match e
  13050. [(FunRef f n)
  13051. (values (FunRef f n) (dict-ref env f))]
  13052. [(Apply e es)
  13053. (define-values (e^ es^ rt) (type-check-apply env e es))
  13054. (values (Apply e^ es^) rt)]
  13055. [(Call e es)
  13056. (define-values (e^ es^ rt) (type-check-apply env e es))
  13057. (values (Call e^ es^) rt)]
  13058. [else ((super type-check-exp env) e)])))
  13059. (define/public (type-check-def env)
  13060. (lambda (e)
  13061. (match e
  13062. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  13063. (define new-env (append (map cons xs ps) env))
  13064. (define-values (body^ ty^) ((type-check-exp new-env) body))
  13065. (check-type-equal? ty^ rt body)
  13066. (Def f p:t* rt info body^)])))
  13067. (define/public (fun-def-type d)
  13068. (match d
  13069. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  13070. (define/override (type-check-program e)
  13071. (match e
  13072. [(ProgramDefsExp info ds body)
  13073. (define env (for/list ([d ds])
  13074. (cons (Def-name d) (fun-def-type d))))
  13075. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  13076. (define-values (body^ ty) ((type-check-exp env) body))
  13077. (check-type-equal? ty 'Integer body)
  13078. (ProgramDefsExp info ds^ body^)]))))
  13079. (define (type-check-Lfun p)
  13080. (send (new type-check-Lfun-class) type-check-program p))
  13081. \end{lstlisting}
  13082. \fi}
  13083. {\if\edition\pythonEd
  13084. \begin{lstlisting}
  13085. class TypeCheckLfun(TypeCheckLtup):
  13086. def type_check_exp(self, e, env):
  13087. match e:
  13088. case Call(Name('input_int'), []):
  13089. return super().type_check_exp(e, env)
  13090. case Call(func, args):
  13091. func_t = self.type_check_exp(func, env)
  13092. args_t = [self.type_check_exp(arg, env) for arg in args]
  13093. match func_t:
  13094. case FunctionType(params_t, return_t):
  13095. for (arg_t, param_t) in zip(args_t, params_t):
  13096. check_type_equal(param_t, arg_t, e)
  13097. return return_t
  13098. case _:
  13099. raise Exception('type_check_exp: in call, unexpected ' +
  13100. repr(func_t))
  13101. case _:
  13102. return super().type_check_exp(e, env)
  13103. def type_check_stmts(self, ss, env):
  13104. if len(ss) == 0:
  13105. return
  13106. match ss[0]:
  13107. case FunctionDef(name, params, body, dl, returns, comment):
  13108. new_env = env.copy().update(params)
  13109. rt = self.type_check_stmts(body, new_env)
  13110. check_type_equal(returns, rt, ss[0])
  13111. return self.type_check_stmts(ss[1:], env)
  13112. case Return(value):
  13113. return self.type_check_exp(value, env)
  13114. case _:
  13115. return super().type_check_stmts(ss, env)
  13116. def type_check(self, p):
  13117. match p:
  13118. case Module(body):
  13119. env = {}
  13120. for s in body:
  13121. match s:
  13122. case FunctionDef(name, params, bod, dl, returns, comment):
  13123. if name in env:
  13124. raise Exception('type_check: function ' +
  13125. repr(name) + ' defined twice')
  13126. params_t = [t for (x,t) in params]
  13127. env[name] = FunctionType(params_t, returns)
  13128. self.type_check_stmts(body, env)
  13129. case _:
  13130. raise Exception('type_check: unexpected ' + repr(p))
  13131. \end{lstlisting}
  13132. \fi}
  13133. \end{tcolorbox}
  13134. \caption{Type checker for the \LangFun{} language.}
  13135. \label{fig:type-check-Lfun}
  13136. \end{figure}
  13137. \clearpage
  13138. \section{Functions in x86}
  13139. \label{sec:fun-x86}
  13140. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  13141. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  13142. %% \margincomment{\tiny Talk about the return address on the
  13143. %% stack and what callq and retq does.\\ --Jeremy }
  13144. The x86 architecture provides a few features to support the
  13145. implementation of functions. We have already seen that there are
  13146. labels in x86 so that one can refer to the location of an instruction,
  13147. as is needed for jump instructions. Labels can also be used to mark
  13148. the beginning of the instructions for a function. Going further, we
  13149. can obtain the address of a label by using the \key{leaq}
  13150. instruction. For example, the following puts the address of the
  13151. \code{inc} label into the \code{rbx} register:
  13152. \begin{lstlisting}
  13153. leaq inc(%rip), %rbx
  13154. \end{lstlisting}
  13155. Recall from section~\ref{sec:select-instructions-gc} that
  13156. \verb!inc(%rip)! is an example of instruction-pointer-relative
  13157. addressing.
  13158. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  13159. to functions whose locations were given by a label, such as
  13160. \code{read\_int}. To support function calls in this chapter we instead
  13161. jump to functions whose location are given by an address in
  13162. a register; that is, we use \emph{indirect function calls}. The
  13163. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  13164. before the register name.\index{subject}{indirect function call}
  13165. \begin{lstlisting}
  13166. callq *%rbx
  13167. \end{lstlisting}
  13168. \subsection{Calling Conventions}
  13169. \label{sec:calling-conventions-fun}
  13170. \index{subject}{calling conventions}
  13171. The \code{callq} instruction provides partial support for implementing
  13172. functions: it pushes the return address on the stack and it jumps to
  13173. the target. However, \code{callq} does not handle
  13174. \begin{enumerate}
  13175. \item parameter passing,
  13176. \item pushing frames on the procedure call stack and popping them off,
  13177. or
  13178. \item determining how registers are shared by different functions.
  13179. \end{enumerate}
  13180. Regarding parameter passing, recall that the x86-64 calling
  13181. convention for Unix-based system uses the following six registers to
  13182. pass arguments to a function, in the given order.
  13183. \begin{lstlisting}
  13184. rdi rsi rdx rcx r8 r9
  13185. \end{lstlisting}
  13186. If there are more than six arguments, then the calling convention
  13187. mandates using space on the frame of the caller for the rest of the
  13188. arguments. However, to ease the implementation of efficient tail calls
  13189. (section~\ref{sec:tail-call}), we arrange never to need more than six
  13190. arguments.
  13191. %
  13192. The return value of the function is stored in register \code{rax}.
  13193. \index{subject}{prelude}\index{subject}{conclusion}
  13194. Regarding frames \index{subject}{frame} and the procedure call stack,
  13195. \index{subject}{procedure call stack} recall from
  13196. section~\ref{sec:x86} that the stack grows down and each function call
  13197. uses a chunk of space on the stack called a frame. The caller sets the
  13198. stack pointer, register \code{rsp}, to the last data item in its
  13199. frame. The callee must not change anything in the caller's frame, that
  13200. is, anything that is at or above the stack pointer. The callee is free
  13201. to use locations that are below the stack pointer.
  13202. Recall that we store variables of tuple type on the root stack. So,
  13203. the prelude of a function needs to move the root stack pointer
  13204. \code{r15} up according to the number of variables of tuple type and
  13205. the conclusion needs to move the root stack pointer back down. Also,
  13206. the prelude must initialize to \code{0} this frame's slots in the root
  13207. stack to signal to the garbage collector that those slots do not yet
  13208. contain a valid pointer. Otherwise the garbage collector will
  13209. interpret the garbage bits in those slots as memory addresses and try
  13210. to traverse them, causing serious mayhem!
  13211. Regarding the sharing of registers between different functions, recall
  13212. from section~\ref{sec:calling-conventions} that the registers are
  13213. divided into two groups, the caller-saved registers and the
  13214. callee-saved registers. The caller should assume that all the
  13215. caller-saved registers are overwritten with arbitrary values by the
  13216. callee. For that reason we recommend in
  13217. section~\ref{sec:calling-conventions} that variables that are live
  13218. during a function call should not be assigned to caller-saved
  13219. registers.
  13220. On the flip side, if the callee wants to use a callee-saved register,
  13221. the callee must save the contents of those registers on their stack
  13222. frame and then put them back prior to returning to the caller. For
  13223. that reason we recommend in section~\ref{sec:calling-conventions} that if
  13224. the register allocator assigns a variable to a callee-saved register,
  13225. then the prelude of the \code{main} function must save that register
  13226. to the stack and the conclusion of \code{main} must restore it. This
  13227. recommendation now generalizes to all functions.
  13228. Recall that the base pointer, register \code{rbp}, is used as a
  13229. point of reference within a frame, so that each local variable can be
  13230. accessed at a fixed offset from the base pointer
  13231. (section~\ref{sec:x86}).
  13232. %
  13233. Figure~\ref{fig:call-frames} shows the general layout of the caller
  13234. and callee frames.
  13235. \begin{figure}[tbp]
  13236. \centering
  13237. \begin{tcolorbox}[colback=white]
  13238. \begin{tabular}{r|r|l|l} \hline
  13239. Caller View & Callee View & Contents & Frame \\ \hline
  13240. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  13241. 0(\key{\%rbp}) & & old \key{rbp} \\
  13242. -8(\key{\%rbp}) & & callee-saved $1$ \\
  13243. \ldots & & \ldots \\
  13244. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  13245. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  13246. \ldots & & \ldots \\
  13247. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  13248. %% & & \\
  13249. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  13250. %% & \ldots & \ldots \\
  13251. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  13252. \hline
  13253. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  13254. & 0(\key{\%rbp}) & old \key{rbp} \\
  13255. & -8(\key{\%rbp}) & callee-saved $1$ \\
  13256. & \ldots & \ldots \\
  13257. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  13258. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  13259. & \ldots & \ldots \\
  13260. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  13261. \end{tabular}
  13262. \end{tcolorbox}
  13263. \caption{Memory layout of caller and callee frames.}
  13264. \label{fig:call-frames}
  13265. \end{figure}
  13266. %% Recall from section~\ref{sec:x86} that the stack is also used for
  13267. %% local variables and for storing the values of callee-saved registers
  13268. %% (we shall refer to all of these collectively as ``locals''), and that
  13269. %% at the beginning of a function we move the stack pointer \code{rsp}
  13270. %% down to make room for them.
  13271. %% We recommend storing the local variables
  13272. %% first and then the callee-saved registers, so that the local variables
  13273. %% can be accessed using \code{rbp} the same as before the addition of
  13274. %% functions.
  13275. %% To make additional room for passing arguments, we shall
  13276. %% move the stack pointer even further down. We count how many stack
  13277. %% arguments are needed for each function call that occurs inside the
  13278. %% body of the function and find their maximum. Adding this number to the
  13279. %% number of locals gives us how much the \code{rsp} should be moved at
  13280. %% the beginning of the function. In preparation for a function call, we
  13281. %% offset from \code{rsp} to set up the stack arguments. We put the first
  13282. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  13283. %% so on.
  13284. %% Upon calling the function, the stack arguments are retrieved by the
  13285. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  13286. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  13287. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  13288. %% the layout of the caller and callee frames. Notice how important it is
  13289. %% that we correctly compute the maximum number of arguments needed for
  13290. %% function calls; if that number is too small then the arguments and
  13291. %% local variables will smash into each other!
  13292. \subsection{Efficient Tail Calls}
  13293. \label{sec:tail-call}
  13294. In general, the amount of stack space used by a program is determined
  13295. by the longest chain of nested function calls. That is, if function
  13296. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  13297. amount of stack space is linear in $n$. The depth $n$ can grow quite
  13298. large if functions are recursive. However, in some cases we can
  13299. arrange to use only a constant amount of space for a long chain of
  13300. nested function calls.
  13301. A \emph{tail call}\index{subject}{tail call} is a function call that
  13302. happens as the last action in a function body. For example, in the
  13303. following program, the recursive call to \code{tail\_sum} is a tail
  13304. call:
  13305. \begin{center}
  13306. {\if\edition\racketEd
  13307. \begin{lstlisting}
  13308. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  13309. (if (eq? n 0)
  13310. r
  13311. (tail_sum (- n 1) (+ n r))))
  13312. (+ (tail_sum 3 0) 36)
  13313. \end{lstlisting}
  13314. \fi}
  13315. {\if\edition\pythonEd
  13316. \begin{lstlisting}
  13317. def tail_sum(n : int, r : int) -> int:
  13318. if n == 0:
  13319. return r
  13320. else:
  13321. return tail_sum(n - 1, n + r)
  13322. print( tail_sum(3, 0) + 36)
  13323. \end{lstlisting}
  13324. \fi}
  13325. \end{center}
  13326. At a tail call, the frame of the caller is no longer needed, so we can
  13327. pop the caller's frame before making the tail call. With this
  13328. approach, a recursive function that makes only tail calls ends up
  13329. using a constant amount of stack space. Functional languages like
  13330. Racket rely heavily on recursive functions, so the definition of
  13331. Racket \emph{requires} that all tail calls be optimized in this way.
  13332. \index{subject}{frame}
  13333. Some care is needed with regard to argument passing in tail calls. As
  13334. mentioned, for arguments beyond the sixth, the convention is to use
  13335. space in the caller's frame for passing arguments. However, for a
  13336. tail call we pop the caller's frame and can no longer use it. An
  13337. alternative is to use space in the callee's frame for passing
  13338. arguments. However, this option is also problematic because the caller
  13339. and callee's frames overlap in memory. As we begin to copy the
  13340. arguments from their sources in the caller's frame, the target
  13341. locations in the callee's frame might collide with the sources for
  13342. later arguments! We solve this problem by using the heap instead of
  13343. the stack for passing more than six arguments
  13344. (section~\ref{sec:limit-functions-r4}).
  13345. As mentioned, for a tail call we pop the caller's frame prior to
  13346. making the tail call. The instructions for popping a frame are the
  13347. instructions that we usually place in the conclusion of a
  13348. function. Thus, we also need to place such code immediately before
  13349. each tail call. These instructions include restoring the callee-saved
  13350. registers, so it is fortunate that the argument passing registers are
  13351. all caller-saved registers.
  13352. One note remains regarding which instruction to use to make the tail
  13353. call. When the callee is finished, it should not return to the current
  13354. function but instead return to the function that called the current
  13355. one. Thus, the return address that is already on the stack is the
  13356. right one, and we should not use \key{callq} to make the tail call
  13357. because that would overwrite the return address. Instead we simply use
  13358. the \key{jmp} instruction. As with the indirect function call, we write
  13359. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  13360. prefixed with an asterisk. We recommend using \code{rax} to hold the
  13361. jump target because the conclusion can overwrite just about everything
  13362. else.
  13363. \begin{lstlisting}
  13364. jmp *%rax
  13365. \end{lstlisting}
  13366. \section{Shrink \LangFun{}}
  13367. \label{sec:shrink-r4}
  13368. The \code{shrink} pass performs a minor modification to ease the
  13369. later passes. This pass introduces an explicit \code{main} function
  13370. that gobbles up all the top-level statements of the module.
  13371. %
  13372. \racket{It also changes the top \code{ProgramDefsExp} form to
  13373. \code{ProgramDefs}.}
  13374. {\if\edition\racketEd
  13375. \begin{lstlisting}
  13376. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  13377. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  13378. \end{lstlisting}
  13379. where $\itm{mainDef}$ is
  13380. \begin{lstlisting}
  13381. (Def 'main '() 'Integer '() |$\Exp'$|)
  13382. \end{lstlisting}
  13383. \fi}
  13384. {\if\edition\pythonEd
  13385. \begin{lstlisting}
  13386. Module(|$\Def\ldots\Stmt\ldots$|)
  13387. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  13388. \end{lstlisting}
  13389. where $\itm{mainDef}$ is
  13390. \begin{lstlisting}
  13391. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  13392. \end{lstlisting}
  13393. \fi}
  13394. \section{Reveal Functions and the \LangFunRef{} language}
  13395. \label{sec:reveal-functions-r4}
  13396. The syntax of \LangFun{} is inconvenient for purposes of compilation
  13397. in that it conflates the use of function names and local
  13398. variables. This is a problem because we need to compile the use of a
  13399. function name differently from the use of a local variable. In
  13400. particular, we use \code{leaq} to convert the function name (a label
  13401. in x86) to an address in a register. Thus, we create a new pass that
  13402. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  13403. $n$ is the arity of the function.\python{\footnote{The arity is not
  13404. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  13405. This pass is named \code{reveal\_functions} and the output language
  13406. is \LangFunRef{}.
  13407. %is defined in figure~\ref{fig:f1-syntax}.
  13408. %% The concrete syntax for a
  13409. %% function reference is $\CFUNREF{f}$.
  13410. %% \begin{figure}[tp]
  13411. %% \centering
  13412. %% \fbox{
  13413. %% \begin{minipage}{0.96\textwidth}
  13414. %% {\if\edition\racketEd
  13415. %% \[
  13416. %% \begin{array}{lcl}
  13417. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  13418. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13419. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  13420. %% \end{array}
  13421. %% \]
  13422. %% \fi}
  13423. %% {\if\edition\pythonEd
  13424. %% \[
  13425. %% \begin{array}{lcl}
  13426. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  13427. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  13428. %% \end{array}
  13429. %% \]
  13430. %% \fi}
  13431. %% \end{minipage}
  13432. %% }
  13433. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  13434. %% (figure~\ref{fig:Lfun-syntax}).}
  13435. %% \label{fig:f1-syntax}
  13436. %% \end{figure}
  13437. %% Distinguishing between calls in tail position and non-tail position
  13438. %% requires the pass to have some notion of context. We recommend using
  13439. %% two mutually recursive functions, one for processing expressions in
  13440. %% tail position and another for the rest.
  13441. \racket{Placing this pass after \code{uniquify} will make sure that
  13442. there are no local variables and functions that share the same
  13443. name.}
  13444. %
  13445. The \code{reveal\_functions} pass should come before the
  13446. \code{remove\_complex\_operands} pass because function references
  13447. should be categorized as complex expressions.
  13448. \section{Limit Functions}
  13449. \label{sec:limit-functions-r4}
  13450. Recall that we wish to limit the number of function parameters to six
  13451. so that we do not need to use the stack for argument passing, which
  13452. makes it easier to implement efficient tail calls. However, because
  13453. the input language \LangFun{} supports arbitrary numbers of function
  13454. arguments, we have some work to do! The \code{limit\_functions} pass
  13455. transforms functions and function calls that involve more than six
  13456. arguments to pass the first five arguments as usual, but it packs the
  13457. rest of the arguments into a tuple and passes it as the sixth
  13458. argument.\footnote{The implementation this pass can be postponed to
  13459. last because you can test the rest of the passes on functions with
  13460. six or fewer parameters.}
  13461. Each function definition with seven or more parameters is transformed as
  13462. follows.
  13463. {\if\edition\racketEd
  13464. \begin{lstlisting}
  13465. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  13466. |$\Rightarrow$|
  13467. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  13468. \end{lstlisting}
  13469. \fi}
  13470. {\if\edition\pythonEd
  13471. \begin{lstlisting}
  13472. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  13473. |$\Rightarrow$|
  13474. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  13475. |$T_r$|, None, |$\itm{body}'$|, None)
  13476. \end{lstlisting}
  13477. \fi}
  13478. %
  13479. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  13480. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  13481. the $k$th element of the tuple, where $k = i - 6$.
  13482. %
  13483. {\if\edition\racketEd
  13484. \begin{lstlisting}
  13485. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  13486. \end{lstlisting}
  13487. \fi}
  13488. {\if\edition\pythonEd
  13489. \begin{lstlisting}
  13490. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  13491. \end{lstlisting}
  13492. \fi}
  13493. For function calls with too many arguments, the \code{limit\_functions}
  13494. pass transforms them in the following way:
  13495. \begin{tabular}{lll}
  13496. \begin{minipage}{0.3\textwidth}
  13497. {\if\edition\racketEd
  13498. \begin{lstlisting}
  13499. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  13500. \end{lstlisting}
  13501. \fi}
  13502. {\if\edition\pythonEd
  13503. \begin{lstlisting}
  13504. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  13505. \end{lstlisting}
  13506. \fi}
  13507. \end{minipage}
  13508. &
  13509. $\Rightarrow$
  13510. &
  13511. \begin{minipage}{0.5\textwidth}
  13512. {\if\edition\racketEd
  13513. \begin{lstlisting}
  13514. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  13515. \end{lstlisting}
  13516. \fi}
  13517. {\if\edition\pythonEd
  13518. \begin{lstlisting}
  13519. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  13520. \end{lstlisting}
  13521. \fi}
  13522. \end{minipage}
  13523. \end{tabular}
  13524. \section{Remove Complex Operands}
  13525. \label{sec:rco-r4}
  13526. The primary decisions to make for this pass are whether to classify
  13527. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  13528. atomic or complex expressions. Recall that an atomic expression will
  13529. end up as an immediate argument of an x86 instruction. Function
  13530. application will be translated to a sequence of instructions, so
  13531. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  13532. complex expression. On the other hand, the arguments of
  13533. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  13534. expressions.
  13535. %
  13536. Regarding \code{FunRef}, as discussed previously, the function label
  13537. needs to be converted to an address using the \code{leaq}
  13538. instruction. Thus, even though \code{FunRef} seems rather simple, it
  13539. needs to be classified as a complex expression so that we generate an
  13540. assignment statement with a left-hand side that can serve as the
  13541. target of the \code{leaq}.
  13542. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  13543. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  13544. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  13545. and augments programs to include a list of function definitions.
  13546. %
  13547. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  13548. \newcommand{\LfunMonadASTRacket}{
  13549. \begin{array}{lcl}
  13550. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13551. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13552. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13553. \end{array}
  13554. }
  13555. \newcommand{\LfunMonadASTPython}{
  13556. \begin{array}{lcl}
  13557. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  13558. \MID \key{TupleType}\LS\Type^+\RS\\
  13559. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13560. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  13561. \Stmt &::=& \RETURN{\Exp} \\
  13562. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13563. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13564. \end{array}
  13565. }
  13566. \begin{figure}[tp]
  13567. \centering
  13568. \begin{tcolorbox}[colback=white]
  13569. \small
  13570. {\if\edition\racketEd
  13571. \[
  13572. \begin{array}{l}
  13573. \gray{\LvarMonadASTRacket} \\ \hline
  13574. \gray{\LifMonadASTRacket} \\ \hline
  13575. \gray{\LwhileMonadASTRacket} \\ \hline
  13576. \gray{\LtupMonadASTRacket} \\ \hline
  13577. \LfunMonadASTRacket \\
  13578. \begin{array}{rcl}
  13579. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13580. \end{array}
  13581. \end{array}
  13582. \]
  13583. \fi}
  13584. {\if\edition\pythonEd
  13585. \[
  13586. \begin{array}{l}
  13587. \gray{\LvarMonadASTPython} \\ \hline
  13588. \gray{\LifMonadASTPython} \\ \hline
  13589. \gray{\LwhileMonadASTPython} \\ \hline
  13590. \gray{\LtupMonadASTPython} \\ \hline
  13591. \LfunMonadASTPython \\
  13592. \begin{array}{rcl}
  13593. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13594. \end{array}
  13595. \end{array}
  13596. \]
  13597. \fi}
  13598. \end{tcolorbox}
  13599. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  13600. \label{fig:Lfun-anf-syntax}
  13601. \end{figure}
  13602. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  13603. %% \LangFunANF{} of this pass.
  13604. %% \begin{figure}[tp]
  13605. %% \centering
  13606. %% \fbox{
  13607. %% \begin{minipage}{0.96\textwidth}
  13608. %% \small
  13609. %% \[
  13610. %% \begin{array}{rcl}
  13611. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  13612. %% \MID \VOID{} } \\
  13613. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  13614. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  13615. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  13616. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  13617. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  13618. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  13619. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  13620. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  13621. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  13622. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  13623. %% \end{array}
  13624. %% \]
  13625. %% \end{minipage}
  13626. %% }
  13627. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  13628. %% \label{fig:Lfun-anf-syntax}
  13629. %% \end{figure}
  13630. \section{Explicate Control and the \LangCFun{} language}
  13631. \label{sec:explicate-control-r4}
  13632. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  13633. output of \code{explicate\_control}.
  13634. %
  13635. %% \racket{(The concrete syntax is given in
  13636. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  13637. %
  13638. The auxiliary functions for assignment\racket{ and tail contexts} should
  13639. be updated with cases for
  13640. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13641. function for predicate context should be updated for
  13642. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13643. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13644. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13645. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13646. auxiliary function for processing function definitions. This code is
  13647. similar to the case for \code{Program} in \LangVec{}. The top-level
  13648. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13649. form of \LangFun{} can then apply this new function to all the
  13650. function definitions.
  13651. {\if\edition\pythonEd
  13652. The translation of \code{Return} statements requires a new auxiliary
  13653. function to handle expressions in tail context, called
  13654. \code{explicate\_tail}. The function should take an expression and the
  13655. dictionary of basic blocks and produce a list of statements in the
  13656. \LangCFun{} language. The \code{explicate\_tail} function should
  13657. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13658. and a default case for other kinds of expressions. The default case
  13659. should produce a \code{Return} statement. The case for \code{Call}
  13660. should change it into \code{TailCall}. The other cases should
  13661. recursively process their subexpressions and statements, choosing the
  13662. appropriate explicate functions for the various contexts.
  13663. \fi}
  13664. \newcommand{\CfunASTRacket}{
  13665. \begin{array}{lcl}
  13666. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13667. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13668. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13669. \end{array}
  13670. }
  13671. \newcommand{\CfunASTPython}{
  13672. \begin{array}{lcl}
  13673. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13674. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13675. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13676. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13677. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13678. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13679. \end{array}
  13680. }
  13681. \begin{figure}[tp]
  13682. \begin{tcolorbox}[colback=white]
  13683. \small
  13684. {\if\edition\racketEd
  13685. \[
  13686. \begin{array}{l}
  13687. \gray{\CvarASTRacket} \\ \hline
  13688. \gray{\CifASTRacket} \\ \hline
  13689. \gray{\CloopASTRacket} \\ \hline
  13690. \gray{\CtupASTRacket} \\ \hline
  13691. \CfunASTRacket \\
  13692. \begin{array}{lcl}
  13693. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13694. \end{array}
  13695. \end{array}
  13696. \]
  13697. \fi}
  13698. {\if\edition\pythonEd
  13699. \[
  13700. \begin{array}{l}
  13701. \gray{\CifASTPython} \\ \hline
  13702. \gray{\CtupASTPython} \\ \hline
  13703. \CfunASTPython \\
  13704. \begin{array}{lcl}
  13705. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13706. \end{array}
  13707. \end{array}
  13708. \]
  13709. \fi}
  13710. \end{tcolorbox}
  13711. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  13712. \label{fig:c3-syntax}
  13713. \end{figure}
  13714. \clearpage
  13715. \section{Select Instructions and the \LangXIndCall{} Language}
  13716. \label{sec:select-r4}
  13717. \index{subject}{instruction selection}
  13718. The output of select instructions is a program in the \LangXIndCall{}
  13719. language; the definition of its concrete syntax is shown in
  13720. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  13721. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  13722. directive on the labels of function definitions to make sure the
  13723. bottom three bits are zero, which we put to use in
  13724. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  13725. this section. \index{subject}{x86}
  13726. \newcommand{\GrammarXIndCall}{
  13727. \begin{array}{lcl}
  13728. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13729. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13730. \Block &::= & \Instr^{+} \\
  13731. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13732. \end{array}
  13733. }
  13734. \newcommand{\ASTXIndCallRacket}{
  13735. \begin{array}{lcl}
  13736. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13737. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13738. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13739. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13740. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13741. \end{array}
  13742. }
  13743. \begin{figure}[tp]
  13744. \begin{tcolorbox}[colback=white]
  13745. \small
  13746. \[
  13747. \begin{array}{l}
  13748. \gray{\GrammarXInt} \\ \hline
  13749. \gray{\GrammarXIf} \\ \hline
  13750. \gray{\GrammarXGlobal} \\ \hline
  13751. \GrammarXIndCall \\
  13752. \begin{array}{lcl}
  13753. \LangXIndCallM{} &::= & \Def^{*}
  13754. \end{array}
  13755. \end{array}
  13756. \]
  13757. \end{tcolorbox}
  13758. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  13759. \label{fig:x86-3-concrete}
  13760. \end{figure}
  13761. \begin{figure}[tp]
  13762. \begin{tcolorbox}[colback=white]
  13763. \small
  13764. {\if\edition\racketEd
  13765. \[\arraycolsep=3pt
  13766. \begin{array}{l}
  13767. \gray{\ASTXIntRacket} \\ \hline
  13768. \gray{\ASTXIfRacket} \\ \hline
  13769. \gray{\ASTXGlobalRacket} \\ \hline
  13770. \ASTXIndCallRacket \\
  13771. \begin{array}{lcl}
  13772. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13773. \end{array}
  13774. \end{array}
  13775. \]
  13776. \fi}
  13777. {\if\edition\pythonEd
  13778. \[
  13779. \begin{array}{lcl}
  13780. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13781. \MID \BYTEREG{\Reg} } \\
  13782. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13783. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13784. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13785. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13786. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13787. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13788. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13789. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13790. \end{array}
  13791. \]
  13792. \fi}
  13793. \end{tcolorbox}
  13794. \caption{The abstract syntax of \LangXIndCall{} (extends
  13795. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  13796. \label{fig:x86-3}
  13797. \end{figure}
  13798. An assignment of a function reference to a variable becomes a
  13799. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13800. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13801. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13802. node, whose concrete syntax is instruction-pointer-relative
  13803. addressing.
  13804. \begin{center}
  13805. \begin{tabular}{lcl}
  13806. \begin{minipage}{0.35\textwidth}
  13807. {\if\edition\racketEd
  13808. \begin{lstlisting}
  13809. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13810. \end{lstlisting}
  13811. \fi}
  13812. {\if\edition\pythonEd
  13813. \begin{lstlisting}
  13814. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13815. \end{lstlisting}
  13816. \fi}
  13817. \end{minipage}
  13818. &
  13819. $\Rightarrow$\qquad\qquad
  13820. &
  13821. \begin{minipage}{0.3\textwidth}
  13822. \begin{lstlisting}
  13823. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13824. \end{lstlisting}
  13825. \end{minipage}
  13826. \end{tabular}
  13827. \end{center}
  13828. Regarding function definitions, we need to remove the parameters and
  13829. instead perform parameter passing using the conventions discussed in
  13830. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13831. registers. We recommend turning the parameters into local variables
  13832. and generating instructions at the beginning of the function to move
  13833. from the argument-passing registers
  13834. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  13835. {\if\edition\racketEd
  13836. \begin{lstlisting}
  13837. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13838. |$\Rightarrow$|
  13839. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13840. \end{lstlisting}
  13841. \fi}
  13842. {\if\edition\pythonEd
  13843. \begin{lstlisting}
  13844. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13845. |$\Rightarrow$|
  13846. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13847. \end{lstlisting}
  13848. \fi}
  13849. The basic blocks $B'$ are the same as $B$ except that the
  13850. \code{start} block is modified to add the instructions for moving from
  13851. the argument registers to the parameter variables. So the \code{start}
  13852. block of $B$ shown on the left of the following is changed to the code
  13853. on the right:
  13854. \begin{center}
  13855. \begin{minipage}{0.3\textwidth}
  13856. \begin{lstlisting}
  13857. start:
  13858. |$\itm{instr}_1$|
  13859. |$\cdots$|
  13860. |$\itm{instr}_n$|
  13861. \end{lstlisting}
  13862. \end{minipage}
  13863. $\Rightarrow$
  13864. \begin{minipage}{0.3\textwidth}
  13865. \begin{lstlisting}
  13866. |$f$|start:
  13867. movq %rdi, |$x_1$|
  13868. movq %rsi, |$x_2$|
  13869. |$\cdots$|
  13870. |$\itm{instr}_1$|
  13871. |$\cdots$|
  13872. |$\itm{instr}_n$|
  13873. \end{lstlisting}
  13874. \end{minipage}
  13875. \end{center}
  13876. Recall that we use the label \code{start} for the initial block of a
  13877. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  13878. the conclusion of the program with \code{conclusion}, so that
  13879. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13880. by a jump to \code{conclusion}. With the addition of function
  13881. definitions, there is a start block and conclusion for each function,
  13882. but their labels need to be unique. We recommend prepending the
  13883. function's name to \code{start} and \code{conclusion}, respectively,
  13884. to obtain unique labels.
  13885. \racket{The interpreter for \LangXIndCall{} needs to be given the
  13886. number of parameters the function expects, but the parameters are no
  13887. longer in the syntax of function definitions. Instead, add an entry
  13888. to $\itm{info}$ that maps \code{num-params} to the number of
  13889. parameters to construct $\itm{info}'$.}
  13890. By changing the parameters to local variables, we are giving the
  13891. register allocator control over which registers or stack locations to
  13892. use for them. If you implement the move-biasing challenge
  13893. (section~\ref{sec:move-biasing}), the register allocator will try to
  13894. assign the parameter variables to the corresponding argument register,
  13895. in which case the \code{patch\_instructions} pass will remove the
  13896. \code{movq} instruction. This happens in the example translation given
  13897. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  13898. the \code{add} function.
  13899. %
  13900. Also, note that the register allocator will perform liveness analysis
  13901. on this sequence of move instructions and build the interference
  13902. graph. So, for example, $x_1$ will be marked as interfering with
  13903. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  13904. which is good because otherwise the first \code{movq} would overwrite
  13905. the argument in \code{rsi} that is needed for $x_2$.
  13906. Next, consider the compilation of function calls. In the mirror image
  13907. of the handling of parameters in function definitions, the arguments
  13908. are moved to the argument-passing registers. Note that the function
  13909. is not given as a label, but its address is produced by the argument
  13910. $\itm{arg}_0$. So, we translate the call into an indirect function
  13911. call. The return value from the function is stored in \code{rax}, so
  13912. it needs to be moved into the \itm{lhs}.
  13913. \begin{lstlisting}
  13914. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13915. |$\Rightarrow$|
  13916. movq |$\itm{arg}_1$|, %rdi
  13917. movq |$\itm{arg}_2$|, %rsi
  13918. |$\vdots$|
  13919. callq *|$\itm{arg}_0$|
  13920. movq %rax, |$\itm{lhs}$|
  13921. \end{lstlisting}
  13922. The \code{IndirectCallq} AST node includes an integer for the arity of
  13923. the function, that is, the number of parameters. That information is
  13924. useful in the \code{uncover\_live} pass for determining which
  13925. argument-passing registers are potentially read during the call.
  13926. For tail calls, the parameter passing is the same as non-tail calls:
  13927. generate instructions to move the arguments into the argument-passing
  13928. registers. After that we need to pop the frame from the procedure
  13929. call stack. However, we do not yet know how big the frame is; that
  13930. gets determined during register allocation. So, instead of generating
  13931. those instructions here, we invent a new instruction that means ``pop
  13932. the frame and then do an indirect jump,'' which we name
  13933. \code{TailJmp}. The abstract syntax for this instruction includes an
  13934. argument that specifies where to jump and an integer that represents
  13935. the arity of the function being called.
  13936. \section{Register Allocation}
  13937. \label{sec:register-allocation-r4}
  13938. The addition of functions requires some changes to all three aspects
  13939. of register allocation, which we discuss in the following subsections.
  13940. \subsection{Liveness Analysis}
  13941. \label{sec:liveness-analysis-r4}
  13942. \index{subject}{liveness analysis}
  13943. %% The rest of the passes need only minor modifications to handle the new
  13944. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13945. %% \code{leaq}.
  13946. The \code{IndirectCallq} instruction should be treated like
  13947. \code{Callq} regarding its written locations $W$, in that they should
  13948. include all the caller-saved registers. Recall that the reason for
  13949. that is to force variables that are live across a function call to be assigned to callee-saved
  13950. registers or to be spilled to the stack.
  13951. Regarding the set of read locations $R$, the arity field of
  13952. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  13953. argument-passing registers should be considered as read by those
  13954. instructions. Also, the target field of \code{TailJmp} and
  13955. \code{IndirectCallq} should be included in the set of read locations
  13956. $R$.
  13957. \subsection{Build Interference Graph}
  13958. \label{sec:build-interference-r4}
  13959. With the addition of function definitions, we compute a separate interference
  13960. graph for each function (not just one for the whole program).
  13961. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  13962. spill tuple-typed variables that are live during a call to
  13963. \code{collect}, the garbage collector. With the addition of functions
  13964. to our language, we need to revisit this issue. Functions that perform
  13965. allocation contain calls to the collector. Thus, we should not only
  13966. spill a tuple-typed variable when it is live during a call to
  13967. \code{collect}, but we should spill the variable if it is live during
  13968. call to any user-defined function. Thus, in the
  13969. \code{build\_interference} pass, we recommend adding interference
  13970. edges between call-live tuple-typed variables and the callee-saved
  13971. registers (in addition to the usual addition of edges between
  13972. call-live variables and the caller-saved registers).
  13973. \subsection{Allocate Registers}
  13974. The primary change to the \code{allocate\_registers} pass is adding an
  13975. auxiliary function for handling definitions (the \Def{} nonterminal
  13976. shown in figure~\ref{fig:x86-3}) with one case for function
  13977. definitions. The logic is the same as described in
  13978. chapter~\ref{ch:register-allocation-Lvar} except that now register
  13979. allocation is performed many times, once for each function definition,
  13980. instead of just once for the whole program.
  13981. \section{Patch Instructions}
  13982. In \code{patch\_instructions}, you should deal with the x86
  13983. idiosyncrasy that the destination argument of \code{leaq} must be a
  13984. register. Additionally, you should ensure that the argument of
  13985. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13986. trample many other registers before the tail call, as explained in the
  13987. next section.
  13988. \section{Prelude and Conclusion}
  13989. Now that register allocation is complete, we can translate the
  13990. \code{TailJmp} into a sequence of instructions. A naive translation of
  13991. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13992. before the jump we need to pop the current frame to achieve efficient
  13993. tail calls. This sequence of instructions is the same as the code for
  13994. the conclusion of a function, except that the \code{retq} is replaced with
  13995. \code{jmp *$\itm{arg}$}.
  13996. Regarding function definitions, we generate a prelude and conclusion
  13997. for each one. This code is similar to the prelude and conclusion
  13998. generated for the \code{main} function presented in
  13999. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14000. carry out the following steps:
  14001. % TODO: .align the functions!
  14002. \begin{enumerate}
  14003. %% \item Start with \code{.global} and \code{.align} directives followed
  14004. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14005. %% example.)
  14006. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14007. pointer.
  14008. \item Push to the stack all the callee-saved registers that were
  14009. used for register allocation.
  14010. \item Move the stack pointer \code{rsp} down to make room for the
  14011. regular spills (aligned to 16 bytes).
  14012. \item Move the root stack pointer \code{r15} up by the size of the
  14013. root-stack frame for this function, which depends on the number of
  14014. spilled tuple-typed variables. \label{root-stack-init}
  14015. \item Initialize to zero all new entries in the root-stack frame.
  14016. \item Jump to the start block.
  14017. \end{enumerate}
  14018. The prelude of the \code{main} function has an additional task: call
  14019. the \code{initialize} function to set up the garbage collector, and
  14020. then move the value of the global \code{rootstack\_begin} in
  14021. \code{r15}. This initialization should happen before step
  14022. \ref{root-stack-init}, which depends on \code{r15}.
  14023. The conclusion of every function should do the following:
  14024. \begin{enumerate}
  14025. \item Move the stack pointer back up past the regular spills.
  14026. \item Restore the callee-saved registers by popping them from the
  14027. stack.
  14028. \item Move the root stack pointer back down by the size of the
  14029. root-stack frame for this function.
  14030. \item Restore \code{rbp} by popping it from the stack.
  14031. \item Return to the caller with the \code{retq} instruction.
  14032. \end{enumerate}
  14033. The output of this pass is \LangXIndCallFlat{}, which differs from
  14034. \LangXIndCall{} in that there is no longer an AST node for function
  14035. definitions. Instead, a program is just an association list of basic
  14036. blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  14037. \[
  14038. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  14039. \]
  14040. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  14041. compiling \LangFun{} to x86.
  14042. \begin{exercise}\normalfont\normalsize
  14043. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  14044. Create eight new programs that use functions, including examples that
  14045. pass functions and return functions from other functions, recursive
  14046. functions, functions that create vectors, and functions that make tail
  14047. calls. Test your compiler on these new programs and all your
  14048. previously created test programs.
  14049. \end{exercise}
  14050. \begin{figure}[tbp]
  14051. \begin{tcolorbox}[colback=white]
  14052. {\if\edition\racketEd
  14053. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  14054. \node (Lfun) at (0,2) {\large \LangFun{}};
  14055. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  14056. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  14057. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  14058. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  14059. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  14060. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14061. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14062. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14063. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14064. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14065. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14066. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  14067. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  14068. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  14069. \path[->,bend left=15] (Lfun) edge [above] node
  14070. {\ttfamily\footnotesize shrink} (Lfun-1);
  14071. \path[->,bend left=15] (Lfun-1) edge [above] node
  14072. {\ttfamily\footnotesize uniquify} (Lfun-2);
  14073. \path[->,bend left=15] (Lfun-2) edge [above] node
  14074. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14075. \path[->,bend left=15] (F1-1) edge [left] node
  14076. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14077. \path[->,bend left=15] (F1-2) edge [below] node
  14078. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  14079. \path[->,bend left=15] (F1-3) edge [below] node
  14080. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  14081. \path[->,bend right=15] (F1-4) edge [above] node
  14082. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14083. \path[->,bend right=15] (F1-5) edge [right] node
  14084. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14085. \path[->,bend right=15] (C3-2) edge [right] node
  14086. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14087. \path[->,bend left=15] (x86-2) edge [right] node
  14088. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14089. \path[->,bend right=15] (x86-2-1) edge [below] node
  14090. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  14091. \path[->,bend right=15] (x86-2-2) edge [right] node
  14092. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  14093. \path[->,bend left=15] (x86-3) edge [above] node
  14094. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14095. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14096. \end{tikzpicture}
  14097. \fi}
  14098. {\if\edition\pythonEd
  14099. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  14100. \node (Lfun) at (0,2) {\large \LangFun{}};
  14101. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  14102. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  14103. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  14104. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  14105. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14106. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  14107. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  14108. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  14109. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  14110. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  14111. \path[->,bend left=15] (Lfun) edge [above] node
  14112. {\ttfamily\footnotesize shrink} (Lfun-2);
  14113. \path[->,bend left=15] (Lfun-2) edge [above] node
  14114. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  14115. \path[->,bend left=15] (F1-1) edge [above] node
  14116. {\ttfamily\footnotesize limit\_functions} (F1-2);
  14117. \path[->,bend left=15] (F1-2) edge [right] node
  14118. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  14119. \path[->,bend right=15] (F1-4) edge [above] node
  14120. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  14121. \path[->,bend right=15] (F1-5) edge [right] node
  14122. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14123. \path[->,bend left=15] (C3-2) edge [right] node
  14124. {\ttfamily\footnotesize select\_instructions} (x86-2);
  14125. \path[->,bend right=15] (x86-2) edge [below] node
  14126. {\ttfamily\footnotesize assign\_homes} (x86-3);
  14127. \path[->,bend left=15] (x86-3) edge [above] node
  14128. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  14129. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  14130. \end{tikzpicture}
  14131. \fi}
  14132. \end{tcolorbox}
  14133. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  14134. \label{fig:Lfun-passes}
  14135. \end{figure}
  14136. \section{An Example Translation}
  14137. \label{sec:functions-example}
  14138. Figure~\ref{fig:add-fun} shows an example translation of a simple
  14139. function in \LangFun{} to x86. The figure also includes the results of the
  14140. \code{explicate\_control} and \code{select\_instructions} passes.
  14141. \begin{figure}[htbp]
  14142. \begin{tcolorbox}[colback=white]
  14143. \begin{tabular}{ll}
  14144. \begin{minipage}{0.4\textwidth}
  14145. % s3_2.rkt
  14146. {\if\edition\racketEd
  14147. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14148. (define (add [x : Integer]
  14149. [y : Integer])
  14150. : Integer
  14151. (+ x y))
  14152. (add 40 2)
  14153. \end{lstlisting}
  14154. \fi}
  14155. {\if\edition\pythonEd
  14156. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14157. def add(x:int, y:int) -> int:
  14158. return x + y
  14159. print(add(40, 2))
  14160. \end{lstlisting}
  14161. \fi}
  14162. $\Downarrow$
  14163. {\if\edition\racketEd
  14164. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14165. (define (add86 [x87 : Integer]
  14166. [y88 : Integer])
  14167. : Integer
  14168. add86start:
  14169. return (+ x87 y88);
  14170. )
  14171. (define (main) : Integer ()
  14172. mainstart:
  14173. tmp89 = (fun-ref add86 2);
  14174. (tail-call tmp89 40 2)
  14175. )
  14176. \end{lstlisting}
  14177. \fi}
  14178. {\if\edition\pythonEd
  14179. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14180. def add(x:int, y:int) -> int:
  14181. addstart:
  14182. return x + y
  14183. def main() -> int:
  14184. mainstart:
  14185. fun.0 = add
  14186. tmp.1 = fun.0(40, 2)
  14187. print(tmp.1)
  14188. return 0
  14189. \end{lstlisting}
  14190. \fi}
  14191. \end{minipage}
  14192. &
  14193. $\Rightarrow$
  14194. \begin{minipage}{0.5\textwidth}
  14195. {\if\edition\racketEd
  14196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14197. (define (add86) : Integer
  14198. add86start:
  14199. movq %rdi, x87
  14200. movq %rsi, y88
  14201. movq x87, %rax
  14202. addq y88, %rax
  14203. jmp inc1389conclusion
  14204. )
  14205. (define (main) : Integer
  14206. mainstart:
  14207. leaq (fun-ref add86 2), tmp89
  14208. movq $40, %rdi
  14209. movq $2, %rsi
  14210. tail-jmp tmp89
  14211. )
  14212. \end{lstlisting}
  14213. \fi}
  14214. {\if\edition\pythonEd
  14215. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14216. def add() -> int:
  14217. addstart:
  14218. movq %rdi, x
  14219. movq %rsi, y
  14220. movq x, %rax
  14221. addq y, %rax
  14222. jmp addconclusion
  14223. def main() -> int:
  14224. mainstart:
  14225. leaq add, fun.0
  14226. movq $40, %rdi
  14227. movq $2, %rsi
  14228. callq *fun.0
  14229. movq %rax, tmp.1
  14230. movq tmp.1, %rdi
  14231. callq print_int
  14232. movq $0, %rax
  14233. jmp mainconclusion
  14234. \end{lstlisting}
  14235. \fi}
  14236. $\Downarrow$
  14237. \end{minipage}
  14238. \end{tabular}
  14239. \begin{tabular}{ll}
  14240. \begin{minipage}{0.3\textwidth}
  14241. {\if\edition\racketEd
  14242. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14243. .globl add86
  14244. .align 8
  14245. add86:
  14246. pushq %rbp
  14247. movq %rsp, %rbp
  14248. jmp add86start
  14249. add86start:
  14250. movq %rdi, %rax
  14251. addq %rsi, %rax
  14252. jmp add86conclusion
  14253. add86conclusion:
  14254. popq %rbp
  14255. retq
  14256. \end{lstlisting}
  14257. \fi}
  14258. {\if\edition\pythonEd
  14259. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14260. .align 8
  14261. add:
  14262. pushq %rbp
  14263. movq %rsp, %rbp
  14264. subq $0, %rsp
  14265. jmp addstart
  14266. addstart:
  14267. movq %rdi, %rdx
  14268. movq %rsi, %rcx
  14269. movq %rdx, %rax
  14270. addq %rcx, %rax
  14271. jmp addconclusion
  14272. addconclusion:
  14273. subq $0, %r15
  14274. addq $0, %rsp
  14275. popq %rbp
  14276. retq
  14277. \end{lstlisting}
  14278. \fi}
  14279. \end{minipage}
  14280. &
  14281. \begin{minipage}{0.5\textwidth}
  14282. {\if\edition\racketEd
  14283. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14284. .globl main
  14285. .align 8
  14286. main:
  14287. pushq %rbp
  14288. movq %rsp, %rbp
  14289. movq $16384, %rdi
  14290. movq $16384, %rsi
  14291. callq initialize
  14292. movq rootstack_begin(%rip), %r15
  14293. jmp mainstart
  14294. mainstart:
  14295. leaq add86(%rip), %rcx
  14296. movq $40, %rdi
  14297. movq $2, %rsi
  14298. movq %rcx, %rax
  14299. popq %rbp
  14300. jmp *%rax
  14301. mainconclusion:
  14302. popq %rbp
  14303. retq
  14304. \end{lstlisting}
  14305. \fi}
  14306. {\if\edition\pythonEd
  14307. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14308. .globl main
  14309. .align 8
  14310. main:
  14311. pushq %rbp
  14312. movq %rsp, %rbp
  14313. subq $0, %rsp
  14314. movq $65536, %rdi
  14315. movq $65536, %rsi
  14316. callq initialize
  14317. movq rootstack_begin(%rip), %r15
  14318. jmp mainstart
  14319. mainstart:
  14320. leaq add(%rip), %rcx
  14321. movq $40, %rdi
  14322. movq $2, %rsi
  14323. callq *%rcx
  14324. movq %rax, %rcx
  14325. movq %rcx, %rdi
  14326. callq print_int
  14327. movq $0, %rax
  14328. jmp mainconclusion
  14329. mainconclusion:
  14330. subq $0, %r15
  14331. addq $0, %rsp
  14332. popq %rbp
  14333. retq
  14334. \end{lstlisting}
  14335. \fi}
  14336. \end{minipage}
  14337. \end{tabular}
  14338. \end{tcolorbox}
  14339. \caption{Example compilation of a simple function to x86.}
  14340. \label{fig:add-fun}
  14341. \end{figure}
  14342. % Challenge idea: inlining! (simple version)
  14343. % Further Reading
  14344. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  14345. \chapter{Lexically Scoped Functions}
  14346. \label{ch:Llambda}
  14347. \index{subject}{lambda}
  14348. \index{subject}{lexical scoping}
  14349. \setcounter{footnote}{0}
  14350. This chapter studies lexically scoped functions. Lexical scoping means
  14351. that a function's body may refer to variables whose binding site is
  14352. outside of the function, in an enclosing scope.
  14353. %
  14354. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  14355. in \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  14356. creating lexically scoped functions. The body of the \key{lambda}
  14357. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  14358. binding sites for \code{x} and \code{y} are outside of the
  14359. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  14360. \key{let}}\python{a local variable of function \code{f}}, and
  14361. \code{x} is a parameter of function \code{f}. Note that function
  14362. \code{f} returns the \key{lambda} as its result value. The main
  14363. expression of the program includes two calls to \code{f} with
  14364. different arguments for \code{x}: first \code{5} and then \code{3}. The
  14365. functions returned from \code{f} are bound to variables \code{g} and
  14366. \code{h}. Even though these two functions were created by the same
  14367. \code{lambda}, they are really different functions because they use
  14368. different values for \code{x}. Applying \code{g} to \code{11} produces
  14369. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  14370. so the result of the program is \code{42}.
  14371. \begin{figure}[btp]
  14372. \begin{tcolorbox}[colback=white]
  14373. {\if\edition\racketEd
  14374. % lambda_test_21.rkt
  14375. \begin{lstlisting}
  14376. (define (f [x : Integer]) : (Integer -> Integer)
  14377. (let ([y 4])
  14378. (lambda: ([z : Integer]) : Integer
  14379. (+ x (+ y z)))))
  14380. (let ([g (f 5)])
  14381. (let ([h (f 3)])
  14382. (+ (g 11) (h 15))))
  14383. \end{lstlisting}
  14384. \fi}
  14385. {\if\edition\pythonEd
  14386. \begin{lstlisting}
  14387. def f(x : int) -> Callable[[int], int]:
  14388. y = 4
  14389. return lambda z: x + y + z
  14390. g = f(5)
  14391. h = f(3)
  14392. print( g(11) + h(15) )
  14393. \end{lstlisting}
  14394. \fi}
  14395. \end{tcolorbox}
  14396. \caption{Example of a lexically scoped function.}
  14397. \label{fig:lexical-scoping}
  14398. \end{figure}
  14399. The approach that we take for implementing lexically scoped functions
  14400. is to compile them into top-level function definitions, translating
  14401. from \LangLam{} into \LangFun{}. However, the compiler must give
  14402. special treatment to variable occurrences such as \code{x} and
  14403. \code{y} in the body of the \code{lambda} shown in
  14404. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  14405. may not refer to variables defined outside of it. To identify such
  14406. variable occurrences, we review the standard notion of free variable.
  14407. \begin{definition}\normalfont
  14408. A variable is \emph{free in expression} $e$ if the variable occurs
  14409. inside $e$ but does not have an enclosing definition that is also in
  14410. $e$.\index{subject}{free variable}
  14411. \end{definition}
  14412. For example, in the expression
  14413. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  14414. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  14415. only \code{x} and \code{y} are free in the following expression,
  14416. because \code{z} is defined by the \code{lambda}
  14417. {\if\edition\racketEd
  14418. \begin{lstlisting}
  14419. (lambda: ([z : Integer]) : Integer
  14420. (+ x (+ y z)))
  14421. \end{lstlisting}
  14422. \fi}
  14423. {\if\edition\pythonEd
  14424. \begin{lstlisting}
  14425. lambda z: x + y + z
  14426. \end{lstlisting}
  14427. \fi}
  14428. %
  14429. \noindent Thus the free variables of a \code{lambda} are the ones that
  14430. need special treatment. We need to transport at runtime the values
  14431. of those variables from the point where the \code{lambda} was created
  14432. to the point where the \code{lambda} is applied. An efficient solution
  14433. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  14434. values of the free variables together with a function pointer into a
  14435. tuple, an arrangement called a \emph{flat closure} (which we shorten
  14436. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  14437. closure}
  14438. %
  14439. By design, we have all the ingredients to make closures:
  14440. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  14441. function pointers. The function pointer resides at index $0$, and the
  14442. values for the free variables fill in the rest of the tuple.
  14443. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  14444. to see how closures work. It is a three-step dance. The program calls
  14445. function \code{f}, which creates a closure for the \code{lambda}. The
  14446. closure is a tuple whose first element is a pointer to the top-level
  14447. function that we will generate for the \code{lambda}; the second
  14448. element is the value of \code{x}, which is \code{5}; and the third
  14449. element is \code{4}, the value of \code{y}. The closure does not
  14450. contain an element for \code{z} because \code{z} is not a free
  14451. variable of the \code{lambda}. Creating the closure is step 1 of the
  14452. dance. The closure is returned from \code{f} and bound to \code{g}, as
  14453. shown in figure~\ref{fig:closures}.
  14454. %
  14455. The second call to \code{f} creates another closure, this time with
  14456. \code{3} in the second slot (for \code{x}). This closure is also
  14457. returned from \code{f} but bound to \code{h}, which is also shown in
  14458. figure~\ref{fig:closures}.
  14459. \begin{figure}[tbp]
  14460. \centering
  14461. \begin{minipage}{0.65\textwidth}
  14462. \begin{tcolorbox}[colback=white]
  14463. \includegraphics[width=\textwidth]{figs/closures}
  14464. \end{tcolorbox}
  14465. \end{minipage}
  14466. \caption{Flat closure representations for the two functions
  14467. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  14468. \label{fig:closures}
  14469. \end{figure}
  14470. Continuing with the example, consider the application of \code{g} to
  14471. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  14472. closure, we obtain the function pointer from the first element of the
  14473. closure and call it, passing in the closure itself and then the
  14474. regular arguments, in this case \code{11}. This technique for applying
  14475. a closure is step 2 of the dance.
  14476. %
  14477. But doesn't this \code{lambda} take only one argument, for parameter
  14478. \code{z}? The third and final step of the dance is generating a
  14479. top-level function for a \code{lambda}. We add an additional
  14480. parameter for the closure and insert an initialization at the beginning
  14481. of the function for each free variable, to bind those variables to the
  14482. appropriate elements from the closure parameter.
  14483. %
  14484. This three-step dance is known as \emph{closure conversion}. We
  14485. discuss the details of closure conversion in
  14486. section~\ref{sec:closure-conversion} and show the code generated from
  14487. the example in section~\ref{sec:example-lambda}. First, we define
  14488. the syntax and semantics of \LangLam{} in section~\ref{sec:r5}.
  14489. \section{The \LangLam{} Language}
  14490. \label{sec:r5}
  14491. The definitions of the concrete syntax and abstract syntax for
  14492. \LangLam{}, a language with anonymous functions and lexical scoping,
  14493. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  14494. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  14495. for \LangFun{}, which already has syntax for function application.
  14496. %
  14497. \python{The syntax also includes an assignment statement that includes
  14498. a type annotation for the variable on the left-hand side, which
  14499. facilitates the type checking of \code{lambda} expressions that we
  14500. discuss later in this section.}
  14501. %
  14502. \racket{The \code{procedure-arity} operation returns the number of parameters
  14503. of a given function, an operation that we need for the translation
  14504. of dynamic typing in chapter~\ref{ch:Ldyn}.}
  14505. %
  14506. \python{The \code{arity} operation returns the number of parameters of
  14507. a given function, an operation that we need for the translation
  14508. of dynamic typing in chapter~\ref{ch:Ldyn}.
  14509. The \code{arity} operation is not in Python, but the same functionality
  14510. is available in a more complex form. We include \code{arity} in the
  14511. \LangLam{} source language to enable testing.}
  14512. \newcommand{\LlambdaGrammarRacket}{
  14513. \begin{array}{lcl}
  14514. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  14515. &\MID& \LP \key{procedure-arity}~\Exp\RP
  14516. \end{array}
  14517. }
  14518. \newcommand{\LlambdaASTRacket}{
  14519. \begin{array}{lcl}
  14520. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  14521. \itm{op} &::=& \code{procedure-arity}
  14522. \end{array}
  14523. }
  14524. \newcommand{\LlambdaGrammarPython}{
  14525. \begin{array}{lcl}
  14526. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  14527. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  14528. \end{array}
  14529. }
  14530. \newcommand{\LlambdaASTPython}{
  14531. \begin{array}{lcl}
  14532. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  14533. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  14534. \end{array}
  14535. }
  14536. % include AnnAssign in ASTPython
  14537. \begin{figure}[tp]
  14538. \centering
  14539. \begin{tcolorbox}[colback=white]
  14540. \small
  14541. {\if\edition\racketEd
  14542. \[
  14543. \begin{array}{l}
  14544. \gray{\LintGrammarRacket{}} \\ \hline
  14545. \gray{\LvarGrammarRacket{}} \\ \hline
  14546. \gray{\LifGrammarRacket{}} \\ \hline
  14547. \gray{\LwhileGrammarRacket} \\ \hline
  14548. \gray{\LtupGrammarRacket} \\ \hline
  14549. \gray{\LfunGrammarRacket} \\ \hline
  14550. \LlambdaGrammarRacket \\
  14551. \begin{array}{lcl}
  14552. \LangLamM{} &::=& \Def\ldots \; \Exp
  14553. \end{array}
  14554. \end{array}
  14555. \]
  14556. \fi}
  14557. {\if\edition\pythonEd
  14558. \[
  14559. \begin{array}{l}
  14560. \gray{\LintGrammarPython{}} \\ \hline
  14561. \gray{\LvarGrammarPython{}} \\ \hline
  14562. \gray{\LifGrammarPython{}} \\ \hline
  14563. \gray{\LwhileGrammarPython} \\ \hline
  14564. \gray{\LtupGrammarPython} \\ \hline
  14565. \gray{\LfunGrammarPython} \\ \hline
  14566. \LlambdaGrammarPython \\
  14567. \begin{array}{lcl}
  14568. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  14569. \end{array}
  14570. \end{array}
  14571. \]
  14572. \fi}
  14573. \end{tcolorbox}
  14574. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  14575. with \key{lambda}.}
  14576. \label{fig:Llam-concrete-syntax}
  14577. \end{figure}
  14578. \begin{figure}[tp]
  14579. \centering
  14580. \begin{tcolorbox}[colback=white]
  14581. \small
  14582. {\if\edition\racketEd
  14583. \[\arraycolsep=3pt
  14584. \begin{array}{l}
  14585. \gray{\LintOpAST} \\ \hline
  14586. \gray{\LvarASTRacket{}} \\ \hline
  14587. \gray{\LifASTRacket{}} \\ \hline
  14588. \gray{\LwhileASTRacket{}} \\ \hline
  14589. \gray{\LtupASTRacket{}} \\ \hline
  14590. \gray{\LfunASTRacket} \\ \hline
  14591. \LlambdaASTRacket \\
  14592. \begin{array}{lcl}
  14593. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  14594. \end{array}
  14595. \end{array}
  14596. \]
  14597. \fi}
  14598. {\if\edition\pythonEd
  14599. \[
  14600. \begin{array}{l}
  14601. \gray{\LintASTPython} \\ \hline
  14602. \gray{\LvarASTPython{}} \\ \hline
  14603. \gray{\LifASTPython{}} \\ \hline
  14604. \gray{\LwhileASTPython{}} \\ \hline
  14605. \gray{\LtupASTPython{}} \\ \hline
  14606. \gray{\LfunASTPython} \\ \hline
  14607. \LlambdaASTPython \\
  14608. \begin{array}{lcl}
  14609. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14610. \end{array}
  14611. \end{array}
  14612. \]
  14613. \fi}
  14614. \end{tcolorbox}
  14615. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  14616. \label{fig:Llam-syntax}
  14617. \end{figure}
  14618. \index{subject}{interpreter}
  14619. \label{sec:interp-Llambda}
  14620. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  14621. \LangLam{}. The case for \key{Lambda} saves the current environment
  14622. inside the returned function value. Recall that during function
  14623. application, the environment stored in the function value, extended
  14624. with the mapping of parameters to argument values, is used to
  14625. interpret the body of the function.
  14626. \begin{figure}[tbp]
  14627. \begin{tcolorbox}[colback=white]
  14628. {\if\edition\racketEd
  14629. \begin{lstlisting}
  14630. (define interp-Llambda-class
  14631. (class interp-Lfun-class
  14632. (super-new)
  14633. (define/override (interp-op op)
  14634. (match op
  14635. ['procedure-arity
  14636. (lambda (v)
  14637. (match v
  14638. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  14639. [else (error 'interp-op "expected a function, not ~a" v)]))]
  14640. [else (super interp-op op)]))
  14641. (define/override ((interp-exp env) e)
  14642. (define recur (interp-exp env))
  14643. (match e
  14644. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  14645. `(function ,xs ,body ,env)]
  14646. [else ((super interp-exp env) e)]))
  14647. ))
  14648. (define (interp-Llambda p)
  14649. (send (new interp-Llambda-class) interp-program p))
  14650. \end{lstlisting}
  14651. \fi}
  14652. {\if\edition\pythonEd
  14653. \begin{lstlisting}
  14654. class InterpLlambda(InterpLfun):
  14655. def arity(self, v):
  14656. match v:
  14657. case Function(name, params, body, env):
  14658. return len(params)
  14659. case _:
  14660. raise Exception('Llambda arity unexpected ' + repr(v))
  14661. def interp_exp(self, e, env):
  14662. match e:
  14663. case Call(Name('arity'), [fun]):
  14664. f = self.interp_exp(fun, env)
  14665. return self.arity(f)
  14666. case Lambda(params, body):
  14667. return Function('lambda', params, [Return(body)], env)
  14668. case _:
  14669. return super().interp_exp(e, env)
  14670. def interp_stmts(self, ss, env):
  14671. if len(ss) == 0:
  14672. return
  14673. match ss[0]:
  14674. case AnnAssign(lhs, typ, value, simple):
  14675. env[lhs.id] = self.interp_exp(value, env)
  14676. return self.interp_stmts(ss[1:], env)
  14677. case _:
  14678. return super().interp_stmts(ss, env)
  14679. \end{lstlisting}
  14680. \fi}
  14681. \end{tcolorbox}
  14682. \caption{Interpreter for \LangLam{}.}
  14683. \label{fig:interp-Llambda}
  14684. \end{figure}
  14685. \label{sec:type-check-r5}
  14686. \index{subject}{type checking}
  14687. {\if\edition\racketEd
  14688. %
  14689. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  14690. \key{lambda} form. The body of the \key{lambda} is checked in an
  14691. environment that includes the current environment (because it is
  14692. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14693. require the body's type to match the declared return type.
  14694. %
  14695. \fi}
  14696. {\if\edition\pythonEd
  14697. %
  14698. Figures~\ref{fig:type-check-Llambda} and
  14699. \ref{fig:type-check-Llambda-part2} define the type checker for
  14700. \LangLam{}, which is more complex than one might expect. The reason
  14701. for the added complexity is that the syntax of \key{lambda} does not
  14702. include type annotations for the parameters or return type. Instead
  14703. they must be inferred. There are many approaches of type inference to
  14704. choose from of varying degrees of complexity. We choose one of the
  14705. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14706. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14707. this book is compilation, not type inference.
  14708. The main idea of bidirectional type inference is to add an auxiliary
  14709. function, here named \code{check\_exp}, that takes an expected type
  14710. and checks whether the given expression is of that type. Thus, in
  14711. \code{check\_exp}, type information flows in a top-down manner with
  14712. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14713. function, where type information flows in a primarily bottom-up
  14714. manner.
  14715. %
  14716. The idea then is to use \code{check\_exp} in all the places where we
  14717. already know what the type of an expression should be, such as in the
  14718. \code{return} statement of a top-level function definition, or on the
  14719. right-hand side of an annotated assignment statement.
  14720. Getting back to \code{lambda}, it is straightforward to check a
  14721. \code{lambda} inside \code{check\_exp} because the expected type
  14722. provides the parameter types and the return type. On the other hand,
  14723. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14724. that we do not allow \code{lambda} in contexts where we don't already
  14725. know its type. This restriction does not incur a loss of
  14726. expressiveness for \LangLam{} because it is straightforward to modify
  14727. a program to sidestep the restriction, for example, by using an
  14728. annotated assignment statement to assign the \code{lambda} to a
  14729. temporary variable.
  14730. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14731. checker records their type in a \code{has\_type} field. This type
  14732. information is used later in this chapter.
  14733. %
  14734. \fi}
  14735. \begin{figure}[tbp]
  14736. \begin{tcolorbox}[colback=white]
  14737. {\if\edition\racketEd
  14738. \begin{lstlisting}
  14739. (define (type-check-Llambda env)
  14740. (lambda (e)
  14741. (match e
  14742. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14743. (define-values (new-body bodyT)
  14744. ((type-check-exp (append (map cons xs Ts) env)) body))
  14745. (define ty `(,@Ts -> ,rT))
  14746. (cond
  14747. [(equal? rT bodyT)
  14748. (values (HasType (Lambda params rT new-body) ty) ty)]
  14749. [else
  14750. (error "mismatch in return type" bodyT rT)])]
  14751. ...
  14752. )))
  14753. \end{lstlisting}
  14754. \fi}
  14755. {\if\edition\pythonEd
  14756. \begin{lstlisting}
  14757. class TypeCheckLlambda(TypeCheckLfun):
  14758. def type_check_exp(self, e, env):
  14759. match e:
  14760. case Name(id):
  14761. e.has_type = env[id]
  14762. return env[id]
  14763. case Lambda(params, body):
  14764. raise Exception('cannot synthesize a type for a lambda')
  14765. case Call(Name('arity'), [func]):
  14766. func_t = self.type_check_exp(func, env)
  14767. match func_t:
  14768. case FunctionType(params_t, return_t):
  14769. return IntType()
  14770. case _:
  14771. raise Exception('in arity, unexpected ' + repr(func_t))
  14772. case _:
  14773. return super().type_check_exp(e, env)
  14774. def check_exp(self, e, ty, env):
  14775. match e:
  14776. case Lambda(params, body):
  14777. e.has_type = ty
  14778. match ty:
  14779. case FunctionType(params_t, return_t):
  14780. new_env = env.copy().update(zip(params, params_t))
  14781. self.check_exp(body, return_t, new_env)
  14782. case _:
  14783. raise Exception('lambda does not have type ' + str(ty))
  14784. case Call(func, args):
  14785. func_t = self.type_check_exp(func, env)
  14786. match func_t:
  14787. case FunctionType(params_t, return_t):
  14788. for (arg, param_t) in zip(args, params_t):
  14789. self.check_exp(arg, param_t, env)
  14790. self.check_type_equal(return_t, ty, e)
  14791. case _:
  14792. raise Exception('type_check_exp: in call, unexpected ' + \
  14793. repr(func_t))
  14794. case _:
  14795. t = self.type_check_exp(e, env)
  14796. self.check_type_equal(t, ty, e)
  14797. \end{lstlisting}
  14798. \fi}
  14799. \end{tcolorbox}
  14800. \caption{Type checking \LangLam{}\python{, part 1}.}
  14801. \label{fig:type-check-Llambda}
  14802. \end{figure}
  14803. {\if\edition\pythonEd
  14804. \begin{figure}[tbp]
  14805. \begin{tcolorbox}[colback=white]
  14806. \begin{lstlisting}
  14807. def check_stmts(self, ss, return_ty, env):
  14808. if len(ss) == 0:
  14809. return
  14810. match ss[0]:
  14811. case FunctionDef(name, params, body, dl, returns, comment):
  14812. new_env = env.copy().update(params)
  14813. rt = self.check_stmts(body, returns, new_env)
  14814. self.check_stmts(ss[1:], return_ty, env)
  14815. case Return(value):
  14816. self.check_exp(value, return_ty, env)
  14817. case Assign([Name(id)], value):
  14818. if id in env:
  14819. self.check_exp(value, env[id], env)
  14820. else:
  14821. env[id] = self.type_check_exp(value, env)
  14822. self.check_stmts(ss[1:], return_ty, env)
  14823. case Assign([Subscript(tup, Constant(index), Store())], value):
  14824. tup_t = self.type_check_exp(tup, env)
  14825. match tup_t:
  14826. case TupleType(ts):
  14827. self.check_exp(value, ts[index], env)
  14828. case _:
  14829. raise Exception('expected a tuple, not ' + repr(tup_t))
  14830. self.check_stmts(ss[1:], return_ty, env)
  14831. case AnnAssign(Name(id), ty_annot, value, simple):
  14832. ss[0].annotation = ty_annot
  14833. if id in env:
  14834. self.check_type_equal(env[id], ty_annot)
  14835. else:
  14836. env[id] = ty_annot
  14837. self.check_exp(value, ty_annot, env)
  14838. self.check_stmts(ss[1:], return_ty, env)
  14839. case _:
  14840. self.type_check_stmts(ss, env)
  14841. def type_check(self, p):
  14842. match p:
  14843. case Module(body):
  14844. env = {}
  14845. for s in body:
  14846. match s:
  14847. case FunctionDef(name, params, bod, dl, returns, comment):
  14848. params_t = [t for (x,t) in params]
  14849. env[name] = FunctionType(params_t, returns)
  14850. self.check_stmts(body, int, env)
  14851. \end{lstlisting}
  14852. \end{tcolorbox}
  14853. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14854. \label{fig:type-check-Llambda-part2}
  14855. \end{figure}
  14856. \fi}
  14857. \clearpage
  14858. \section{Assignment and Lexically Scoped Functions}
  14859. \label{sec:assignment-scoping}
  14860. The combination of lexically scoped functions and assignment to
  14861. variables raises a challenge with the flat-closure approach to
  14862. implementing lexically scoped functions. Consider the following
  14863. example in which function \code{f} has a free variable \code{x} that
  14864. is changed after \code{f} is created but before the call to \code{f}.
  14865. % loop_test_11.rkt
  14866. {\if\edition\racketEd
  14867. \begin{lstlisting}
  14868. (let ([x 0])
  14869. (let ([y 0])
  14870. (let ([z 20])
  14871. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14872. (begin
  14873. (set! x 10)
  14874. (set! y 12)
  14875. (f y))))))
  14876. \end{lstlisting}
  14877. \fi}
  14878. {\if\edition\pythonEd
  14879. % box_free_assign.py
  14880. \begin{lstlisting}
  14881. def g(z : int) -> int:
  14882. x = 0
  14883. y = 0
  14884. f : Callable[[int],int] = lambda a: a + x + z
  14885. x = 10
  14886. y = 12
  14887. return f(y)
  14888. print( g(20) )
  14889. \end{lstlisting}
  14890. \fi} The correct output for this example is \code{42} because the call
  14891. to \code{f} is required to use the current value of \code{x} (which is
  14892. \code{10}). Unfortunately, the closure conversion pass
  14893. (section~\ref{sec:closure-conversion}) generates code for the
  14894. \code{lambda} that copies the old value of \code{x} into a
  14895. closure. Thus, if we naively applied closure conversion, the output of
  14896. this program would be \code{32}.
  14897. A first attempt at solving this problem would be to save a pointer to
  14898. \code{x} in the closure and change the occurrences of \code{x} inside
  14899. the lambda to dereference the pointer. Of course, this would require
  14900. assigning \code{x} to the stack and not to a register. However, the
  14901. problem goes a bit deeper.
  14902. Consider the following example that returns a function that refers to
  14903. a local variable of the enclosing function:
  14904. \begin{center}
  14905. \begin{minipage}{\textwidth}
  14906. {\if\edition\racketEd
  14907. \begin{lstlisting}
  14908. (define (f []) : Integer
  14909. (let ([x 0])
  14910. (let ([g (lambda: () : Integer x)])
  14911. (begin
  14912. (set! x 42)
  14913. g))))
  14914. ((f))
  14915. \end{lstlisting}
  14916. \fi}
  14917. {\if\edition\pythonEd
  14918. % counter.py
  14919. \begin{lstlisting}
  14920. def f():
  14921. x = 0
  14922. g = lambda: x
  14923. x = 42
  14924. return g
  14925. print( f()() )
  14926. \end{lstlisting}
  14927. \fi}
  14928. \end{minipage}
  14929. \end{center}
  14930. In this example, the lifetime of \code{x} extends beyond the lifetime
  14931. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14932. stack frame for the call to \code{f}, it would be gone by the time we
  14933. called \code{g}, leaving us with dangling pointers for
  14934. \code{x}. This example demonstrates that when a variable occurs free
  14935. inside a function, its lifetime becomes indefinite. Thus, the value of
  14936. the variable needs to live on the heap. The verb
  14937. \emph{box}\index{subject}{box} is often used for allocating a single
  14938. value on the heap, producing a pointer, and
  14939. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14940. %
  14941. We introduce a new pass named \code{convert\_assignments} to address
  14942. this challenge.
  14943. %
  14944. \python{But before diving into that, we have one more
  14945. problem to discuss.}
  14946. \if\edition\pythonEd
  14947. \section{Uniquify Variables}
  14948. \label{sec:uniquify-lambda}
  14949. With the addition of \code{lambda} we have a complication to deal
  14950. with: name shadowing. Consider the following program with a function
  14951. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14952. \code{lambda} expressions. The first \code{lambda} has a parameter
  14953. that is also named \code{x}.
  14954. \begin{lstlisting}
  14955. def f(x:int, y:int) -> Callable[[int], int]:
  14956. g : Callable[[int],int] = (lambda x: x + y)
  14957. h : Callable[[int],int] = (lambda y: x + y)
  14958. x = input_int()
  14959. return g
  14960. print(f(0, 10)(32))
  14961. \end{lstlisting}
  14962. Many of our compiler passes rely on being able to connect variable
  14963. uses with their definitions using just the name of the variable,
  14964. including new passes in this chapter. However, in the above example
  14965. the name of the variable does not uniquely determine its
  14966. definition. To solve this problem we recommend implementing a pass
  14967. named \code{uniquify} that renames every variable in the program to
  14968. make sure they are all unique.
  14969. The following shows the result of \code{uniquify} for the above
  14970. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14971. and the \code{x} parameter of the \code{lambda} is renamed to
  14972. \code{x\_4}.
  14973. \begin{lstlisting}
  14974. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14975. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14976. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14977. x_0 = input_int()
  14978. return g_2
  14979. def main() -> int :
  14980. print(f(0, 10)(32))
  14981. return 0
  14982. \end{lstlisting}
  14983. \fi
  14984. %% \section{Reveal Functions}
  14985. %% \label{sec:reveal-functions-r5}
  14986. %% \racket{To support the \code{procedure-arity} operator we need to
  14987. %% communicate the arity of a function to the point of closure
  14988. %% creation.}
  14989. %% %
  14990. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  14991. %% function at runtime. Thus, we need to communicate the arity of a
  14992. %% function to the point of closure creation.}
  14993. %% %
  14994. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14995. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14996. %% \[
  14997. %% \begin{array}{lcl}
  14998. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14999. %% \end{array}
  15000. %% \]
  15001. \section{Assignment Conversion}
  15002. \label{sec:convert-assignments}
  15003. The purpose of the \code{convert\_assignments} pass is to address the
  15004. challenge regarding the interaction between variable assignments and
  15005. closure conversion. First we identify which variables need to be
  15006. boxed, and then we transform the program to box those variables. In
  15007. general, boxing introduces runtime overhead that we would like to
  15008. avoid, so we should box as few variables as possible. We recommend
  15009. boxing the variables in the intersection of the following two sets of
  15010. variables:
  15011. \begin{enumerate}
  15012. \item The variables that are free in a \code{lambda}.
  15013. \item The variables that appear on the left-hand side of an
  15014. assignment.
  15015. \end{enumerate}
  15016. The first condition is a must but the second condition is
  15017. conservative. It is possible to develop a more liberal condition using
  15018. static program analysis.
  15019. Consider again the first example from
  15020. section~\ref{sec:assignment-scoping}:
  15021. %
  15022. {\if\edition\racketEd
  15023. \begin{lstlisting}
  15024. (let ([x 0])
  15025. (let ([y 0])
  15026. (let ([z 20])
  15027. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15028. (begin
  15029. (set! x 10)
  15030. (set! y 12)
  15031. (f y))))))
  15032. \end{lstlisting}
  15033. \fi}
  15034. {\if\edition\pythonEd
  15035. \begin{lstlisting}
  15036. def g(z : int) -> int:
  15037. x = 0
  15038. y = 0
  15039. f : Callable[[int],int] = lambda a: a + x + z
  15040. x = 10
  15041. y = 12
  15042. return f(y)
  15043. print( g(20) )
  15044. \end{lstlisting}
  15045. \fi}
  15046. %
  15047. \noindent The variables \code{x} and \code{y} are assigned to. The
  15048. variables \code{x} and \code{z} occur free inside the
  15049. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  15050. \code{y} or \code{z}. The boxing of \code{x} consists of three
  15051. transformations: initialize \code{x} with a tuple whose elements are
  15052. uninitialized, replace reads from \code{x} with tuple reads, and
  15053. replace each assignment to \code{x} with a tuple write. The output of
  15054. \code{convert\_assignments} for this example is as follows:
  15055. %
  15056. {\if\edition\racketEd
  15057. \begin{lstlisting}
  15058. (define (main) : Integer
  15059. (let ([x0 (vector 0)])
  15060. (let ([y1 0])
  15061. (let ([z2 20])
  15062. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  15063. (+ a3 (+ (vector-ref x0 0) z2)))])
  15064. (begin
  15065. (vector-set! x0 0 10)
  15066. (set! y1 12)
  15067. (f4 y1)))))))
  15068. \end{lstlisting}
  15069. \fi}
  15070. %
  15071. {\if\edition\pythonEd
  15072. \begin{lstlisting}
  15073. def g(z : int)-> int:
  15074. x = (uninitialized(int),)
  15075. x[0] = 0
  15076. y = 0
  15077. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  15078. x[0] = 10
  15079. y = 12
  15080. return f(y)
  15081. def main() -> int:
  15082. print(g(20))
  15083. return 0
  15084. \end{lstlisting}
  15085. \fi}
  15086. To compute the free variables of all the \code{lambda} expressions, we
  15087. recommend defining the following two auxiliary functions:
  15088. \begin{enumerate}
  15089. \item \code{free\_variables} computes the free variables of an expression, and
  15090. \item \code{free\_in\_lambda} collects all the variables that are
  15091. free in any of the \code{lambda} expressions, using
  15092. \code{free\_variables} in the case for each \code{lambda}.
  15093. \end{enumerate}
  15094. {\if\edition\racketEd
  15095. %
  15096. To compute the variables that are assigned to, we recommend updating
  15097. the \code{collect-set!} function that we introduced in
  15098. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  15099. as \code{Lambda}.
  15100. %
  15101. \fi}
  15102. {\if\edition\pythonEd
  15103. %
  15104. To compute the variables that are assigned to, we recommend defining
  15105. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  15106. the set of variables that occur in the left-hand side of an assignment
  15107. statement, and otherwise returns the empty set.
  15108. %
  15109. \fi}
  15110. Let $\mathit{AF}$ be the intersection of the set of variables that are
  15111. free in a \code{lambda} and that are assigned to in the enclosing
  15112. function definition.
  15113. Next we discuss the \code{convert\_assignments} pass. In the case for
  15114. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  15115. $\VAR{x}$ to a tuple read.
  15116. %
  15117. {\if\edition\racketEd
  15118. \begin{lstlisting}
  15119. (Var |$x$|)
  15120. |$\Rightarrow$|
  15121. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  15122. \end{lstlisting}
  15123. \fi}
  15124. %
  15125. {\if\edition\pythonEd
  15126. \begin{lstlisting}
  15127. Name(|$x$|)
  15128. |$\Rightarrow$|
  15129. Subscript(Name(|$x$|), Constant(0), Load())
  15130. \end{lstlisting}
  15131. \fi}
  15132. %
  15133. \noindent In the case for assignment, recursively process the
  15134. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  15135. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  15136. as follows:
  15137. %
  15138. {\if\edition\racketEd
  15139. \begin{lstlisting}
  15140. (SetBang |$x$| |$\itm{rhs}$|)
  15141. |$\Rightarrow$|
  15142. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  15143. \end{lstlisting}
  15144. \fi}
  15145. {\if\edition\pythonEd
  15146. \begin{lstlisting}
  15147. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  15148. |$\Rightarrow$|
  15149. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  15150. \end{lstlisting}
  15151. \fi}
  15152. %
  15153. {\if\edition\racketEd
  15154. The case for \code{Lambda} is nontrivial, but it is similar to the
  15155. case for function definitions, which we discuss next.
  15156. \fi}
  15157. %
  15158. To translate a function definition, we first compute $\mathit{AF}$,
  15159. the intersection of the variables that are free in a \code{lambda} and
  15160. that are assigned to. We then apply assignment conversion to the body
  15161. of the function definition. Finally, we box the parameters of this
  15162. function definition that are in $\mathit{AF}$. For example,
  15163. the parameter \code{x} of the following function \code{g}
  15164. needs to be boxed:
  15165. {\if\edition\racketEd
  15166. \begin{lstlisting}
  15167. (define (g [x : Integer]) : Integer
  15168. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  15169. (begin
  15170. (set! x 10)
  15171. (f 32))))
  15172. \end{lstlisting}
  15173. \fi}
  15174. %
  15175. {\if\edition\pythonEd
  15176. \begin{lstlisting}
  15177. def g(x : int) -> int:
  15178. f : Callable[[int],int] = lambda a: a + x
  15179. x = 10
  15180. return f(32)
  15181. \end{lstlisting}
  15182. \fi}
  15183. %
  15184. \noindent We box parameter \code{x} by creating a local variable named
  15185. \code{x} that is initialized to a tuple whose contents is the value of
  15186. the parameter, which has been renamed to \code{x\_0}.
  15187. %
  15188. {\if\edition\racketEd
  15189. \begin{lstlisting}
  15190. (define (g [x_0 : Integer]) : Integer
  15191. (let ([x (vector x_0)])
  15192. (let ([f (lambda: ([a : Integer]) : Integer
  15193. (+ a (vector-ref x 0)))])
  15194. (begin
  15195. (vector-set! x 0 10)
  15196. (f 32)))))
  15197. \end{lstlisting}
  15198. \fi}
  15199. %
  15200. {\if\edition\pythonEd
  15201. \begin{lstlisting}
  15202. def g(x_0 : int)-> int:
  15203. x = (x_0,)
  15204. f : Callable[[int], int] = (lambda a: a + x[0])
  15205. x[0] = 10
  15206. return f(32)
  15207. \end{lstlisting}
  15208. \fi}
  15209. \section{Closure Conversion}
  15210. \label{sec:closure-conversion}
  15211. \index{subject}{closure conversion}
  15212. The compiling of lexically scoped functions into top-level function
  15213. definitions and flat closures is accomplished in the pass
  15214. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  15215. and before \code{limit\_functions}.
  15216. As usual, we implement the pass as a recursive function over the
  15217. AST. The interesting cases are for \key{lambda} and function
  15218. application. We transform a \key{lambda} expression into an expression
  15219. that creates a closure, that is, a tuple for which the first element
  15220. is a function pointer and the rest of the elements are the values of
  15221. the free variables of the \key{lambda}.
  15222. %
  15223. However, we use the \code{Closure} AST node instead of using a tuple
  15224. so that we can record the arity.
  15225. %
  15226. In the generated code that follows, \itm{fvs} is the free variables of
  15227. the lambda and \itm{name} is a unique symbol generated to identify the
  15228. lambda.
  15229. %
  15230. \racket{The \itm{arity} is the number of parameters (the length of
  15231. \itm{ps}).}
  15232. %
  15233. {\if\edition\racketEd
  15234. \begin{lstlisting}
  15235. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  15236. |$\Rightarrow$|
  15237. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  15238. \end{lstlisting}
  15239. \fi}
  15240. %
  15241. {\if\edition\pythonEd
  15242. \begin{lstlisting}
  15243. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  15244. |$\Rightarrow$|
  15245. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  15246. \end{lstlisting}
  15247. \fi}
  15248. %
  15249. In addition to transforming each \key{Lambda} AST node into a
  15250. tuple, we create a top-level function definition for each
  15251. \key{Lambda}, as shown next.\\
  15252. \begin{minipage}{0.8\textwidth}
  15253. {\if\edition\racketEd
  15254. \begin{lstlisting}
  15255. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  15256. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  15257. ...
  15258. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  15259. |\itm{body'}|)...))
  15260. \end{lstlisting}
  15261. \fi}
  15262. {\if\edition\pythonEd
  15263. \begin{lstlisting}
  15264. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  15265. |$\itm{fvs}_1$| = clos[1]
  15266. |$\ldots$|
  15267. |$\itm{fvs}_n$| = clos[|$n$|]
  15268. |\itm{body'}|
  15269. \end{lstlisting}
  15270. \fi}
  15271. \end{minipage}\\
  15272. The \code{clos} parameter refers to the closure. Translate the type
  15273. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  15274. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  15275. \itm{closTy} is a tuple type for which the first element type is
  15276. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  15277. the element types are the types of the free variables in the
  15278. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  15279. is nontrivial to give a type to the function in the closure's type.%
  15280. %
  15281. \footnote{To give an accurate type to a closure, we would need to add
  15282. existential types to the type checker~\citep{Minamide:1996ys}.}
  15283. %
  15284. %% The dummy type is considered to be equal to any other type during type
  15285. %% checking.
  15286. The free variables become local variables that are initialized with
  15287. their values in the closure.
  15288. Closure conversion turns every function into a tuple, so the type
  15289. annotations in the program must also be translated. We recommend
  15290. defining an auxiliary recursive function for this purpose. Function
  15291. types should be translated as follows:
  15292. %
  15293. {\if\edition\racketEd
  15294. \begin{lstlisting}
  15295. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  15296. |$\Rightarrow$|
  15297. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  15298. \end{lstlisting}
  15299. \fi}
  15300. {\if\edition\pythonEd
  15301. \begin{lstlisting}
  15302. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  15303. |$\Rightarrow$|
  15304. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  15305. \end{lstlisting}
  15306. \fi}
  15307. %
  15308. This type indicates that the first thing in the tuple is a
  15309. function. The first parameter of the function is a tuple (a closure)
  15310. and the rest of the parameters are the ones from the original
  15311. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  15312. omits the types of the free variables because (1) those types are not
  15313. available in this context, and (2) we do not need them in the code that
  15314. is generated for function application. So this type describes only the
  15315. first component of the closure tuple. At runtime the tuple may have
  15316. more components, but we ignore them at this point.
  15317. We transform function application into code that retrieves the
  15318. function from the closure and then calls the function, passing the
  15319. closure as the first argument. We place $e'$ in a temporary variable
  15320. to avoid code duplication.
  15321. \begin{center}
  15322. \begin{minipage}{\textwidth}
  15323. {\if\edition\racketEd
  15324. \begin{lstlisting}
  15325. (Apply |$e$| |$\itm{es}$|)
  15326. |$\Rightarrow$|
  15327. (Let |$\itm{tmp}$| |$e'$|
  15328. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  15329. \end{lstlisting}
  15330. \fi}
  15331. %
  15332. {\if\edition\pythonEd
  15333. \begin{lstlisting}
  15334. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  15335. |$\Rightarrow$|
  15336. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  15337. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  15338. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  15339. \end{lstlisting}
  15340. \fi}
  15341. \end{minipage}
  15342. \end{center}
  15343. There is also the question of what to do with references to top-level
  15344. function definitions. To maintain a uniform translation of function
  15345. application, we turn function references into closures.
  15346. \begin{tabular}{lll}
  15347. \begin{minipage}{0.3\textwidth}
  15348. {\if\edition\racketEd
  15349. \begin{lstlisting}
  15350. (FunRef |$f$| |$n$|)
  15351. \end{lstlisting}
  15352. \fi}
  15353. {\if\edition\pythonEd
  15354. \begin{lstlisting}
  15355. FunRef(|$f$|, |$n$|)
  15356. \end{lstlisting}
  15357. \fi}
  15358. \end{minipage}
  15359. &
  15360. $\Rightarrow$
  15361. &
  15362. \begin{minipage}{0.5\textwidth}
  15363. {\if\edition\racketEd
  15364. \begin{lstlisting}
  15365. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  15366. \end{lstlisting}
  15367. \fi}
  15368. {\if\edition\pythonEd
  15369. \begin{lstlisting}
  15370. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  15371. \end{lstlisting}
  15372. \fi}
  15373. \end{minipage}
  15374. \end{tabular} \\
  15375. We no longer need the annotated assignment statement \code{AnnAssign}
  15376. to support the type checking of \code{lambda} expressions, so we
  15377. translate it to a regular \code{Assign} statement.
  15378. The top-level function definitions need to be updated to take an extra
  15379. closure parameter, but that parameter is ignored in the body of those
  15380. functions.
  15381. \section{An Example Translation}
  15382. \label{sec:example-lambda}
  15383. Figure~\ref{fig:lexical-functions-example} shows the result of
  15384. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  15385. program demonstrating lexical scoping that we discussed at the
  15386. beginning of this chapter.
  15387. \begin{figure}[tbp]
  15388. \begin{tcolorbox}[colback=white]
  15389. \begin{minipage}{0.8\textwidth}
  15390. {\if\edition\racketEd
  15391. % tests/lambda_test_6.rkt
  15392. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15393. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  15394. (let ([y8 4])
  15395. (lambda: ([z9 : Integer]) : Integer
  15396. (+ x7 (+ y8 z9)))))
  15397. (define (main) : Integer
  15398. (let ([g0 ((fun-ref f6 1) 5)])
  15399. (let ([h1 ((fun-ref f6 1) 3)])
  15400. (+ (g0 11) (h1 15)))))
  15401. \end{lstlisting}
  15402. $\Rightarrow$
  15403. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15404. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  15405. (let ([y8 4])
  15406. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  15407. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  15408. (let ([x7 (vector-ref fvs3 1)])
  15409. (let ([y8 (vector-ref fvs3 2)])
  15410. (+ x7 (+ y8 z9)))))
  15411. (define (main) : Integer
  15412. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  15413. ((vector-ref clos5 0) clos5 5))])
  15414. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  15415. ((vector-ref clos6 0) clos6 3))])
  15416. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  15417. \end{lstlisting}
  15418. \fi}
  15419. %
  15420. {\if\edition\pythonEd
  15421. % free_var.py
  15422. \begin{lstlisting}
  15423. def f(x : int) -> Callable[[int], int]:
  15424. y = 4
  15425. return lambda z: x + y + z
  15426. g = f(5)
  15427. h = f(3)
  15428. print( g(11) + h(15) )
  15429. \end{lstlisting}
  15430. $\Rightarrow$
  15431. \begin{lstlisting}
  15432. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  15433. x = fvs_1[1]
  15434. y = fvs_1[2]
  15435. return x + y[0] + z
  15436. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  15437. y = (777,)
  15438. y[0] = 4
  15439. return (lambda_0, x, y)
  15440. def main() -> int:
  15441. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  15442. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  15443. print((let clos_5 = g in clos_5[0](clos_5, 11))
  15444. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  15445. return 0
  15446. \end{lstlisting}
  15447. \fi}
  15448. \end{minipage}
  15449. \end{tcolorbox}
  15450. \caption{Example of closure conversion.}
  15451. \label{fig:lexical-functions-example}
  15452. \end{figure}
  15453. \begin{exercise}\normalfont\normalsize
  15454. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  15455. Create five new programs that use \key{lambda} functions and make use of
  15456. lexical scoping. Test your compiler on these new programs and all
  15457. your previously created test programs.
  15458. \end{exercise}
  15459. \section{Expose Allocation}
  15460. \label{sec:expose-allocation-r5}
  15461. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  15462. that allocates and initializes a tuple, similar to the translation of
  15463. the tuple creation in section~\ref{sec:expose-allocation}.
  15464. The only difference is replacing the use of
  15465. \ALLOC{\itm{len}}{\itm{type}} with
  15466. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  15467. \section{Explicate Control and \LangCLam{}}
  15468. \label{sec:explicate-r5}
  15469. The output language of \code{explicate\_control} is \LangCLam{}; the
  15470. definition of its abstract syntax is shown in
  15471. figure~\ref{fig:Clam-syntax}.
  15472. %
  15473. \racket{The only differences with respect to \LangCFun{} are the
  15474. addition of the \code{AllocateClosure} form to the grammar for
  15475. $\Exp$ and the \code{procedure-arity} operator. The handling of
  15476. \code{AllocateClosure} in the \code{explicate\_control} pass is
  15477. similar to the handling of other expressions such as primitive
  15478. operators.}
  15479. %
  15480. \python{The differences with respect to \LangCFun{} are the
  15481. additions of \code{Uninitialized}, \code{AllocateClosure},
  15482. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  15483. \code{explicate\_control} pass is similar to the handling of other
  15484. expressions such as primitive operators.}
  15485. \newcommand{\ClambdaASTRacket}{
  15486. \begin{array}{lcl}
  15487. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  15488. \itm{op} &::= & \code{procedure-arity}
  15489. \end{array}
  15490. }
  15491. \newcommand{\ClambdaASTPython}{
  15492. \begin{array}{lcl}
  15493. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  15494. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  15495. &\MID& \ARITY{\Atm}
  15496. \end{array}
  15497. }
  15498. \begin{figure}[tp]
  15499. \begin{tcolorbox}[colback=white]
  15500. \small
  15501. {\if\edition\racketEd
  15502. \[
  15503. \begin{array}{l}
  15504. \gray{\CvarASTRacket} \\ \hline
  15505. \gray{\CifASTRacket} \\ \hline
  15506. \gray{\CloopASTRacket} \\ \hline
  15507. \gray{\CtupASTRacket} \\ \hline
  15508. \gray{\CfunASTRacket} \\ \hline
  15509. \ClambdaASTRacket \\
  15510. \begin{array}{lcl}
  15511. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  15512. \end{array}
  15513. \end{array}
  15514. \]
  15515. \fi}
  15516. {\if\edition\pythonEd
  15517. \[
  15518. \begin{array}{l}
  15519. \gray{\CifASTPython} \\ \hline
  15520. \gray{\CtupASTPython} \\ \hline
  15521. \gray{\CfunASTPython} \\ \hline
  15522. \ClambdaASTPython \\
  15523. \begin{array}{lcl}
  15524. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  15525. \end{array}
  15526. \end{array}
  15527. \]
  15528. \fi}
  15529. \end{tcolorbox}
  15530. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  15531. \label{fig:Clam-syntax}
  15532. \end{figure}
  15533. \section{Select Instructions}
  15534. \label{sec:select-instructions-Llambda}
  15535. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  15536. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  15537. (section~\ref{sec:select-instructions-gc}). The only difference is
  15538. that you should place the \itm{arity} in the tag that is stored at
  15539. position $0$ of the vector. Recall that in
  15540. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  15541. was not used. We store the arity in the $5$ bits starting at position
  15542. $58$.
  15543. \racket{Compile the \code{procedure-arity} operator into a sequence of
  15544. instructions that access the tag from position $0$ of the vector and
  15545. extract the $5$ bits starting at position $58$ from the tag.}
  15546. %
  15547. \python{Compile a call to the \code{arity} operator to a sequence of
  15548. instructions that access the tag from position $0$ of the tuple
  15549. (representing a closure) and extract the $5$-bits starting at position
  15550. $58$ from the tag.}
  15551. \begin{figure}[p]
  15552. \begin{tcolorbox}[colback=white]
  15553. {\if\edition\racketEd
  15554. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15555. \node (Lfun) at (0,2) {\large \LangLam{}};
  15556. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  15557. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  15558. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  15559. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  15560. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  15561. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  15562. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  15563. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  15564. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  15565. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  15566. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  15567. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  15568. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  15569. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  15570. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  15571. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  15572. \path[->,bend left=15] (Lfun) edge [above] node
  15573. {\ttfamily\footnotesize shrink} (Lfun-2);
  15574. \path[->,bend left=15] (Lfun-2) edge [above] node
  15575. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15576. \path[->,bend left=15] (Lfun-3) edge [above] node
  15577. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15578. \path[->,bend left=15] (F1-0) edge [left] node
  15579. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15580. \path[->,bend left=15] (F1-1) edge [below] node
  15581. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  15582. \path[->,bend right=15] (F1-2) edge [above] node
  15583. {\ttfamily\footnotesize limit\_functions} (F1-3);
  15584. \path[->,bend right=15] (F1-3) edge [above] node
  15585. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  15586. \path[->,bend left=15] (F1-4) edge [right] node
  15587. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  15588. \path[->,bend right=15] (F1-5) edge [below] node
  15589. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  15590. \path[->,bend left=15] (F1-6) edge [above] node
  15591. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15592. \path[->] (C3-2) edge [right] node
  15593. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15594. \path[->,bend right=15] (x86-2) edge [right] node
  15595. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15596. \path[->,bend right=15] (x86-2-1) edge [below] node
  15597. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15598. \path[->,bend right=15] (x86-2-2) edge [right] node
  15599. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15600. \path[->,bend left=15] (x86-3) edge [above] node
  15601. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15602. \path[->,bend left=15] (x86-4) edge [right] node
  15603. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15604. \end{tikzpicture}
  15605. \fi}
  15606. {\if\edition\pythonEd
  15607. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15608. \node (Lfun) at (0,2) {\large \LangLam{}};
  15609. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  15610. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  15611. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  15612. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  15613. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  15614. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  15615. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  15616. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  15617. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  15618. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  15619. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  15620. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  15621. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  15622. \path[->,bend left=15] (Lfun) edge [above] node
  15623. {\ttfamily\footnotesize shrink} (Lfun-2);
  15624. \path[->,bend left=15] (Lfun-2) edge [above] node
  15625. {\ttfamily\footnotesize uniquify} (Lfun-3);
  15626. \path[->,bend left=15] (Lfun-3) edge [above] node
  15627. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  15628. \path[->,bend left=15] (F1-0) edge [left] node
  15629. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  15630. \path[->,bend left=15] (F1-1) edge [below] node
  15631. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  15632. \path[->,bend left=15] (F1-2) edge [below] node
  15633. {\ttfamily\footnotesize limit\_functions} (F1-3);
  15634. \path[->,bend right=15] (F1-3) edge [above] node
  15635. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  15636. \path[->,bend right=15] (F1-5) edge [right] node
  15637. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  15638. \path[->,bend left=15] (F1-6) edge [right] node
  15639. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15640. \path[->,bend right=15] (C3-2) edge [right] node
  15641. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15642. \path[->,bend right=15] (x86-2) edge [below] node
  15643. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15644. \path[->,bend right=15] (x86-3) edge [below] node
  15645. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15646. \path[->,bend left=15] (x86-4) edge [above] node
  15647. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15648. \end{tikzpicture}
  15649. \fi}
  15650. \end{tcolorbox}
  15651. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  15652. functions.}
  15653. \label{fig:Llambda-passes}
  15654. \end{figure}
  15655. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  15656. needed for the compilation of \LangLam{}.
  15657. \clearpage
  15658. \section{Challenge: Optimize Closures}
  15659. \label{sec:optimize-closures}
  15660. In this chapter we compile lexically scoped functions into a
  15661. relatively efficient representation: flat closures. However, even this
  15662. representation comes with some overhead. For example, consider the
  15663. following program with a function \code{tail\_sum} that does not have
  15664. any free variables and where all the uses of \code{tail\_sum} are in
  15665. applications in which we know that only \code{tail\_sum} is being applied
  15666. (and not any other functions):
  15667. \begin{center}
  15668. \begin{minipage}{0.95\textwidth}
  15669. {\if\edition\racketEd
  15670. \begin{lstlisting}
  15671. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  15672. (if (eq? n 0)
  15673. s
  15674. (tail_sum (- n 1) (+ n s))))
  15675. (+ (tail_sum 3 0) 36)
  15676. \end{lstlisting}
  15677. \fi}
  15678. {\if\edition\pythonEd
  15679. \begin{lstlisting}
  15680. def tail_sum(n : int, s : int) -> int:
  15681. if n == 0:
  15682. return s
  15683. else:
  15684. return tail_sum(n - 1, n + s)
  15685. print( tail_sum(3, 0) + 36)
  15686. \end{lstlisting}
  15687. \fi}
  15688. \end{minipage}
  15689. \end{center}
  15690. As described in this chapter, we uniformly apply closure conversion to
  15691. all functions, obtaining the following output for this program:
  15692. \begin{center}
  15693. \begin{minipage}{0.95\textwidth}
  15694. {\if\edition\racketEd
  15695. \begin{lstlisting}
  15696. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  15697. (if (eq? n2 0)
  15698. s3
  15699. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  15700. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  15701. (define (main) : Integer
  15702. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  15703. ((vector-ref clos6 0) clos6 3 0)) 27))
  15704. \end{lstlisting}
  15705. \fi}
  15706. {\if\edition\pythonEd
  15707. \begin{lstlisting}
  15708. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  15709. if n_0 == 0:
  15710. return s_1
  15711. else:
  15712. return (let clos_2 = (tail_sum,)
  15713. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  15714. def main() -> int :
  15715. print((let clos_4 = (tail_sum,)
  15716. in clos_4[0](clos_4, 3, 0)) + 36)
  15717. return 0
  15718. \end{lstlisting}
  15719. \fi}
  15720. \end{minipage}
  15721. \end{center}
  15722. If this program were compiled according to the previous chapter, there
  15723. would be no allocation and the calls to \code{tail\_sum} would be
  15724. direct calls. In contrast, the program presented here allocates memory
  15725. for each closure and the calls to \code{tail\_sum} are indirect. These
  15726. two differences incur considerable overhead in a program such as this,
  15727. in which the allocations and indirect calls occur inside a tight loop.
  15728. One might think that this problem is trivial to solve: can't we just
  15729. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  15730. and compile them to direct calls instead of treating it like a call to
  15731. a closure? We would also drop the new \code{fvs} parameter of
  15732. \code{tail\_sum}.
  15733. %
  15734. However, this problem is not so trivial, because a global function may
  15735. \emph{escape} and become involved in applications that also involve
  15736. closures. Consider the following example in which the application
  15737. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  15738. application because the \code{lambda} may flow into \code{f}, but the
  15739. \code{inc} function might also flow into \code{f}:
  15740. \begin{center}
  15741. \begin{minipage}{\textwidth}
  15742. % lambda_test_30.rkt
  15743. {\if\edition\racketEd
  15744. \begin{lstlisting}
  15745. (define (inc [x : Integer]) : Integer
  15746. (+ x 1))
  15747. (let ([y (read)])
  15748. (let ([f (if (eq? (read) 0)
  15749. inc
  15750. (lambda: ([x : Integer]) : Integer (- x y)))])
  15751. (f 41)))
  15752. \end{lstlisting}
  15753. \fi}
  15754. {\if\edition\pythonEd
  15755. \begin{lstlisting}
  15756. def add1(x : int) -> int:
  15757. return x + 1
  15758. y = input_int()
  15759. g : Callable[[int], int] = lambda x: x - y
  15760. f = add1 if input_int() == 0 else g
  15761. print( f(41) )
  15762. \end{lstlisting}
  15763. \fi}
  15764. \end{minipage}
  15765. \end{center}
  15766. If a global function name is used in any way other than as the
  15767. operator in a direct call, then we say that the function
  15768. \emph{escapes}. If a global function does not escape, then we do not
  15769. need to perform closure conversion on the function.
  15770. \begin{exercise}\normalfont\normalsize
  15771. Implement an auxiliary function for detecting which global
  15772. functions escape. Using that function, implement an improved version
  15773. of closure conversion that does not apply closure conversion to
  15774. global functions that do not escape but instead compiles them as
  15775. regular functions. Create several new test cases that check whether
  15776. your compiler properly detect whether global functions escape or not.
  15777. \end{exercise}
  15778. So far we have reduced the overhead of calling global functions, but
  15779. it would also be nice to reduce the overhead of calling a
  15780. \code{lambda} when we can determine at compile time which
  15781. \code{lambda} will be called. We refer to such calls as \emph{known
  15782. calls}. Consider the following example in which a \code{lambda} is
  15783. bound to \code{f} and then applied.
  15784. {\if\edition\racketEd
  15785. % lambda_test_9.rkt
  15786. \begin{lstlisting}
  15787. (let ([y (read)])
  15788. (let ([f (lambda: ([x : Integer]) : Integer
  15789. (+ x y))])
  15790. (f 21)))
  15791. \end{lstlisting}
  15792. \fi}
  15793. {\if\edition\pythonEd
  15794. \begin{lstlisting}
  15795. y = input_int()
  15796. f : Callable[[int],int] = lambda x: x + y
  15797. print( f(21) )
  15798. \end{lstlisting}
  15799. \fi}
  15800. %
  15801. \noindent Closure conversion compiles the application
  15802. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  15803. %
  15804. {\if\edition\racketEd
  15805. \begin{lstlisting}
  15806. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15807. (let ([y2 (vector-ref fvs6 1)])
  15808. (+ x3 y2)))
  15809. (define (main) : Integer
  15810. (let ([y2 (read)])
  15811. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15812. ((vector-ref f4 0) f4 21))))
  15813. \end{lstlisting}
  15814. \fi}
  15815. {\if\edition\pythonEd
  15816. \begin{lstlisting}
  15817. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15818. y_1 = fvs_4[1]
  15819. return x_2 + y_1[0]
  15820. def main() -> int:
  15821. y_1 = (777,)
  15822. y_1[0] = input_int()
  15823. f_0 = (lambda_3, y_1)
  15824. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15825. return 0
  15826. \end{lstlisting}
  15827. \fi}
  15828. %
  15829. \noindent However, we can instead compile the application
  15830. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  15831. %
  15832. {\if\edition\racketEd
  15833. \begin{lstlisting}
  15834. (define (main) : Integer
  15835. (let ([y2 (read)])
  15836. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15837. ((fun-ref lambda5 1) f4 21))))
  15838. \end{lstlisting}
  15839. \fi}
  15840. {\if\edition\pythonEd
  15841. \begin{lstlisting}
  15842. def main() -> int:
  15843. y_1 = (777,)
  15844. y_1[0] = input_int()
  15845. f_0 = (lambda_3, y_1)
  15846. print(lambda_3(f_0, 21))
  15847. return 0
  15848. \end{lstlisting}
  15849. \fi}
  15850. The problem of determining which \code{lambda} will be called from a
  15851. particular application is quite challenging in general and the topic
  15852. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15853. following exercise we recommend that you compile an application to a
  15854. direct call when the operator is a variable and \racket{the variable
  15855. is \code{let}-bound to a closure}\python{the previous assignment to
  15856. the variable is a closure}. This can be accomplished by maintaining
  15857. an environment that maps variables to function names. Extend the
  15858. environment whenever you encounter a closure on the right-hand side of
  15859. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15860. name of the global function for the closure. This pass should come
  15861. after closure conversion.
  15862. \begin{exercise}\normalfont\normalsize
  15863. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15864. compiles known calls into direct calls. Verify that your compiler is
  15865. successful in this regard on several example programs.
  15866. \end{exercise}
  15867. These exercises only scratch the surface of closure optimization. A
  15868. good next step for the interested reader is to look at the work of
  15869. \citet{Keep:2012ab}.
  15870. \section{Further Reading}
  15871. The notion of lexically scoped functions predates modern computers by
  15872. about a decade. They were invented by \citet{Church:1932aa}, who
  15873. proposed the lambda calculus as a foundation for logic. Anonymous
  15874. functions were included in the LISP~\citep{McCarthy:1960dz}
  15875. programming language but were initially dynamically scoped. The Scheme
  15876. dialect of LISP adopted lexical scoping, and
  15877. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15878. Scheme programs. However, environments were represented as linked
  15879. lists, so variable look-up was linear in the size of the
  15880. environment. \citet{Appel91} gives a detailed description of several
  15881. closure representations. In this chapter we represent environments
  15882. using flat closures, which were invented by
  15883. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15884. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15885. closures, variable look-up is constant time but the time to create a
  15886. closure is proportional to the number of its free variables. Flat
  15887. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  15888. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15889. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15890. % compilers)
  15891. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15892. \chapter{Dynamic Typing}
  15893. \label{ch:Ldyn}
  15894. \index{subject}{dynamic typing}
  15895. \setcounter{footnote}{0}
  15896. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15897. typed language that is a subset of \racket{Racket}\python{Python}. The
  15898. focus on dynamic typing is in contrast to the previous chapters, which
  15899. have studied the compilation of statically typed languages. In
  15900. dynamically typed languages such as \LangDyn{}, a particular
  15901. expression may produce a value of a different type each time it is
  15902. executed. Consider the following example with a conditional \code{if}
  15903. expression that may return a Boolean or an integer depending on the
  15904. input to the program:
  15905. % part of dynamic_test_25.rkt
  15906. {\if\edition\racketEd
  15907. \begin{lstlisting}
  15908. (not (if (eq? (read) 1) #f 0))
  15909. \end{lstlisting}
  15910. \fi}
  15911. {\if\edition\pythonEd
  15912. \begin{lstlisting}
  15913. not (False if input_int() == 1 else 0)
  15914. \end{lstlisting}
  15915. \fi}
  15916. Languages that allow expressions to produce different kinds of values
  15917. are called \emph{polymorphic}, a word composed of the Greek roots
  15918. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  15919. There are several kinds of polymorphism in programming languages, such as
  15920. subtype polymorphism and parametric polymorphism
  15921. (aka. generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  15922. study in this chapter does not have a special name; it is the kind
  15923. that arises in dynamically typed languages.
  15924. Another characteristic of dynamically typed languages is that
  15925. their primitive operations, such as \code{not}, are often defined to operate
  15926. on many different types of values. In fact, in
  15927. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15928. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  15929. given anything else it returns \FALSE{}.
  15930. Furthermore, even when primitive operations restrict their inputs to
  15931. values of a certain type, this restriction is enforced at runtime
  15932. instead of during compilation. For example, the tuple read
  15933. operation
  15934. \racket{\code{(vector-ref \#t 0)}}
  15935. \python{\code{True[0]}}
  15936. results in a runtime error because the first argument must
  15937. be a tuple, not a Boolean.
  15938. \section{The \LangDyn{} Language}
  15939. \newcommand{\LdynGrammarRacket}{
  15940. \begin{array}{rcl}
  15941. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15942. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15943. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15944. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15945. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15946. \end{array}
  15947. }
  15948. \newcommand{\LdynASTRacket}{
  15949. \begin{array}{lcl}
  15950. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15951. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15952. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15953. \end{array}
  15954. }
  15955. \begin{figure}[tp]
  15956. \centering
  15957. \begin{tcolorbox}[colback=white]
  15958. \small
  15959. {\if\edition\racketEd
  15960. \[
  15961. \begin{array}{l}
  15962. \gray{\LintGrammarRacket{}} \\ \hline
  15963. \gray{\LvarGrammarRacket{}} \\ \hline
  15964. \gray{\LifGrammarRacket{}} \\ \hline
  15965. \gray{\LwhileGrammarRacket} \\ \hline
  15966. \gray{\LtupGrammarRacket} \\ \hline
  15967. \LdynGrammarRacket \\
  15968. \begin{array}{rcl}
  15969. \LangDynM{} &::=& \Def\ldots\; \Exp
  15970. \end{array}
  15971. \end{array}
  15972. \]
  15973. \fi}
  15974. {\if\edition\pythonEd
  15975. \[
  15976. \begin{array}{rcl}
  15977. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15978. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15979. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15980. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15981. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15982. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15983. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15984. \MID \CLEN{\Exp} \\
  15985. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15986. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15987. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15988. \MID \Var\mathop{\key{=}}\Exp \\
  15989. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15990. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15991. &\MID& \CRETURN{\Exp} \\
  15992. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15993. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15994. \end{array}
  15995. \]
  15996. \fi}
  15997. \end{tcolorbox}
  15998. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15999. \label{fig:r7-concrete-syntax}
  16000. \end{figure}
  16001. \begin{figure}[tp]
  16002. \centering
  16003. \begin{tcolorbox}[colback=white]
  16004. \small
  16005. {\if\edition\racketEd
  16006. \[
  16007. \begin{array}{l}
  16008. \gray{\LintASTRacket{}} \\ \hline
  16009. \gray{\LvarASTRacket{}} \\ \hline
  16010. \gray{\LifASTRacket{}} \\ \hline
  16011. \gray{\LwhileASTRacket} \\ \hline
  16012. \gray{\LtupASTRacket} \\ \hline
  16013. \LdynASTRacket \\
  16014. \begin{array}{lcl}
  16015. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16016. \end{array}
  16017. \end{array}
  16018. \]
  16019. \fi}
  16020. {\if\edition\pythonEd
  16021. \[
  16022. \begin{array}{rcl}
  16023. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  16024. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  16025. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  16026. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  16027. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  16028. &\MID & \code{Is()} \\
  16029. \itm{bool} &::=& \code{True} \MID \code{False} \\
  16030. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  16031. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  16032. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  16033. \MID \VAR{\Var{}} \\
  16034. &\MID& \BOOL{\itm{bool}}
  16035. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  16036. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  16037. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  16038. &\MID& \LEN{\Exp} \\
  16039. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  16040. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  16041. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  16042. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  16043. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  16044. &\MID& \RETURN{\Exp} \\
  16045. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  16046. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  16047. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16048. \end{array}
  16049. \]
  16050. \fi}
  16051. \end{tcolorbox}
  16052. \caption{The abstract syntax of \LangDyn{}.}
  16053. \label{fig:r7-syntax}
  16054. \end{figure}
  16055. The definitions of the concrete and abstract syntax of \LangDyn{} are
  16056. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  16057. %
  16058. There is no type checker for \LangDyn{} because it checks types only
  16059. at runtime.
  16060. The definitional interpreter for \LangDyn{} is presented in
  16061. \racket{figure~\ref{fig:interp-Ldyn}}
  16062. \python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}},
  16063. and definitions of its auxiliary functions are shown in
  16064. figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  16065. \INT{n}. Instead of simply returning the integer \code{n} (as
  16066. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  16067. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  16068. value} that combines an underlying value with a tag that identifies
  16069. what kind of value it is. We define the following \racket{struct}\python{class}
  16070. to represent tagged values:
  16071. %
  16072. {\if\edition\racketEd
  16073. \begin{lstlisting}
  16074. (struct Tagged (value tag) #:transparent)
  16075. \end{lstlisting}
  16076. \fi}
  16077. {\if\edition\pythonEd
  16078. \begin{minipage}{\textwidth}
  16079. \begin{lstlisting}
  16080. @dataclass(eq=True)
  16081. class Tagged(Value):
  16082. value : Value
  16083. tag : str
  16084. def __str__(self):
  16085. return str(self.value)
  16086. \end{lstlisting}
  16087. \end{minipage}
  16088. \fi}
  16089. %
  16090. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  16091. \code{Vector}, and \code{Procedure}.}
  16092. %
  16093. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  16094. \code{'tuple'}, and \code{'function'}.}
  16095. %
  16096. Tags are closely related to types but do not always capture all the
  16097. information that a type does.
  16098. %
  16099. \racket{For example, a vector of type \code{(Vector Any Any)} is
  16100. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  16101. Any)} is tagged with \code{Procedure}.}
  16102. %
  16103. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  16104. is tagged with \code{'tuple'} and a function of type
  16105. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  16106. is tagged with \code{'function'}.}
  16107. Next consider the match case for accessing the element of a tuple.
  16108. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  16109. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  16110. argument is a tuple and the second is an integer.
  16111. \racket{
  16112. If they are not, a \code{trapped-error} is raised. Recall from
  16113. section~\ref{sec:interp_Lint} that when a definition interpreter
  16114. raises a \code{trapped-error} error, the compiled code must also
  16115. signal an error by exiting with return code \code{255}. A
  16116. \code{trapped-error} is also raised if the index is not less than the
  16117. length of the vector.
  16118. }
  16119. %
  16120. \python{If they are not, an exception is raised. The compiled code
  16121. must also signal an error by exiting with return code \code{255}. A
  16122. exception is also raised if the index is not less than the length of the
  16123. tuple or if it is negative.}
  16124. \begin{figure}[tbp]
  16125. \begin{tcolorbox}[colback=white]
  16126. {\if\edition\racketEd
  16127. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16128. (define ((interp-Ldyn-exp env) ast)
  16129. (define recur (interp-Ldyn-exp env))
  16130. (match ast
  16131. [(Var x) (dict-ref env x)]
  16132. [(Int n) (Tagged n 'Integer)]
  16133. [(Bool b) (Tagged b 'Boolean)]
  16134. [(Lambda xs rt body)
  16135. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  16136. [(Prim 'vector es)
  16137. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  16138. [(Prim 'vector-ref (list e1 e2))
  16139. (define vec (recur e1)) (define i (recur e2))
  16140. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16141. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16142. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16143. (vector-ref (Tagged-value vec) (Tagged-value i))]
  16144. [(Prim 'vector-set! (list e1 e2 e3))
  16145. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  16146. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  16147. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  16148. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  16149. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  16150. (Tagged (void) 'Void)]
  16151. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  16152. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  16153. [(Prim 'or (list e1 e2))
  16154. (define v1 (recur e1))
  16155. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  16156. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  16157. [(Prim op (list e1))
  16158. #:when (set-member? type-predicates op)
  16159. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  16160. [(Prim op es)
  16161. (define args (map recur es))
  16162. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  16163. (unless (for/or ([expected-tags (op-tags op)])
  16164. (equal? expected-tags tags))
  16165. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  16166. (tag-value
  16167. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  16168. [(If q t f)
  16169. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  16170. [(Apply f es)
  16171. (define new-f (recur f)) (define args (map recur es))
  16172. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  16173. (match f-val
  16174. [`(function ,xs ,body ,lam-env)
  16175. (unless (eq? (length xs) (length args))
  16176. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  16177. (define new-env (append (map cons xs args) lam-env))
  16178. ((interp-Ldyn-exp new-env) body)]
  16179. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  16180. \end{lstlisting}
  16181. \fi}
  16182. {\if\edition\pythonEd
  16183. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16184. class InterpLdyn(InterpLlambda):
  16185. def interp_exp(self, e, env):
  16186. match e:
  16187. case Constant(n):
  16188. return self.tag(super().interp_exp(e, env))
  16189. case Tuple(es, Load()):
  16190. return self.tag(super().interp_exp(e, env))
  16191. case Lambda(params, body):
  16192. return self.tag(super().interp_exp(e, env))
  16193. case Call(Name('input_int'), []):
  16194. return self.tag(super().interp_exp(e, env))
  16195. case BinOp(left, Add(), right):
  16196. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16197. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  16198. case BinOp(left, Sub(), right):
  16199. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  16200. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  16201. case UnaryOp(USub(), e1):
  16202. v = self.interp_exp(e1, env)
  16203. return self.tag(- self.untag(v, 'int', e))
  16204. case IfExp(test, body, orelse):
  16205. v = self.interp_exp(test, env)
  16206. if self.untag(v, 'bool', e):
  16207. return self.interp_exp(body, env)
  16208. else:
  16209. return self.interp_exp(orelse, env)
  16210. case UnaryOp(Not(), e1):
  16211. v = self.interp_exp(e1, env)
  16212. return self.tag(not self.untag(v, 'bool', e))
  16213. case BoolOp(And(), values):
  16214. left = values[0]; right = values[1]
  16215. l = self.interp_exp(left, env)
  16216. if self.untag(l, 'bool', e):
  16217. return self.interp_exp(right, env)
  16218. else:
  16219. return self.tag(False)
  16220. case BoolOp(Or(), values):
  16221. left = values[0]; right = values[1]
  16222. l = self.interp_exp(left, env)
  16223. if self.untag(l, 'bool', e):
  16224. return self.tag(True)
  16225. else:
  16226. return self.interp_exp(right, env)
  16227. case Compare(left, [cmp], [right]):
  16228. l = self.interp_exp(left, env)
  16229. r = self.interp_exp(right, env)
  16230. if l.tag == r.tag:
  16231. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  16232. else:
  16233. raise Exception('interp Compare unexpected '
  16234. + repr(l) + ' ' + repr(r))
  16235. case Subscript(tup, index, Load()):
  16236. t = self.interp_exp(tup, env)
  16237. n = self.interp_exp(index, env)
  16238. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  16239. case Call(Name('len'), [tup]):
  16240. t = self.interp_exp(tup, env)
  16241. return self.tag(len(self.untag(t, 'tuple', e)))
  16242. case _:
  16243. return self.tag(super().interp_exp(e, env))
  16244. \end{lstlisting}
  16245. \fi}
  16246. \end{tcolorbox}
  16247. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  16248. \label{fig:interp-Ldyn}
  16249. \end{figure}
  16250. {\if\edition\pythonEd
  16251. \begin{figure}[tbp]
  16252. \begin{tcolorbox}[colback=white]
  16253. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16254. class InterpLdyn(InterpLlambda):
  16255. def interp_stmts(self, ss, env):
  16256. if len(ss) == 0:
  16257. return
  16258. match ss[0]:
  16259. case If(test, body, orelse):
  16260. v = self.interp_exp(test, env)
  16261. if self.untag(v, 'bool', ss[0]):
  16262. return self.interp_stmts(body + ss[1:], env)
  16263. else:
  16264. return self.interp_stmts(orelse + ss[1:], env)
  16265. case While(test, body, []):
  16266. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  16267. self.interp_stmts(body, env)
  16268. return self.interp_stmts(ss[1:], env)
  16269. case Assign([Subscript(tup, index)], value):
  16270. tup = self.interp_exp(tup, env)
  16271. index = self.interp_exp(index, env)
  16272. tup_v = self.untag(tup, 'tuple', ss[0])
  16273. index_v = self.untag(index, 'int', ss[0])
  16274. tup_v[index_v] = self.interp_exp(value, env)
  16275. return self.interp_stmts(ss[1:], env)
  16276. case FunctionDef(name, params, bod, dl, returns, comment):
  16277. ps = [x for (x,t) in params]
  16278. env[name] = self.tag(Function(name, ps, bod, env))
  16279. return self.interp_stmts(ss[1:], env)
  16280. case _:
  16281. return super().interp_stmts(ss, env)
  16282. \end{lstlisting}
  16283. \end{tcolorbox}
  16284. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  16285. \label{fig:interp-Ldyn-2}
  16286. \end{figure}
  16287. \fi}
  16288. \begin{figure}[tbp]
  16289. \begin{tcolorbox}[colback=white]
  16290. {\if\edition\racketEd
  16291. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16292. (define (interp-op op)
  16293. (match op
  16294. ['+ fx+]
  16295. ['- fx-]
  16296. ['read read-fixnum]
  16297. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  16298. ['< (lambda (v1 v2)
  16299. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  16300. ['<= (lambda (v1 v2)
  16301. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  16302. ['> (lambda (v1 v2)
  16303. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  16304. ['>= (lambda (v1 v2)
  16305. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  16306. ['boolean? boolean?]
  16307. ['integer? fixnum?]
  16308. ['void? void?]
  16309. ['vector? vector?]
  16310. ['vector-length vector-length]
  16311. ['procedure? (match-lambda
  16312. [`(functions ,xs ,body ,env) #t] [else #f])]
  16313. [else (error 'interp-op "unknown operator" op)]))
  16314. (define (op-tags op)
  16315. (match op
  16316. ['+ '((Integer Integer))]
  16317. ['- '((Integer Integer) (Integer))]
  16318. ['read '(())]
  16319. ['not '((Boolean))]
  16320. ['< '((Integer Integer))]
  16321. ['<= '((Integer Integer))]
  16322. ['> '((Integer Integer))]
  16323. ['>= '((Integer Integer))]
  16324. ['vector-length '((Vector))]))
  16325. (define type-predicates
  16326. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16327. (define (tag-value v)
  16328. (cond [(boolean? v) (Tagged v 'Boolean)]
  16329. [(fixnum? v) (Tagged v 'Integer)]
  16330. [(procedure? v) (Tagged v 'Procedure)]
  16331. [(vector? v) (Tagged v 'Vector)]
  16332. [(void? v) (Tagged v 'Void)]
  16333. [else (error 'tag-value "unidentified value ~a" v)]))
  16334. (define (check-tag val expected ast)
  16335. (define tag (Tagged-tag val))
  16336. (unless (eq? tag expected)
  16337. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  16338. \end{lstlisting}
  16339. \fi}
  16340. {\if\edition\pythonEd
  16341. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16342. class InterpLdyn(InterpLlambda):
  16343. def tag(self, v):
  16344. if v is True or v is False:
  16345. return Tagged(v, 'bool')
  16346. elif isinstance(v, int):
  16347. return Tagged(v, 'int')
  16348. elif isinstance(v, Function):
  16349. return Tagged(v, 'function')
  16350. elif isinstance(v, tuple):
  16351. return Tagged(v, 'tuple')
  16352. elif isinstance(v, type(None)):
  16353. return Tagged(v, 'none')
  16354. else:
  16355. raise Exception('tag: unexpected ' + repr(v))
  16356. def untag(self, v, expected_tag, ast):
  16357. match v:
  16358. case Tagged(val, tag) if tag == expected_tag:
  16359. return val
  16360. case _:
  16361. raise Exception('expected Tagged value with '
  16362. + expected_tag + ', not ' + ' ' + repr(v))
  16363. def apply_fun(self, fun, args, e):
  16364. f = self.untag(fun, 'function', e)
  16365. return super().apply_fun(f, args, e)
  16366. \end{lstlisting}
  16367. \fi}
  16368. \end{tcolorbox}
  16369. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  16370. \label{fig:interp-Ldyn-aux}
  16371. \end{figure}
  16372. \clearpage
  16373. \section{Representation of Tagged Values}
  16374. The interpreter for \LangDyn{} introduced a new kind of value: the
  16375. tagged value. To compile \LangDyn{} to x86 we must decide how to
  16376. represent tagged values at the bit level. Because almost every
  16377. operation in \LangDyn{} involves manipulating tagged values, the
  16378. representation must be efficient. Recall that all our values are 64
  16379. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  16380. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  16381. $011$ for procedures, and $101$ for the void value\python{,
  16382. \key{None}}. We define the following auxiliary function for mapping
  16383. types to tag codes:
  16384. %
  16385. {\if\edition\racketEd
  16386. \begin{align*}
  16387. \itm{tagof}(\key{Integer}) &= 001 \\
  16388. \itm{tagof}(\key{Boolean}) &= 100 \\
  16389. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  16390. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  16391. \itm{tagof}(\key{Void}) &= 101
  16392. \end{align*}
  16393. \fi}
  16394. {\if\edition\pythonEd
  16395. \begin{align*}
  16396. \itm{tagof}(\key{IntType()}) &= 001 \\
  16397. \itm{tagof}(\key{BoolType()}) &= 100 \\
  16398. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  16399. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  16400. \itm{tagof}(\key{type(None)}) &= 101
  16401. \end{align*}
  16402. \fi}
  16403. %
  16404. This stealing of 3 bits comes at some price: integers are now restricted
  16405. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  16406. affect tuples and procedures because those values are addresses, and
  16407. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  16408. they are always $000$. Thus, we do not lose information by overwriting
  16409. the rightmost 3 bits with the tag, and we can simply zero out the tag
  16410. to recover the original address.
  16411. To make tagged values into first-class entities, we can give them a
  16412. type called \racket{\code{Any}}\python{\code{AnyType()}} and define
  16413. operations such as \code{Inject} and \code{Project} for creating and
  16414. using them, yielding the statically typed \LangAny{} intermediate
  16415. language. We describe how to compile \LangDyn{} to \LangAny{} in
  16416. section~\ref{sec:compile-r7}; in th next section we describe the
  16417. \LangAny{} language in greater detail.
  16418. \section{The \LangAny{} Language}
  16419. \label{sec:Rany-lang}
  16420. \newcommand{\LanyASTRacket}{
  16421. \begin{array}{lcl}
  16422. \Type &::= & \ANYTY \\
  16423. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  16424. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  16425. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  16426. \itm{op} &::= & \code{any-vector-length}
  16427. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  16428. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  16429. \MID \code{procedure?} \MID \code{void?} \\
  16430. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  16431. \end{array}
  16432. }
  16433. \newcommand{\LanyASTPython}{
  16434. \begin{array}{lcl}
  16435. \Type &::= & \key{AnyType()} \\
  16436. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  16437. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  16438. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  16439. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  16440. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\Exp\RS}\\
  16441. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS} \\
  16442. &\MID& \CALL{\VAR{\key{'arity'}}}{\LS\Exp\RS} \\
  16443. &\MID& \CALL{\VAR{\key{'make\_any'}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  16444. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  16445. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  16446. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  16447. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  16448. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  16449. \end{array}
  16450. }
  16451. \begin{figure}[tp]
  16452. \centering
  16453. \begin{tcolorbox}[colback=white]
  16454. \small
  16455. {\if\edition\racketEd
  16456. \[
  16457. \begin{array}{l}
  16458. \gray{\LintOpAST} \\ \hline
  16459. \gray{\LvarASTRacket{}} \\ \hline
  16460. \gray{\LifASTRacket{}} \\ \hline
  16461. \gray{\LwhileASTRacket{}} \\ \hline
  16462. \gray{\LtupASTRacket{}} \\ \hline
  16463. \gray{\LfunASTRacket} \\ \hline
  16464. \gray{\LlambdaASTRacket} \\ \hline
  16465. \LanyASTRacket \\
  16466. \begin{array}{lcl}
  16467. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16468. \end{array}
  16469. \end{array}
  16470. \]
  16471. \fi}
  16472. {\if\edition\pythonEd
  16473. \[
  16474. \begin{array}{l}
  16475. \gray{\LintASTPython} \\ \hline
  16476. \gray{\LvarASTPython{}} \\ \hline
  16477. \gray{\LifASTPython{}} \\ \hline
  16478. \gray{\LwhileASTPython{}} \\ \hline
  16479. \gray{\LtupASTPython{}} \\ \hline
  16480. \gray{\LfunASTPython} \\ \hline
  16481. \gray{\LlambdaASTPython} \\ \hline
  16482. \LanyASTPython \\
  16483. \begin{array}{lcl}
  16484. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  16485. \end{array}
  16486. \end{array}
  16487. \]
  16488. \fi}
  16489. \end{tcolorbox}
  16490. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  16491. \label{fig:Lany-syntax}
  16492. \end{figure}
  16493. The definition of the abstract syntax of \LangAny{} is given in
  16494. figure~\ref{fig:Lany-syntax}.
  16495. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  16496. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  16497. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  16498. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  16499. converts the tagged value produced by expression $e$ into a value of
  16500. type $T$ or halts the program if the type tag does not match $T$.
  16501. %
  16502. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  16503. restricted to be a flat type (the nonterminal $\FType$) which
  16504. simplifies the implementation and complies with the needs for
  16505. compiling \LangDyn{}.
  16506. The \racket{\code{any-vector}} operators
  16507. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  16508. operations so that they can be applied to a value of type
  16509. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  16510. tuple operations in that the index is not restricted to a literal
  16511. integer in the grammar but is allowed to be any expression.
  16512. \racket{The type predicates such as
  16513. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  16514. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  16515. the predicate and return {\FALSE} otherwise.}
  16516. The type checker for \LangAny{} is shown in
  16517. figure~\ref{fig:type-check-Lany}
  16518. %
  16519. \racket{ and uses the auxiliary functions presented in
  16520. figure~\ref{fig:type-check-Lany-aux}}.
  16521. %
  16522. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  16523. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  16524. \begin{figure}[btp]
  16525. \begin{tcolorbox}[colback=white]
  16526. {\if\edition\racketEd
  16527. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16528. (define type-check-Lany-class
  16529. (class type-check-Llambda-class
  16530. (super-new)
  16531. (inherit check-type-equal?)
  16532. (define/override (type-check-exp env)
  16533. (lambda (e)
  16534. (define recur (type-check-exp env))
  16535. (match e
  16536. [(Inject e1 ty)
  16537. (unless (flat-ty? ty)
  16538. (error 'type-check "may only inject from flat type, not ~a" ty))
  16539. (define-values (new-e1 e-ty) (recur e1))
  16540. (check-type-equal? e-ty ty e)
  16541. (values (Inject new-e1 ty) 'Any)]
  16542. [(Project e1 ty)
  16543. (unless (flat-ty? ty)
  16544. (error 'type-check "may only project to flat type, not ~a" ty))
  16545. (define-values (new-e1 e-ty) (recur e1))
  16546. (check-type-equal? e-ty 'Any e)
  16547. (values (Project new-e1 ty) ty)]
  16548. [(Prim 'any-vector-length (list e1))
  16549. (define-values (e1^ t1) (recur e1))
  16550. (check-type-equal? t1 'Any e)
  16551. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  16552. [(Prim 'any-vector-ref (list e1 e2))
  16553. (define-values (e1^ t1) (recur e1))
  16554. (define-values (e2^ t2) (recur e2))
  16555. (check-type-equal? t1 'Any e)
  16556. (check-type-equal? t2 'Integer e)
  16557. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  16558. [(Prim 'any-vector-set! (list e1 e2 e3))
  16559. (define-values (e1^ t1) (recur e1))
  16560. (define-values (e2^ t2) (recur e2))
  16561. (define-values (e3^ t3) (recur e3))
  16562. (check-type-equal? t1 'Any e)
  16563. (check-type-equal? t2 'Integer e)
  16564. (check-type-equal? t3 'Any e)
  16565. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  16566. [(Prim pred (list e1))
  16567. #:when (set-member? (type-predicates) pred)
  16568. (define-values (new-e1 e-ty) (recur e1))
  16569. (check-type-equal? e-ty 'Any e)
  16570. (values (Prim pred (list new-e1)) 'Boolean)]
  16571. [(Prim 'eq? (list arg1 arg2))
  16572. (define-values (e1 t1) (recur arg1))
  16573. (define-values (e2 t2) (recur arg2))
  16574. (match* (t1 t2)
  16575. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  16576. [(other wise) (check-type-equal? t1 t2 e)])
  16577. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  16578. [else ((super type-check-exp env) e)])))
  16579. ))
  16580. \end{lstlisting}
  16581. \fi}
  16582. {\if\edition\pythonEd
  16583. \begin{lstlisting}
  16584. class TypeCheckLany(TypeCheckLlambda):
  16585. def type_check_exp(self, e, env):
  16586. match e:
  16587. case Inject(value, typ):
  16588. self.check_exp(value, typ, env)
  16589. return AnyType()
  16590. case Project(value, typ):
  16591. self.check_exp(value, AnyType(), env)
  16592. return typ
  16593. case Call(Name('any_tuple_load'), [tup, index]):
  16594. self.check_exp(tup, AnyType(), env)
  16595. self.check_exp(index, IntType(), env)
  16596. return AnyType()
  16597. case Call(Name('any_len'), [tup]):
  16598. self.check_exp(tup, AnyType(), env)
  16599. return IntType()
  16600. case Call(Name('arity'), [fun]):
  16601. ty = self.type_check_exp(fun, env)
  16602. match ty:
  16603. case FunctionType(ps, rt):
  16604. return IntType()
  16605. case TupleType([FunctionType(ps,rs)]):
  16606. return IntType()
  16607. case _:
  16608. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  16609. case Call(Name('make_any'), [value, tag]):
  16610. self.type_check_exp(value, env)
  16611. self.check_exp(tag, IntType(), env)
  16612. return AnyType()
  16613. case AnnLambda(params, returns, body):
  16614. new_env = {x:t for (x,t) in env.items()}
  16615. for (x,t) in params:
  16616. new_env[x] = t
  16617. return_t = self.type_check_exp(body, new_env)
  16618. self.check_type_equal(returns, return_t, e)
  16619. return FunctionType([t for (x,t) in params], return_t)
  16620. case _:
  16621. return super().type_check_exp(e, env)
  16622. \end{lstlisting}
  16623. \fi}
  16624. \end{tcolorbox}
  16625. \caption{Type checker for the \LangAny{} language.}
  16626. \label{fig:type-check-Lany}
  16627. \end{figure}
  16628. {\if\edition\racketEd
  16629. \begin{figure}[tbp]
  16630. \begin{tcolorbox}[colback=white]
  16631. \begin{lstlisting}
  16632. (define/override (operator-types)
  16633. (append
  16634. '((integer? . ((Any) . Boolean))
  16635. (vector? . ((Any) . Boolean))
  16636. (procedure? . ((Any) . Boolean))
  16637. (void? . ((Any) . Boolean)))
  16638. (super operator-types)))
  16639. (define/public (type-predicates)
  16640. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  16641. (define/public (flat-ty? ty)
  16642. (match ty
  16643. [(or `Integer `Boolean `Void) #t]
  16644. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  16645. [`(,ts ... -> ,rt)
  16646. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  16647. [else #f]))
  16648. \end{lstlisting}
  16649. \end{tcolorbox}
  16650. \caption{Auxiliary methods for type checking \LangAny{}.}
  16651. \label{fig:type-check-Lany-aux}
  16652. \end{figure}
  16653. \fi}
  16654. \begin{figure}[btp]
  16655. \begin{tcolorbox}[colback=white]
  16656. {\if\edition\racketEd
  16657. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16658. (define interp-Lany-class
  16659. (class interp-Llambda-class
  16660. (super-new)
  16661. (define/override (interp-op op)
  16662. (match op
  16663. ['boolean? (match-lambda
  16664. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  16665. [else #f])]
  16666. ['integer? (match-lambda
  16667. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  16668. [else #f])]
  16669. ['vector? (match-lambda
  16670. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  16671. [else #f])]
  16672. ['procedure? (match-lambda
  16673. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  16674. [else #f])]
  16675. ['eq? (match-lambda*
  16676. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  16677. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  16678. [ls (apply (super interp-op op) ls)])]
  16679. ['any-vector-ref (lambda (v i)
  16680. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  16681. ['any-vector-set! (lambda (v i a)
  16682. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  16683. ['any-vector-length (lambda (v)
  16684. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  16685. [else (super interp-op op)]))
  16686. (define/override ((interp-exp env) e)
  16687. (define recur (interp-exp env))
  16688. (match e
  16689. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  16690. [(Project e ty2) (apply-project (recur e) ty2)]
  16691. [else ((super interp-exp env) e)]))
  16692. ))
  16693. (define (interp-Lany p)
  16694. (send (new interp-Lany-class) interp-program p))
  16695. \end{lstlisting}
  16696. \fi}
  16697. {\if\edition\pythonEd
  16698. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16699. class InterpLany(InterpLlambda):
  16700. def interp_exp(self, e, env):
  16701. match e:
  16702. case Inject(value, typ):
  16703. v = self.interp_exp(value, env)
  16704. return Tagged(v, self.type_to_tag(typ))
  16705. case Project(value, typ):
  16706. v = self.interp_exp(value, env)
  16707. match v:
  16708. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  16709. return val
  16710. case _:
  16711. raise Exception('interp project to ' + repr(typ)
  16712. + ' unexpected ' + repr(v))
  16713. case Call(Name('any_tuple_load'), [tup, index]):
  16714. tv = self.interp_exp(tup, env)
  16715. n = self.interp_exp(index, env)
  16716. match tv:
  16717. case Tagged(v, tag):
  16718. return v[n]
  16719. case _:
  16720. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  16721. case Call(Name('any_len'), [value]):
  16722. v = self.interp_exp(value, env)
  16723. match v:
  16724. case Tagged(value, tag):
  16725. return len(value)
  16726. case _:
  16727. raise Exception('interp any_len unexpected ' + repr(v))
  16728. case Call(Name('arity'), [fun]):
  16729. f = self.interp_exp(fun, env)
  16730. return self.arity(f)
  16731. case _:
  16732. return super().interp_exp(e, env)
  16733. \end{lstlisting}
  16734. \fi}
  16735. \end{tcolorbox}
  16736. \caption{Interpreter for \LangAny{}.}
  16737. \label{fig:interp-Lany}
  16738. \end{figure}
  16739. \begin{figure}[tbp]
  16740. \begin{tcolorbox}[colback=white]
  16741. {\if\edition\racketEd
  16742. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16743. (define/public (apply-inject v tg) (Tagged v tg))
  16744. (define/public (apply-project v ty2)
  16745. (define tag2 (any-tag ty2))
  16746. (match v
  16747. [(Tagged v1 tag1)
  16748. (cond
  16749. [(eq? tag1 tag2)
  16750. (match ty2
  16751. [`(Vector ,ts ...)
  16752. (define l1 ((interp-op 'vector-length) v1))
  16753. (cond
  16754. [(eq? l1 (length ts)) v1]
  16755. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16756. l1 (length ts))])]
  16757. [`(,ts ... -> ,rt)
  16758. (match v1
  16759. [`(function ,xs ,body ,env)
  16760. (cond [(eq? (length xs) (length ts)) v1]
  16761. [else
  16762. (error 'apply-project "arity mismatch ~a != ~a"
  16763. (length xs) (length ts))])]
  16764. [else (error 'apply-project "expected function not ~a" v1)])]
  16765. [else v1])]
  16766. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16767. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16768. \end{lstlisting}
  16769. \fi}
  16770. {\if\edition\pythonEd
  16771. \begin{lstlisting}
  16772. class InterpLany(InterpLlambda):
  16773. def type_to_tag(self, typ):
  16774. match typ:
  16775. case FunctionType(params, rt):
  16776. return 'function'
  16777. case TupleType(fields):
  16778. return 'tuple'
  16779. case t if t == int:
  16780. return 'int'
  16781. case t if t == bool:
  16782. return 'bool'
  16783. case IntType():
  16784. return 'int'
  16785. case BoolType():
  16786. return 'int'
  16787. case _:
  16788. raise Exception('type_to_tag unexpected ' + repr(typ))
  16789. def arity(self, v):
  16790. match v:
  16791. case Function(name, params, body, env):
  16792. return len(params)
  16793. case ClosureTuple(args, arity):
  16794. return arity
  16795. case _:
  16796. raise Exception('Lany arity unexpected ' + repr(v))
  16797. \end{lstlisting}
  16798. \fi}
  16799. \end{tcolorbox}
  16800. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16801. \label{fig:interp-Lany-aux}
  16802. \end{figure}
  16803. \clearpage
  16804. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16805. \label{sec:compile-r7}
  16806. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16807. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16808. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16809. is that given any subexpression $e$ in the \LangDyn{} program, the
  16810. pass will produce an expression $e'$ in \LangAny{} that has type
  16811. \ANYTY{}. For example, the first row in
  16812. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16813. \TRUE{}, which must be injected to produce an expression of type
  16814. \ANYTY{}.
  16815. %
  16816. The compilation of addition is shown in the second row of
  16817. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  16818. representative of many primitive operations: the arguments have type
  16819. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  16820. be performed.
  16821. The compilation of \key{lambda} (third row of
  16822. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16823. produce type annotations: we simply use \ANYTY{}.
  16824. %
  16825. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16826. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16827. this pass has to account for some differences in behavior between
  16828. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16829. permissive than \LangAny{} regarding what kind of values can be used
  16830. in various places. For example, the condition of an \key{if} does
  16831. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16832. of the same type (in that case the result is \code{\#f}).}
  16833. \begin{figure}[btp]
  16834. \centering
  16835. \begin{tcolorbox}[colback=white]
  16836. {\if\edition\racketEd
  16837. \begin{tabular}{lll}
  16838. \begin{minipage}{0.27\textwidth}
  16839. \begin{lstlisting}
  16840. #t
  16841. \end{lstlisting}
  16842. \end{minipage}
  16843. &
  16844. $\Rightarrow$
  16845. &
  16846. \begin{minipage}{0.65\textwidth}
  16847. \begin{lstlisting}
  16848. (inject #t Boolean)
  16849. \end{lstlisting}
  16850. \end{minipage}
  16851. \\[2ex]\hline
  16852. \begin{minipage}{0.27\textwidth}
  16853. \begin{lstlisting}
  16854. (+ |$e_1$| |$e_2$|)
  16855. \end{lstlisting}
  16856. \end{minipage}
  16857. &
  16858. $\Rightarrow$
  16859. &
  16860. \begin{minipage}{0.65\textwidth}
  16861. \begin{lstlisting}
  16862. (inject
  16863. (+ (project |$e'_1$| Integer)
  16864. (project |$e'_2$| Integer))
  16865. Integer)
  16866. \end{lstlisting}
  16867. \end{minipage}
  16868. \\[2ex]\hline
  16869. \begin{minipage}{0.27\textwidth}
  16870. \begin{lstlisting}
  16871. (lambda (|$x_1 \ldots$|) |$e$|)
  16872. \end{lstlisting}
  16873. \end{minipage}
  16874. &
  16875. $\Rightarrow$
  16876. &
  16877. \begin{minipage}{0.65\textwidth}
  16878. \begin{lstlisting}
  16879. (inject
  16880. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  16881. (Any|$\ldots$|Any -> Any))
  16882. \end{lstlisting}
  16883. \end{minipage}
  16884. \\[2ex]\hline
  16885. \begin{minipage}{0.27\textwidth}
  16886. \begin{lstlisting}
  16887. (|$e_0$| |$e_1 \ldots e_n$|)
  16888. \end{lstlisting}
  16889. \end{minipage}
  16890. &
  16891. $\Rightarrow$
  16892. &
  16893. \begin{minipage}{0.65\textwidth}
  16894. \begin{lstlisting}
  16895. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16896. \end{lstlisting}
  16897. \end{minipage}
  16898. \\[2ex]\hline
  16899. \begin{minipage}{0.27\textwidth}
  16900. \begin{lstlisting}
  16901. (vector-ref |$e_1$| |$e_2$|)
  16902. \end{lstlisting}
  16903. \end{minipage}
  16904. &
  16905. $\Rightarrow$
  16906. &
  16907. \begin{minipage}{0.65\textwidth}
  16908. \begin{lstlisting}
  16909. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  16910. \end{lstlisting}
  16911. \end{minipage}
  16912. \\[2ex]\hline
  16913. \begin{minipage}{0.27\textwidth}
  16914. \begin{lstlisting}
  16915. (if |$e_1$| |$e_2$| |$e_3$|)
  16916. \end{lstlisting}
  16917. \end{minipage}
  16918. &
  16919. $\Rightarrow$
  16920. &
  16921. \begin{minipage}{0.65\textwidth}
  16922. \begin{lstlisting}
  16923. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16924. \end{lstlisting}
  16925. \end{minipage}
  16926. \\[2ex]\hline
  16927. \begin{minipage}{0.27\textwidth}
  16928. \begin{lstlisting}
  16929. (eq? |$e_1$| |$e_2$|)
  16930. \end{lstlisting}
  16931. \end{minipage}
  16932. &
  16933. $\Rightarrow$
  16934. &
  16935. \begin{minipage}{0.65\textwidth}
  16936. \begin{lstlisting}
  16937. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16938. \end{lstlisting}
  16939. \end{minipage}
  16940. \\[2ex]\hline
  16941. \begin{minipage}{0.27\textwidth}
  16942. \begin{lstlisting}
  16943. (not |$e_1$|)
  16944. \end{lstlisting}
  16945. \end{minipage}
  16946. &
  16947. $\Rightarrow$
  16948. &
  16949. \begin{minipage}{0.65\textwidth}
  16950. \begin{lstlisting}
  16951. (if (eq? |$e'_1$| (inject #f Boolean))
  16952. (inject #t Boolean) (inject #f Boolean))
  16953. \end{lstlisting}
  16954. \end{minipage}
  16955. \end{tabular}
  16956. \fi}
  16957. {\if\edition\pythonEd
  16958. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  16959. \begin{minipage}{0.23\textwidth}
  16960. \begin{lstlisting}
  16961. True
  16962. \end{lstlisting}
  16963. \end{minipage}
  16964. &
  16965. $\Rightarrow$
  16966. &
  16967. \begin{minipage}{0.7\textwidth}
  16968. \begin{lstlisting}
  16969. Inject(True, BoolType())
  16970. \end{lstlisting}
  16971. \end{minipage}
  16972. \\[2ex]\hline
  16973. \begin{minipage}{0.23\textwidth}
  16974. \begin{lstlisting}
  16975. |$e_1$| + |$e_2$|
  16976. \end{lstlisting}
  16977. \end{minipage}
  16978. &
  16979. $\Rightarrow$
  16980. &
  16981. \begin{minipage}{0.7\textwidth}
  16982. \begin{lstlisting}
  16983. Inject(Project(|$e'_1$|, IntType())
  16984. + Project(|$e'_2$|, IntType()),
  16985. IntType())
  16986. \end{lstlisting}
  16987. \end{minipage}
  16988. \\[2ex]\hline
  16989. \begin{minipage}{0.23\textwidth}
  16990. \begin{lstlisting}
  16991. lambda |$x_1 \ldots$|: |$e$|
  16992. \end{lstlisting}
  16993. \end{minipage}
  16994. &
  16995. $\Rightarrow$
  16996. &
  16997. \begin{minipage}{0.7\textwidth}
  16998. \begin{lstlisting}
  16999. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17000. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17001. \end{lstlisting}
  17002. \end{minipage}
  17003. \\[2ex]\hline
  17004. \begin{minipage}{0.23\textwidth}
  17005. \begin{lstlisting}
  17006. |$e_0$|(|$e_1 \ldots e_n$|)
  17007. \end{lstlisting}
  17008. \end{minipage}
  17009. &
  17010. $\Rightarrow$
  17011. &
  17012. \begin{minipage}{0.7\textwidth}
  17013. \begin{lstlisting}
  17014. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  17015. AnyType())), |$e'_1, \ldots, e'_n$|)
  17016. \end{lstlisting}
  17017. \end{minipage}
  17018. \\[2ex]\hline
  17019. \begin{minipage}{0.23\textwidth}
  17020. \begin{lstlisting}
  17021. |$e_1$|[|$e_2$|]
  17022. \end{lstlisting}
  17023. \end{minipage}
  17024. &
  17025. $\Rightarrow$
  17026. &
  17027. \begin{minipage}{0.7\textwidth}
  17028. \begin{lstlisting}
  17029. Call(Name('any_tuple_load'),
  17030. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  17031. \end{lstlisting}
  17032. \end{minipage}
  17033. %% \begin{minipage}{0.23\textwidth}
  17034. %% \begin{lstlisting}
  17035. %% |$e_2$| if |$e_1$| else |$e_3$|
  17036. %% \end{lstlisting}
  17037. %% \end{minipage}
  17038. %% &
  17039. %% $\Rightarrow$
  17040. %% &
  17041. %% \begin{minipage}{0.7\textwidth}
  17042. %% \begin{lstlisting}
  17043. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17044. %% \end{lstlisting}
  17045. %% \end{minipage}
  17046. %% \\[2ex]\hline
  17047. %% \begin{minipage}{0.23\textwidth}
  17048. %% \begin{lstlisting}
  17049. %% (eq? |$e_1$| |$e_2$|)
  17050. %% \end{lstlisting}
  17051. %% \end{minipage}
  17052. %% &
  17053. %% $\Rightarrow$
  17054. %% &
  17055. %% \begin{minipage}{0.7\textwidth}
  17056. %% \begin{lstlisting}
  17057. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17058. %% \end{lstlisting}
  17059. %% \end{minipage}
  17060. %% \\[2ex]\hline
  17061. %% \begin{minipage}{0.23\textwidth}
  17062. %% \begin{lstlisting}
  17063. %% (not |$e_1$|)
  17064. %% \end{lstlisting}
  17065. %% \end{minipage}
  17066. %% &
  17067. %% $\Rightarrow$
  17068. %% &
  17069. %% \begin{minipage}{0.7\textwidth}
  17070. %% \begin{lstlisting}
  17071. %% (if (eq? |$e'_1$| (inject #f Boolean))
  17072. %% (inject #t Boolean) (inject #f Boolean))
  17073. %% \end{lstlisting}
  17074. %% \end{minipage}
  17075. %% \\[2ex]\hline
  17076. \\\hline
  17077. \end{tabular}
  17078. \fi}
  17079. \end{tcolorbox}
  17080. \caption{Cast insertion}
  17081. \label{fig:compile-r7-Lany}
  17082. \end{figure}
  17083. \section{Reveal Casts}
  17084. \label{sec:reveal-casts-Lany}
  17085. % TODO: define R'_6
  17086. In the \code{reveal\_casts} pass, we recommend compiling
  17087. \code{Project} into a conditional expression that checks whether the
  17088. value's tag matches the target type; if it does, the value is
  17089. converted to a value of the target type by removing the tag; if it
  17090. does not, the program exits.
  17091. %
  17092. {\if\edition\racketEd
  17093. %
  17094. To perform these actions we need a new primitive operation,
  17095. \code{tag-of-any}, and a new form, \code{ValueOf}.
  17096. The \code{tag-of-any} operation retrieves the type tag from a tagged
  17097. value of type \code{Any}. The \code{ValueOf} form retrieves the
  17098. underlying value from a tagged value. The \code{ValueOf} form
  17099. includes the type for the underlying value that is used by the type
  17100. checker.
  17101. %
  17102. \fi}
  17103. %
  17104. {\if\edition\pythonEd
  17105. %
  17106. To perform these actions we need two new AST classes: \code{TagOf} and
  17107. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  17108. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  17109. the underlying value from a tagged value. The \code{ValueOf}
  17110. operation includes the type for the underlying value which is used by
  17111. the type checker.
  17112. %
  17113. \fi}
  17114. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  17115. \code{Project} can be translated as follows.
  17116. \begin{center}
  17117. \begin{minipage}{1.0\textwidth}
  17118. {\if\edition\racketEd
  17119. \begin{lstlisting}
  17120. (Project |$e$| |$\FType$|)
  17121. |$\Rightarrow$|
  17122. (Let |$\itm{tmp}$| |$e'$|
  17123. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  17124. (Int |$\itm{tagof}(\FType)$|)))
  17125. (ValueOf |$\itm{tmp}$| |$\FType$|)
  17126. (Exit)))
  17127. \end{lstlisting}
  17128. \fi}
  17129. {\if\edition\pythonEd
  17130. \begin{lstlisting}
  17131. Project(|$e$|, |$\FType$|)
  17132. |$\Rightarrow$|
  17133. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  17134. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  17135. [Constant(|$\itm{tagof}(\FType)$|)]),
  17136. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  17137. Call(Name('exit'), [])))
  17138. \end{lstlisting}
  17139. \fi}
  17140. \end{minipage}
  17141. \end{center}
  17142. If the target type of the projection is a tuple or function type, then
  17143. there is a bit more work to do. For tuples, check that the length of
  17144. the tuple type matches the length of the tuple. For functions, check
  17145. that the number of parameters in the function type matches the
  17146. function's arity.
  17147. Regarding \code{Inject}, we recommend compiling it to a slightly
  17148. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  17149. takes a tag instead of a type.
  17150. \begin{center}
  17151. \begin{minipage}{1.0\textwidth}
  17152. {\if\edition\racketEd
  17153. \begin{lstlisting}
  17154. (Inject |$e$| |$\FType$|)
  17155. |$\Rightarrow$|
  17156. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  17157. \end{lstlisting}
  17158. \fi}
  17159. {\if\edition\pythonEd
  17160. \begin{lstlisting}
  17161. Inject(|$e$|, |$\FType$|)
  17162. |$\Rightarrow$|
  17163. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  17164. \end{lstlisting}
  17165. \fi}
  17166. \end{minipage}
  17167. \end{center}
  17168. {\if\edition\pythonEd
  17169. %
  17170. The introduction of \code{make\_any} makes it difficult to use
  17171. bidirectional type checking because we no longer have an expected type
  17172. to use for type checking the expression $e'$. Thus, we run into
  17173. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  17174. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  17175. annotated lambda) whose parameters have type annotations and that
  17176. records the return type.
  17177. %
  17178. \fi}
  17179. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  17180. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  17181. translation of \code{Project}.}
  17182. {\if\edition\racketEd
  17183. The \code{any-vector-ref} and \code{any-vector-set!} operations
  17184. combine the projection action with the vector operation. Also, the
  17185. read and write operations allow arbitrary expressions for the index, so
  17186. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  17187. cannot guarantee that the index is within bounds. Thus, we insert code
  17188. to perform bounds checking at runtime. The translation for
  17189. \code{any-vector-ref} is as follows, and the other two operations are
  17190. translated in a similar way:
  17191. \begin{center}
  17192. \begin{minipage}{0.95\textwidth}
  17193. \begin{lstlisting}
  17194. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  17195. |$\Rightarrow$|
  17196. (Let |$v$| |$e'_1$|
  17197. (Let |$i$| |$e'_2$|
  17198. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  17199. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  17200. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  17201. (Exit))
  17202. (Exit))))
  17203. \end{lstlisting}
  17204. \end{minipage}
  17205. \end{center}
  17206. \fi}
  17207. %
  17208. {\if\edition\pythonEd
  17209. %
  17210. The \code{any\_tuple\_load} operation combines the projection action
  17211. with the load operation. Also, the load operation allows arbitrary
  17212. expressions for the index so the type checker for \LangAny{}
  17213. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  17214. within bounds. Thus, we insert code to perform bounds checking at
  17215. runtime. The translation for \code{any\_tuple\_load} is as follows.
  17216. \begin{lstlisting}
  17217. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  17218. |$\Rightarrow$|
  17219. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  17220. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  17221. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  17222. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  17223. Call(Name('exit'), [])),
  17224. Call(Name('exit'), [])))
  17225. \end{lstlisting}
  17226. \fi}
  17227. {\if\edition\pythonEd
  17228. \section{Assignment Conversion}
  17229. \label{sec:convert-assignments-Lany}
  17230. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17231. \code{AnnLambda} AST classes.
  17232. \section{Closure Conversion}
  17233. \label{sec:closure-conversion-Lany}
  17234. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  17235. \code{AnnLambda} AST classes.
  17236. \fi}
  17237. \section{Remove Complex Operands}
  17238. \label{sec:rco-Lany}
  17239. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  17240. expressions. The subexpression of \code{ValueOf} must be atomic.}
  17241. %
  17242. \python{The \code{ValueOf} and \code{TagOf} operations are both
  17243. complex expressions. Their subexpressions must be atomic.}
  17244. \section{Explicate Control and \LangCAny{}}
  17245. \label{sec:explicate-Lany}
  17246. The output of \code{explicate\_control} is the \LangCAny{} language,
  17247. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  17248. %
  17249. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  17250. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  17251. note that the index argument of \code{vector-ref} and
  17252. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  17253. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  17254. %
  17255. \python{
  17256. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  17257. and \code{explicate\_pred} as appropriately to handle the new expressions
  17258. in \LangCAny{}.
  17259. }
  17260. \newcommand{\CanyASTPython}{
  17261. \begin{array}{lcl}
  17262. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  17263. &\MID& \key{TagOf}\LP \Atm \RP
  17264. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  17265. &\MID& \CALL{\VAR{\key{'any\_tuple\_load\_unsafe'}}}{\LS \Atm,\Atm \RS}\\
  17266. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  17267. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  17268. \end{array}
  17269. }
  17270. \newcommand{\CanyASTRacket}{
  17271. \begin{array}{lcl}
  17272. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  17273. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  17274. &\MID& \VALUEOF{\Atm}{\FType} \\
  17275. \Tail &::= & \LP\key{Exit}\RP
  17276. \end{array}
  17277. }
  17278. \begin{figure}[tp]
  17279. \begin{tcolorbox}[colback=white]
  17280. \small
  17281. {\if\edition\racketEd
  17282. \[
  17283. \begin{array}{l}
  17284. \gray{\CvarASTRacket} \\ \hline
  17285. \gray{\CifASTRacket} \\ \hline
  17286. \gray{\CloopASTRacket} \\ \hline
  17287. \gray{\CtupASTRacket} \\ \hline
  17288. \gray{\CfunASTRacket} \\ \hline
  17289. \gray{\ClambdaASTRacket} \\ \hline
  17290. \CanyASTRacket \\
  17291. \begin{array}{lcl}
  17292. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  17293. \end{array}
  17294. \end{array}
  17295. \]
  17296. \fi}
  17297. {\if\edition\pythonEd
  17298. \[
  17299. \begin{array}{l}
  17300. \gray{\CifASTPython} \\ \hline
  17301. \gray{\CtupASTPython} \\ \hline
  17302. \gray{\CfunASTPython} \\ \hline
  17303. \gray{\ClambdaASTPython} \\ \hline
  17304. \CanyASTPython \\
  17305. \begin{array}{lcl}
  17306. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  17307. \end{array}
  17308. \end{array}
  17309. \]
  17310. \fi}
  17311. \end{tcolorbox}
  17312. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  17313. \label{fig:c5-syntax}
  17314. \end{figure}
  17315. \section{Select Instructions}
  17316. \label{sec:select-Lany}
  17317. In the \code{select\_instructions} pass, we translate the primitive
  17318. operations on the \ANYTY{} type to x86 instructions that manipulate
  17319. the three tag bits of the tagged value. In the following descriptions,
  17320. given an atom $e$ we use a primed variable $e'$ to refer to the result
  17321. of translating $e$ into an x86 argument:
  17322. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  17323. We recommend compiling the
  17324. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  17325. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  17326. shifts the destination to the left by the number of bits specified its
  17327. source argument (in this case three, the length of the tag), and it
  17328. preserves the sign of the integer. We use the \key{orq} instruction to
  17329. combine the tag and the value to form the tagged value. \\
  17330. %
  17331. {\if\edition\racketEd
  17332. \begin{lstlisting}
  17333. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17334. |$\Rightarrow$|
  17335. movq |$e'$|, |\itm{lhs'}|
  17336. salq $3, |\itm{lhs'}|
  17337. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17338. \end{lstlisting}
  17339. \fi}
  17340. %
  17341. {\if\edition\pythonEd
  17342. \begin{lstlisting}
  17343. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17344. |$\Rightarrow$|
  17345. movq |$e'$|, |\itm{lhs'}|
  17346. salq $3, |\itm{lhs'}|
  17347. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17348. \end{lstlisting}
  17349. \fi}
  17350. %
  17351. The instruction selection for tuples and procedures is different
  17352. because their is no need to shift them to the left. The rightmost 3
  17353. bits are already zeros, so we simply combine the value and the tag
  17354. using \key{orq}. \\
  17355. %
  17356. {\if\edition\racketEd
  17357. \begin{center}
  17358. \begin{minipage}{\textwidth}
  17359. \begin{lstlisting}
  17360. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  17361. |$\Rightarrow$|
  17362. movq |$e'$|, |\itm{lhs'}|
  17363. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17364. \end{lstlisting}
  17365. \end{minipage}
  17366. \end{center}
  17367. \fi}
  17368. %
  17369. {\if\edition\pythonEd
  17370. \begin{lstlisting}
  17371. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  17372. |$\Rightarrow$|
  17373. movq |$e'$|, |\itm{lhs'}|
  17374. orq $|$\itm{tag}$|, |\itm{lhs'}|
  17375. \end{lstlisting}
  17376. \fi}
  17377. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  17378. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  17379. operation extracts the type tag from a value of type \ANYTY{}. The
  17380. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  17381. bitwise-and of the value with $111$ ($7$ decimal).
  17382. %
  17383. {\if\edition\racketEd
  17384. \begin{lstlisting}
  17385. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  17386. |$\Rightarrow$|
  17387. movq |$e'$|, |\itm{lhs'}|
  17388. andq $7, |\itm{lhs'}|
  17389. \end{lstlisting}
  17390. \fi}
  17391. %
  17392. {\if\edition\pythonEd
  17393. \begin{lstlisting}
  17394. Assign([|\itm{lhs}|], TagOf(|$e$|))
  17395. |$\Rightarrow$|
  17396. movq |$e'$|, |\itm{lhs'}|
  17397. andq $7, |\itm{lhs'}|
  17398. \end{lstlisting}
  17399. \fi}
  17400. \paragraph{\code{ValueOf}}
  17401. The instructions for \key{ValueOf} also differ, depending on whether
  17402. the type $T$ is a pointer (tuple or function) or not (integer or
  17403. Boolean). The following shows the instruction selection for integers
  17404. and Booleans, in which we produce an untagged value by shifting it to
  17405. the right by 3 bits:
  17406. %
  17407. {\if\edition\racketEd
  17408. \begin{lstlisting}
  17409. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17410. |$\Rightarrow$|
  17411. movq |$e'$|, |\itm{lhs'}|
  17412. sarq $3, |\itm{lhs'}|
  17413. \end{lstlisting}
  17414. \fi}
  17415. %
  17416. {\if\edition\pythonEd
  17417. \begin{lstlisting}
  17418. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17419. |$\Rightarrow$|
  17420. movq |$e'$|, |\itm{lhs'}|
  17421. sarq $3, |\itm{lhs'}|
  17422. \end{lstlisting}
  17423. \fi}
  17424. %
  17425. In the case for tuples and procedures, we zero out the rightmost 3
  17426. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  17427. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  17428. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  17429. Finally, we apply \code{andq} with the tagged value to get the desired
  17430. result.
  17431. %
  17432. {\if\edition\racketEd
  17433. \begin{lstlisting}
  17434. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  17435. |$\Rightarrow$|
  17436. movq $|$-8$|, |\itm{lhs'}|
  17437. andq |$e'$|, |\itm{lhs'}|
  17438. \end{lstlisting}
  17439. \fi}
  17440. %
  17441. {\if\edition\pythonEd
  17442. \begin{lstlisting}
  17443. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  17444. |$\Rightarrow$|
  17445. movq $|$-8$|, |\itm{lhs'}|
  17446. andq |$e'$|, |\itm{lhs'}|
  17447. \end{lstlisting}
  17448. \fi}
  17449. %% \paragraph{Type Predicates} We leave it to the reader to
  17450. %% devise a sequence of instructions to implement the type predicates
  17451. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  17452. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  17453. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  17454. operation combines the effect of \code{ValueOf} with accessing the
  17455. length of a tuple from the tag stored at the zero index of the tuple.
  17456. {\if\edition\racketEd
  17457. \begin{lstlisting}
  17458. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  17459. |$\Longrightarrow$|
  17460. movq $|$-8$|, %r11
  17461. andq |$e_1'$|, %r11
  17462. movq 0(%r11), %r11
  17463. andq $126, %r11
  17464. sarq $1, %r11
  17465. movq %r11, |$\itm{lhs'}$|
  17466. \end{lstlisting}
  17467. \fi}
  17468. {\if\edition\pythonEd
  17469. \begin{lstlisting}
  17470. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  17471. |$\Longrightarrow$|
  17472. movq $|$-8$|, %r11
  17473. andq |$e_1'$|, %r11
  17474. movq 0(%r11), %r11
  17475. andq $126, %r11
  17476. sarq $1, %r11
  17477. movq %r11, |$\itm{lhs'}$|
  17478. \end{lstlisting}
  17479. \fi}
  17480. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  17481. This operation combines the effect of \code{ValueOf} with reading an
  17482. element of the tuple (see
  17483. section~\ref{sec:select-instructions-gc}). However, the index may be
  17484. an arbitrary atom, so instead of computing the offset at compile time,
  17485. we must generate instructions to compute the offset at runtime as
  17486. follows. Note the use of the new instruction \code{imulq}.
  17487. \begin{center}
  17488. \begin{minipage}{0.96\textwidth}
  17489. {\if\edition\racketEd
  17490. \begin{lstlisting}
  17491. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17492. |$\Longrightarrow$|
  17493. movq |$\neg 111$|, %r11
  17494. andq |$e_1'$|, %r11
  17495. movq |$e_2'$|, %rax
  17496. addq $1, %rax
  17497. imulq $8, %rax
  17498. addq %rax, %r11
  17499. movq 0(%r11) |$\itm{lhs'}$|
  17500. \end{lstlisting}
  17501. \fi}
  17502. %
  17503. {\if\edition\pythonEd
  17504. \begin{lstlisting}
  17505. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  17506. |$\Longrightarrow$|
  17507. movq $|$-8$|, %r11
  17508. andq |$e_1'$|, %r11
  17509. movq |$e_2'$|, %rax
  17510. addq $1, %rax
  17511. imulq $8, %rax
  17512. addq %rax, %r11
  17513. movq 0(%r11) |$\itm{lhs'}$|
  17514. \end{lstlisting}
  17515. \fi}
  17516. \end{minipage}
  17517. \end{center}
  17518. % $ pacify font lock
  17519. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  17520. %% The code generation for
  17521. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  17522. %% analogous to the above translation for reading from a tuple.
  17523. \section{Register Allocation for \LangAny{}}
  17524. \label{sec:register-allocation-Lany}
  17525. \index{subject}{register allocation}
  17526. There is an interesting interaction between tagged values and garbage
  17527. collection that has an impact on register allocation. A variable of
  17528. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  17529. that needs to be inspected and copied during garbage collection. Thus,
  17530. we need to treat variables of type \ANYTY{} in a similar way to
  17531. variables of tuple type for purposes of register allocation,
  17532. with particular attention to the following:
  17533. \begin{itemize}
  17534. \item If a variable of type \ANYTY{} is live during a function call,
  17535. then it must be spilled. This can be accomplished by changing
  17536. \code{build\_interference} to mark all variables of type \ANYTY{}
  17537. that are live after a \code{callq} to be interfering with all the
  17538. registers.
  17539. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  17540. the root stack instead of the normal procedure call stack.
  17541. \end{itemize}
  17542. Another concern regarding the root stack is that the garbage collector
  17543. needs to differentiate among (1) plain old pointers to tuples, (2) a
  17544. tagged value that points to a tuple, and (3) a tagged value that is
  17545. not a tuple. We enable this differentiation by choosing not to use the
  17546. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  17547. reserved for identifying plain old pointers to tuples. That way, if
  17548. one of the first three bits is set, then we have a tagged value and
  17549. inspecting the tag can differentiate between tuples ($010$) and the
  17550. other kinds of values.
  17551. %% \begin{exercise}\normalfont
  17552. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  17553. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  17554. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  17555. %% compiler on these new programs and all of your previously created test
  17556. %% programs.
  17557. %% \end{exercise}
  17558. \begin{exercise}\normalfont\normalsize
  17559. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  17560. Create tests for \LangDyn{} by adapting ten of your previous test programs
  17561. by removing type annotations. Add five more test programs that
  17562. specifically rely on the language being dynamically typed. That is,
  17563. they should not be legal programs in a statically typed language, but
  17564. nevertheless they should be valid \LangDyn{} programs that run to
  17565. completion without error.
  17566. \end{exercise}
  17567. \begin{figure}[p]
  17568. \begin{tcolorbox}[colback=white]
  17569. {\if\edition\racketEd
  17570. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17571. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17572. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  17573. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  17574. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  17575. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17576. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  17577. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  17578. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  17579. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  17580. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  17581. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  17582. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  17583. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  17584. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  17585. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  17586. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  17587. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  17588. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  17589. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  17590. \path[->,bend left=15] (Lfun) edge [above] node
  17591. {\ttfamily\footnotesize shrink} (Lfun-2);
  17592. \path[->,bend left=15] (Lfun-2) edge [above] node
  17593. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17594. \path[->,bend left=15] (Lfun-3) edge [above] node
  17595. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17596. \path[->,bend left=15] (Lfun-4) edge [left] node
  17597. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17598. \path[->,bend left=15] (Lfun-5) edge [below] node
  17599. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17600. \path[->,bend left=15] (Lfun-6) edge [below] node
  17601. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  17602. \path[->,bend right=15] (Lfun-7) edge [above] node
  17603. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  17604. \path[->,bend right=15] (F1-2) edge [right] node
  17605. {\ttfamily\footnotesize limit\_functions} (F1-3);
  17606. \path[->,bend right=15] (F1-3) edge [below] node
  17607. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  17608. \path[->,bend right=15] (F1-4) edge [below] node
  17609. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17610. \path[->,bend left=15] (F1-5) edge [above] node
  17611. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  17612. \path[->,bend left=15] (F1-6) edge [below] node
  17613. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17614. \path[->,bend left=15] (C3-2) edge [right] node
  17615. {\ttfamily\footnotesize select\_instructions} (x86-2);
  17616. \path[->,bend right=15] (x86-2) edge [right] node
  17617. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17618. \path[->,bend right=15] (x86-2-1) edge [below] node
  17619. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  17620. \path[->,bend right=15] (x86-2-2) edge [right] node
  17621. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  17622. \path[->,bend left=15] (x86-3) edge [above] node
  17623. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  17624. \path[->,bend left=15] (x86-4) edge [right] node
  17625. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  17626. \end{tikzpicture}
  17627. \fi}
  17628. {\if\edition\pythonEd
  17629. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  17630. \node (Lfun) at (0,4) {\large \LangDyn{}};
  17631. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  17632. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  17633. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  17634. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  17635. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  17636. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  17637. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  17638. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  17639. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  17640. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  17641. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  17642. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  17643. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  17644. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  17645. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  17646. \path[->,bend left=15] (Lfun) edge [above] node
  17647. {\ttfamily\footnotesize shrink} (Lfun-2);
  17648. \path[->,bend left=15] (Lfun-2) edge [above] node
  17649. {\ttfamily\footnotesize uniquify} (Lfun-3);
  17650. \path[->,bend left=15] (Lfun-3) edge [above] node
  17651. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  17652. \path[->,bend left=15] (Lfun-4) edge [left] node
  17653. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  17654. \path[->,bend left=15] (Lfun-5) edge [below] node
  17655. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  17656. \path[->,bend right=15] (Lfun-6) edge [above] node
  17657. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  17658. \path[->,bend right=15] (Lfun-7) edge [above] node
  17659. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  17660. \path[->,bend right=15] (F1-2) edge [right] node
  17661. {\ttfamily\footnotesize limit\_functions} (F1-3);
  17662. \path[->,bend right=15] (F1-3) edge [below] node
  17663. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  17664. \path[->,bend left=15] (F1-5) edge [above] node
  17665. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  17666. \path[->,bend left=15] (F1-6) edge [below] node
  17667. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17668. \path[->,bend right=15] (C3-2) edge [right] node
  17669. {\ttfamily\footnotesize select\_instructions} (x86-2);
  17670. \path[->,bend right=15] (x86-2) edge [below] node
  17671. {\ttfamily\footnotesize assign\_homes} (x86-3);
  17672. \path[->,bend right=15] (x86-3) edge [below] node
  17673. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  17674. \path[->,bend left=15] (x86-4) edge [above] node
  17675. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  17676. \end{tikzpicture}
  17677. \fi}
  17678. \end{tcolorbox}
  17679. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  17680. \label{fig:Ldyn-passes}
  17681. \end{figure}
  17682. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  17683. for the compilation of \LangDyn{}.
  17684. % Further Reading
  17685. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17686. %% {\if\edition\pythonEd
  17687. %% \chapter{Objects}
  17688. %% \label{ch:Lobject}
  17689. %% \index{subject}{objects}
  17690. %% \index{subject}{classes}
  17691. %% \setcounter{footnote}{0}
  17692. %% \fi}
  17693. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17694. \chapter{Gradual Typing}
  17695. \label{ch:Lgrad}
  17696. \index{subject}{gradual typing}
  17697. \setcounter{footnote}{0}
  17698. This chapter studies the language \LangGrad{}, in which the programmer
  17699. can choose between static and dynamic type checking in different parts
  17700. of a program, thereby mixing the statically typed \LangLam{} language
  17701. with the dynamically typed \LangDyn{}. There are several approaches to
  17702. mixing static and dynamic typing, including multilanguage
  17703. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  17704. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  17705. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  17706. programmer controls the amount of static versus dynamic checking by
  17707. adding or removing type annotations on parameters and
  17708. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  17709. The definition of the concrete syntax of \LangGrad{} is shown in
  17710. figure~\ref{fig:Lgrad-concrete-syntax} and the definition of its
  17711. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  17712. syntactic difference between \LangLam{} and \LangGrad{} is that type
  17713. annotations are optional, which is specified in the grammar using the
  17714. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  17715. annotations are not optional, but we use the \CANYTY{} type when a type
  17716. annotation is absent.
  17717. %
  17718. Both the type checker and the interpreter for \LangGrad{} require some
  17719. interesting changes to enable gradual typing, which we discuss in the
  17720. next two sections.
  17721. \newcommand{\LgradGrammarRacket}{
  17722. \begin{array}{lcl}
  17723. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  17724. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17725. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  17726. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  17727. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  17728. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  17729. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  17730. \end{array}
  17731. }
  17732. \newcommand{\LgradASTRacket}{
  17733. \begin{array}{lcl}
  17734. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  17735. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  17736. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  17737. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  17738. \itm{op} &::=& \code{procedure-arity} \\
  17739. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  17740. \end{array}
  17741. }
  17742. \newcommand{\LgradGrammarPython}{
  17743. \begin{array}{lcl}
  17744. \Type &::=& \key{Any}
  17745. \MID \key{int}
  17746. \MID \key{bool}
  17747. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  17748. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  17749. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  17750. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  17751. \MID \CARITY{\Exp} \\
  17752. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  17753. \Param &::=& \Var \MID \Var \key{:} \Type \\
  17754. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  17755. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  17756. \end{array}
  17757. }
  17758. \newcommand{\LgradASTPython}{
  17759. \begin{array}{lcl}
  17760. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  17761. &\MID& \key{TupleType}\LP\Type^{*}\RP
  17762. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  17763. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  17764. &\MID& \ARITY{\Exp} \\
  17765. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  17766. \MID \RETURN{\Exp} \\
  17767. \Param &::=& \LP\Var\key{,}\Type\RP \\
  17768. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  17769. \end{array}
  17770. }
  17771. \begin{figure}[tp]
  17772. \centering
  17773. \begin{tcolorbox}[colback=white]
  17774. \small
  17775. {\if\edition\racketEd
  17776. \[
  17777. \begin{array}{l}
  17778. \gray{\LintGrammarRacket{}} \\ \hline
  17779. \gray{\LvarGrammarRacket{}} \\ \hline
  17780. \gray{\LifGrammarRacket{}} \\ \hline
  17781. \gray{\LwhileGrammarRacket} \\ \hline
  17782. \gray{\LtupGrammarRacket} \\ \hline
  17783. \LgradGrammarRacket \\
  17784. \begin{array}{lcl}
  17785. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  17786. \end{array}
  17787. \end{array}
  17788. \]
  17789. \fi}
  17790. {\if\edition\pythonEd
  17791. \[
  17792. \begin{array}{l}
  17793. \gray{\LintGrammarPython{}} \\ \hline
  17794. \gray{\LvarGrammarPython{}} \\ \hline
  17795. \gray{\LifGrammarPython{}} \\ \hline
  17796. \gray{\LwhileGrammarPython} \\ \hline
  17797. \gray{\LtupGrammarPython} \\ \hline
  17798. \LgradGrammarPython \\
  17799. \begin{array}{lcl}
  17800. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  17801. \end{array}
  17802. \end{array}
  17803. \]
  17804. \fi}
  17805. \end{tcolorbox}
  17806. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  17807. \label{fig:Lgrad-concrete-syntax}
  17808. \end{figure}
  17809. \begin{figure}[tp]
  17810. \centering
  17811. \begin{tcolorbox}[colback=white]
  17812. \small
  17813. {\if\edition\racketEd
  17814. \[
  17815. \begin{array}{l}
  17816. \gray{\LintOpAST} \\ \hline
  17817. \gray{\LvarASTRacket{}} \\ \hline
  17818. \gray{\LifASTRacket{}} \\ \hline
  17819. \gray{\LwhileASTRacket{}} \\ \hline
  17820. \gray{\LtupASTRacket{}} \\ \hline
  17821. \LgradASTRacket \\
  17822. \begin{array}{lcl}
  17823. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17824. \end{array}
  17825. \end{array}
  17826. \]
  17827. \fi}
  17828. {\if\edition\pythonEd
  17829. \[
  17830. \begin{array}{l}
  17831. \gray{\LintASTPython{}} \\ \hline
  17832. \gray{\LvarASTPython{}} \\ \hline
  17833. \gray{\LifASTPython{}} \\ \hline
  17834. \gray{\LwhileASTPython} \\ \hline
  17835. \gray{\LtupASTPython} \\ \hline
  17836. \LgradASTPython \\
  17837. \begin{array}{lcl}
  17838. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17839. \end{array}
  17840. \end{array}
  17841. \]
  17842. \fi}
  17843. \end{tcolorbox}
  17844. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  17845. \label{fig:Lgrad-syntax}
  17846. \end{figure}
  17847. % TODO: more road map -Jeremy
  17848. %\clearpage
  17849. \section{Type Checking \LangGrad{}}
  17850. \label{sec:gradual-type-check}
  17851. We begin by discussing the type checking of a partially typed variant
  17852. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  17853. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  17854. statically typed, so there is nothing special happening there with
  17855. respect to type checking. On the other hand, the \code{inc} function
  17856. does not have type annotations, so the type checker assigns the type
  17857. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  17858. \code{+} operator inside \code{inc}. It expects both arguments to have
  17859. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  17860. a gradually typed language, such differences are allowed so long as
  17861. the types are \emph{consistent}; that is, they are equal except in
  17862. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  17863. is consistent with every other type. Figure~\ref{fig:consistent}
  17864. shows the definition of the
  17865. \racket{\code{consistent?}}\python{\code{consistent}} method.
  17866. %
  17867. So the type checker allows the \code{+} operator to be applied
  17868. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  17869. %
  17870. Next consider the call to the \code{map} function shown in
  17871. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  17872. tuple. The \code{inc} function has type
  17873. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  17874. but parameter \code{f} of \code{map} has type
  17875. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17876. The type checker for \LangGrad{} accepts this call because the two types are
  17877. consistent.
  17878. \begin{figure}[btp]
  17879. % gradual_test_9.rkt
  17880. \begin{tcolorbox}[colback=white]
  17881. {\if\edition\racketEd
  17882. \begin{lstlisting}
  17883. (define (map [f : (Integer -> Integer)]
  17884. [v : (Vector Integer Integer)])
  17885. : (Vector Integer Integer)
  17886. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17887. (define (inc x) (+ x 1))
  17888. (vector-ref (map inc (vector 0 41)) 1)
  17889. \end{lstlisting}
  17890. \fi}
  17891. {\if\edition\pythonEd
  17892. \begin{lstlisting}
  17893. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17894. return f(v[0]), f(v[1])
  17895. def inc(x):
  17896. return x + 1
  17897. t = map(inc, (0, 41))
  17898. print(t[1])
  17899. \end{lstlisting}
  17900. \fi}
  17901. \end{tcolorbox}
  17902. \caption{A partially typed version of the \code{map} example.}
  17903. \label{fig:gradual-map}
  17904. \end{figure}
  17905. \begin{figure}[tbp]
  17906. \begin{tcolorbox}[colback=white]
  17907. {\if\edition\racketEd
  17908. \begin{lstlisting}
  17909. (define/public (consistent? t1 t2)
  17910. (match* (t1 t2)
  17911. [('Integer 'Integer) #t]
  17912. [('Boolean 'Boolean) #t]
  17913. [('Void 'Void) #t]
  17914. [('Any t2) #t]
  17915. [(t1 'Any) #t]
  17916. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17917. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17918. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17919. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17920. (consistent? rt1 rt2))]
  17921. [(other wise) #f]))
  17922. \end{lstlisting}
  17923. \fi}
  17924. {\if\edition\pythonEd
  17925. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17926. def consistent(self, t1, t2):
  17927. match (t1, t2):
  17928. case (AnyType(), _):
  17929. return True
  17930. case (_, AnyType()):
  17931. return True
  17932. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  17933. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  17934. case (TupleType(ts1), TupleType(ts2)):
  17935. return all(map(self.consistent, ts1, ts2))
  17936. case (_, _):
  17937. return t1 == t2
  17938. \end{lstlisting}
  17939. \fi}
  17940. \end{tcolorbox}
  17941. \caption{The consistency method on types.}
  17942. \label{fig:consistent}
  17943. \end{figure}
  17944. It is also helpful to consider how gradual typing handles programs with an
  17945. error, such as applying \code{map} to a function that sometimes
  17946. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  17947. type checker for \LangGrad{} accepts this program because the type of
  17948. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  17949. \code{map}; that is,
  17950. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  17951. is consistent with
  17952. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  17953. One might say that a gradual type checker is optimistic in that it
  17954. accepts programs that might execute without a runtime type error.
  17955. %
  17956. The definition of the type checker for \LangGrad{} is shown in
  17957. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17958. and \ref{fig:type-check-Lgradual-3}.
  17959. %% \begin{figure}[tp]
  17960. %% \centering
  17961. %% \fbox{
  17962. %% \begin{minipage}{0.96\textwidth}
  17963. %% \small
  17964. %% \[
  17965. %% \begin{array}{lcl}
  17966. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17967. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17968. %% \end{array}
  17969. %% \]
  17970. %% \end{minipage}
  17971. %% }
  17972. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  17973. %% \label{fig:Lgrad-prime-syntax}
  17974. %% \end{figure}
  17975. \begin{figure}[tbp]
  17976. \begin{tcolorbox}[colback=white]
  17977. {\if\edition\racketEd
  17978. \begin{lstlisting}
  17979. (define (map [f : (Integer -> Integer)]
  17980. [v : (Vector Integer Integer)])
  17981. : (Vector Integer Integer)
  17982. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17983. (define (inc x) (+ x 1))
  17984. (define (true) #t)
  17985. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  17986. (vector-ref (map maybe_inc (vector 0 41)) 0)
  17987. \end{lstlisting}
  17988. \fi}
  17989. {\if\edition\pythonEd
  17990. \begin{lstlisting}
  17991. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  17992. return f(v[0]), f(v[1])
  17993. def inc(x):
  17994. return x + 1
  17995. def true():
  17996. return True
  17997. def maybe_inc(x):
  17998. return inc(x) if input_int() == 0 else true()
  17999. t = map(maybe_inc, (0, 41))
  18000. print( t[1] )
  18001. \end{lstlisting}
  18002. \fi}
  18003. \end{tcolorbox}
  18004. \caption{A variant of the \code{map} example with an error.}
  18005. \label{fig:map-maybe_inc}
  18006. \end{figure}
  18007. Running this program with input \code{1} triggers an
  18008. error when the \code{maybe\_inc} function returns
  18009. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18010. performs checking at runtime to ensure the integrity of the static
  18011. types, such as the
  18012. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  18013. annotation on
  18014. parameter \code{f} of \code{map}.
  18015. Here we give a preview of how the runtime checking is accomplished;
  18016. the following sections provide the details.
  18017. The runtime checking is carried out by a new \code{Cast} AST node that
  18018. is generated in a new pass named \code{cast\_insert}. The output of
  18019. \code{cast\_insert} is a program in the \LangCast{} language, which
  18020. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  18021. %
  18022. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  18023. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  18024. inserted every time the type checker encounters two types that are
  18025. consistent but not equal. In the \code{inc} function, \code{x} is
  18026. cast to \INTTY{} and the result of the \code{+} is cast to
  18027. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  18028. is cast from
  18029. \racket{\code{(Any -> Any)}}
  18030. \python{\code{Callable[[Any], Any]}}
  18031. to
  18032. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18033. %
  18034. In the next section we see how to interpret the \code{Cast} node.
  18035. \begin{figure}[btp]
  18036. \begin{tcolorbox}[colback=white]
  18037. {\if\edition\racketEd
  18038. \begin{lstlisting}
  18039. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  18040. : (Vector Integer Integer)
  18041. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18042. (define (inc [x : Any]) : Any
  18043. (cast (+ (cast x Any Integer) 1) Integer Any))
  18044. (define (true) : Any (cast #t Boolean Any))
  18045. (define (maybe_inc [x : Any]) : Any
  18046. (if (eq? 0 (read)) (inc x) (true)))
  18047. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  18048. (vector 0 41)) 0)
  18049. \end{lstlisting}
  18050. \fi}
  18051. {\if\edition\pythonEd
  18052. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18053. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18054. return f(v[0]), f(v[1])
  18055. def inc(x : Any) -> Any:
  18056. return Cast(Cast(x, Any, int) + 1, int, Any)
  18057. def true() -> Any:
  18058. return Cast(True, bool, Any)
  18059. def maybe_inc(x : Any) -> Any:
  18060. return inc(x) if input_int() == 0 else true()
  18061. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  18062. (0, 41))
  18063. print(t[1])
  18064. \end{lstlisting}
  18065. \fi}
  18066. \end{tcolorbox}
  18067. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  18068. and \code{maybe\_inc} example.}
  18069. \label{fig:map-cast}
  18070. \end{figure}
  18071. {\if\edition\pythonEd
  18072. \begin{figure}[tbp]
  18073. \begin{tcolorbox}[colback=white]
  18074. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18075. class TypeCheckLgrad(TypeCheckLlambda):
  18076. def type_check_exp(self, e, env) -> Type:
  18077. match e:
  18078. case Name(id):
  18079. return env[id]
  18080. case Constant(value) if isinstance(value, bool):
  18081. return BoolType()
  18082. case Constant(value) if isinstance(value, int):
  18083. return IntType()
  18084. case Call(Name('input_int'), []):
  18085. return IntType()
  18086. case BinOp(left, op, right):
  18087. left_type = self.type_check_exp(left, env)
  18088. self.check_consistent(left_type, IntType(), left)
  18089. right_type = self.type_check_exp(right, env)
  18090. self.check_consistent(right_type, IntType(), right)
  18091. return IntType()
  18092. case IfExp(test, body, orelse):
  18093. test_t = self.type_check_exp(test, env)
  18094. self.check_consistent(test_t, BoolType(), test)
  18095. body_t = self.type_check_exp(body, env)
  18096. orelse_t = self.type_check_exp(orelse, env)
  18097. self.check_consistent(body_t, orelse_t, e)
  18098. return self.join_types(body_t, orelse_t)
  18099. case Call(func, args):
  18100. func_t = self.type_check_exp(func, env)
  18101. args_t = [self.type_check_exp(arg, env) for arg in args]
  18102. match func_t:
  18103. case FunctionType(params_t, return_t) if len(params_t) == len(args_t):
  18104. for (arg_t, param_t) in zip(args_t, params_t):
  18105. self.check_consistent(param_t, arg_t, e)
  18106. return return_t
  18107. case AnyType():
  18108. return AnyType()
  18109. case _:
  18110. raise Exception('type_check_exp: in call, unexpected ' + repr(func_t))
  18111. ...
  18112. case _:
  18113. raise Exception('type_check_exp: unexpected ' + repr(e))
  18114. \end{lstlisting}
  18115. \end{tcolorbox}
  18116. \caption{Type checking expressions in the \LangGrad{} language.}
  18117. \label{fig:type-check-Lgradual-1}
  18118. \end{figure}
  18119. \begin{figure}[tbp]
  18120. \begin{tcolorbox}[colback=white]
  18121. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18122. def check_exp(self, e, expected_ty, env):
  18123. match e:
  18124. case Lambda(params, body):
  18125. match expected_ty:
  18126. case FunctionType(params_t, return_t):
  18127. new_env = env.copy().update(zip(params, params_t))
  18128. e.has_type = expected_ty
  18129. body_ty = self.type_check_exp(body, new_env)
  18130. self.check_consistent(body_ty, return_t)
  18131. case AnyType():
  18132. new_env = env.copy().update((p, AnyType()) for p in params)
  18133. e.has_type = FunctionType([AnyType() for _ in params], AnyType())
  18134. body_ty = self.type_check_exp(body, new_env)
  18135. case _:
  18136. raise Exception('lambda does not have type ' + str(expected_ty))
  18137. case _:
  18138. e_ty = self.type_check_exp(e, env)
  18139. self.check_consistent(e_ty, expected_ty, e)
  18140. \end{lstlisting}
  18141. \end{tcolorbox}
  18142. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  18143. \label{fig:type-check-Lgradual-2}
  18144. \end{figure}
  18145. \begin{figure}[tbp]
  18146. \begin{tcolorbox}[colback=white]
  18147. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18148. def type_check_stmt(self, s, env, return_type):
  18149. match s:
  18150. case Assign([Name(id)], value):
  18151. value_ty = self.type_check_exp(value, env)
  18152. if id in env:
  18153. self.check_consistent(env[id], value_ty, value)
  18154. else:
  18155. env[id] = value_ty
  18156. ...
  18157. case _:
  18158. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  18159. def type_check_stmts(self, ss, env, return_type):
  18160. for s in ss:
  18161. self.type_check_stmt(s, env, return_type)
  18162. \end{lstlisting}
  18163. \end{tcolorbox}
  18164. \caption{Type checking statements in the \LangGrad{} language.}
  18165. \label{fig:type-check-Lgradual-3}
  18166. \end{figure}
  18167. \begin{figure}[tbp]
  18168. \begin{tcolorbox}[colback=white]
  18169. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18170. def join_types(self, t1, t2):
  18171. match (t1, t2):
  18172. case (AnyType(), _):
  18173. return t2
  18174. case (_, AnyType()):
  18175. return t1
  18176. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18177. return FunctionType(list(map(self.join_types, ps1, ps2)),
  18178. self.join_types(rt1,rt2))
  18179. case (TupleType(ts1), TupleType(ts2)):
  18180. return TupleType(list(map(self.join_types, ts1, ts2)))
  18181. case (_, _):
  18182. return t1
  18183. def check_consistent(self, t1, t2, e):
  18184. if not self.consistent(t1, t2):
  18185. raise Exception('error: ' + repr(t1) + ' inconsistent with ' + repr(t2) \
  18186. + ' in ' + repr(e))
  18187. \end{lstlisting}
  18188. \end{tcolorbox}
  18189. \caption{Auxiliary methods for type checking \LangGrad{}.}
  18190. \label{fig:type-check-Lgradual-aux}
  18191. \end{figure}
  18192. \fi}
  18193. {\if\edition\racketEd
  18194. \begin{figure}[tbp]
  18195. \begin{tcolorbox}[colback=white]
  18196. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18197. (define/override (type-check-exp env)
  18198. (lambda (e)
  18199. (define recur (type-check-exp env))
  18200. (match e
  18201. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  18202. (define-values (new-es ts)
  18203. (for/lists (exprs types) ([e es])
  18204. (recur e)))
  18205. (define t-ret (type-check-op op ts e))
  18206. (values (Prim op new-es) t-ret)]
  18207. [(Prim 'eq? (list e1 e2))
  18208. (define-values (e1^ t1) (recur e1))
  18209. (define-values (e2^ t2) (recur e2))
  18210. (check-consistent? t1 t2 e)
  18211. (define T (meet t1 t2))
  18212. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  18213. [(Prim 'and (list e1 e2))
  18214. (recur (If e1 e2 (Bool #f)))]
  18215. [(Prim 'or (list e1 e2))
  18216. (define tmp (gensym 'tmp))
  18217. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  18218. [(If e1 e2 e3)
  18219. (define-values (e1^ T1) (recur e1))
  18220. (define-values (e2^ T2) (recur e2))
  18221. (define-values (e3^ T3) (recur e3))
  18222. (check-consistent? T1 'Boolean e)
  18223. (check-consistent? T2 T3 e)
  18224. (define Tif (meet T2 T3))
  18225. (values (If e1^ e2^ e3^) Tif)]
  18226. [(SetBang x e1)
  18227. (define-values (e1^ T1) (recur e1))
  18228. (define varT (dict-ref env x))
  18229. (check-consistent? T1 varT e)
  18230. (values (SetBang x e1^) 'Void)]
  18231. [(WhileLoop e1 e2)
  18232. (define-values (e1^ T1) (recur e1))
  18233. (check-consistent? T1 'Boolean e)
  18234. (define-values (e2^ T2) ((type-check-exp env) e2))
  18235. (values (WhileLoop e1^ e2^) 'Void)]
  18236. [(Prim 'vector-length (list e1))
  18237. (define-values (e1^ t) (recur e1))
  18238. (match t
  18239. [`(Vector ,ts ...)
  18240. (values (Prim 'vector-length (list e1^)) 'Integer)]
  18241. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  18242. \end{lstlisting}
  18243. \end{tcolorbox}
  18244. \caption{Type checker for the \LangGrad{} language, part 1.}
  18245. \label{fig:type-check-Lgradual-1}
  18246. \end{figure}
  18247. \begin{figure}[tbp]
  18248. \begin{tcolorbox}[colback=white]
  18249. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18250. [(Prim 'vector-ref (list e1 e2))
  18251. (define-values (e1^ t1) (recur e1))
  18252. (define-values (e2^ t2) (recur e2))
  18253. (check-consistent? t2 'Integer e)
  18254. (match t1
  18255. [`(Vector ,ts ...)
  18256. (match e2^
  18257. [(Int i)
  18258. (unless (and (0 . <= . i) (i . < . (length ts)))
  18259. (error 'type-check "invalid index ~a in ~a" i e))
  18260. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  18261. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  18262. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  18263. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18264. [(Prim 'vector-set! (list e1 e2 e3) )
  18265. (define-values (e1^ t1) (recur e1))
  18266. (define-values (e2^ t2) (recur e2))
  18267. (define-values (e3^ t3) (recur e3))
  18268. (check-consistent? t2 'Integer e)
  18269. (match t1
  18270. [`(Vector ,ts ...)
  18271. (match e2^
  18272. [(Int i)
  18273. (unless (and (0 . <= . i) (i . < . (length ts)))
  18274. (error 'type-check "invalid index ~a in ~a" i e))
  18275. (check-consistent? (list-ref ts i) t3 e)
  18276. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  18277. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  18278. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  18279. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  18280. [(Apply e1 e2s)
  18281. (define-values (e1^ T1) (recur e1))
  18282. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  18283. (match T1
  18284. [`(,T1ps ... -> ,T1rt)
  18285. (for ([T2 T2s] [Tp T1ps])
  18286. (check-consistent? T2 Tp e))
  18287. (values (Apply e1^ e2s^) T1rt)]
  18288. [`Any (values (Apply e1^ e2s^) 'Any)]
  18289. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  18290. [(Lambda params Tr e1)
  18291. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  18292. (match p
  18293. [`[,x : ,T] (values x T)]
  18294. [(? symbol? x) (values x 'Any)])))
  18295. (define-values (e1^ T1)
  18296. ((type-check-exp (append (map cons xs Ts) env)) e1))
  18297. (check-consistent? Tr T1 e)
  18298. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  18299. `(,@Ts -> ,Tr))]
  18300. [else ((super type-check-exp env) e)]
  18301. )))
  18302. \end{lstlisting}
  18303. \end{tcolorbox}
  18304. \caption{Type checker for the \LangGrad{} language, part 2.}
  18305. \label{fig:type-check-Lgradual-2}
  18306. \end{figure}
  18307. \begin{figure}[tbp]
  18308. \begin{tcolorbox}[colback=white]
  18309. \begin{lstlisting}
  18310. (define/override (type-check-def env)
  18311. (lambda (e)
  18312. (match e
  18313. [(Def f params rt info body)
  18314. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  18315. (match p
  18316. [`[,x : ,T] (values x T)]
  18317. [(? symbol? x) (values x 'Any)])))
  18318. (define new-env (append (map cons xs ps) env))
  18319. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18320. (check-consistent? ty^ rt e)
  18321. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  18322. [else (error 'type-check "ill-formed function definition ~a" e)]
  18323. )))
  18324. (define/override (type-check-program e)
  18325. (match e
  18326. [(Program info body)
  18327. (define-values (body^ ty) ((type-check-exp '()) body))
  18328. (check-consistent? ty 'Integer e)
  18329. (ProgramDefsExp info '() body^)]
  18330. [(ProgramDefsExp info ds body)
  18331. (define new-env (for/list ([d ds])
  18332. (cons (Def-name d) (fun-def-type d))))
  18333. (define ds^ (for/list ([d ds])
  18334. ((type-check-def new-env) d)))
  18335. (define-values (body^ ty) ((type-check-exp new-env) body))
  18336. (check-consistent? ty 'Integer e)
  18337. (ProgramDefsExp info ds^ body^)]
  18338. [else (super type-check-program e)]))
  18339. \end{lstlisting}
  18340. \end{tcolorbox}
  18341. \caption{Type checker for the \LangGrad{} language, part 3.}
  18342. \label{fig:type-check-Lgradual-3}
  18343. \end{figure}
  18344. \begin{figure}[tbp]
  18345. \begin{tcolorbox}[colback=white]
  18346. \begin{lstlisting}
  18347. (define/public (join t1 t2)
  18348. (match* (t1 t2)
  18349. [('Integer 'Integer) 'Integer]
  18350. [('Boolean 'Boolean) 'Boolean]
  18351. [('Void 'Void) 'Void]
  18352. [('Any t2) t2]
  18353. [(t1 'Any) t1]
  18354. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18355. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  18356. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18357. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  18358. -> ,(join rt1 rt2))]))
  18359. (define/public (meet t1 t2)
  18360. (match* (t1 t2)
  18361. [('Integer 'Integer) 'Integer]
  18362. [('Boolean 'Boolean) 'Boolean]
  18363. [('Void 'Void) 'Void]
  18364. [('Any t2) 'Any]
  18365. [(t1 'Any) 'Any]
  18366. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18367. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  18368. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18369. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  18370. -> ,(meet rt1 rt2))]))
  18371. (define/public (check-consistent? t1 t2 e)
  18372. (unless (consistent? t1 t2)
  18373. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  18374. (define explicit-prim-ops
  18375. (set-union
  18376. (type-predicates)
  18377. (set 'procedure-arity 'eq? 'not 'and 'or
  18378. 'vector 'vector-length 'vector-ref 'vector-set!
  18379. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  18380. (define/override (fun-def-type d)
  18381. (match d
  18382. [(Def f params rt info body)
  18383. (define ps
  18384. (for/list ([p params])
  18385. (match p
  18386. [`[,x : ,T] T]
  18387. [(? symbol?) 'Any]
  18388. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  18389. `(,@ps -> ,rt)]
  18390. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  18391. \end{lstlisting}
  18392. \end{tcolorbox}
  18393. \caption{Auxiliary functions for type checking \LangGrad{}.}
  18394. \label{fig:type-check-Lgradual-aux}
  18395. \end{figure}
  18396. \fi}
  18397. \clearpage
  18398. \section{Interpreting \LangCast{}}
  18399. \label{sec:interp-casts}
  18400. The runtime behavior of casts involving simple types such as
  18401. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  18402. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  18403. \code{Inject} operator of \LangAny{}, which puts the integer into a
  18404. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  18405. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  18406. operator, by checking the value's tag and either retrieving
  18407. the underlying integer or signaling an error if the tag is not the
  18408. one for integers (figure~\ref{fig:interp-Lany-aux}).
  18409. %
  18410. Things get more interesting with casts involving
  18411. \racket{function and tuple types}\python{function, tuple, and array types}.
  18412. Consider the cast of the function \code{maybe\_inc} from
  18413. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  18414. to
  18415. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  18416. shown in figure~\ref{fig:map-maybe_inc}.
  18417. When the \code{maybe\_inc} function flows through
  18418. this cast at runtime, we don't know whether it will return
  18419. an integer, because that depends on the input from the user.
  18420. The \LangCast{} interpreter therefore delays the checking
  18421. of the cast until the function is applied. To do so it
  18422. wraps \code{maybe\_inc} in a new function that casts its parameter
  18423. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  18424. casts the return value from \CANYTY{} to \INTTY{}.
  18425. {\if\edition\pythonEd
  18426. %
  18427. There are further complications regarding casts on mutable data
  18428. such as the \code{list} type introduced in
  18429. the challenge assignment of section~\ref{sec:arrays}.
  18430. %
  18431. \fi}
  18432. %
  18433. Consider the example presented in figure~\ref{fig:map-bang} that
  18434. defines a partially typed version of \code{map} whose parameter
  18435. \code{v} has type
  18436. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  18437. and that updates \code{v} in place
  18438. instead of returning a new tuple. So, we name this function
  18439. \code{map\_inplace}. We apply \code{map\_inplace} to an
  18440. \racket{tuple}\python{array} of integers, so the type checker inserts a
  18441. cast from
  18442. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  18443. to
  18444. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  18445. A naive way for the \LangCast{} interpreter to cast between
  18446. \racket{tuple}\python{array} types would be a build a new
  18447. \racket{tuple}\python{array}
  18448. whose elements are the result
  18449. of casting each of the original elements to the appropriate target
  18450. type.
  18451. However, this approach is not valid for mutable data structures.
  18452. In the example of figure~\ref{fig:map-bang},
  18453. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  18454. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  18455. the original one.
  18456. \begin{figure}[tbp]
  18457. \begin{tcolorbox}[colback=white]
  18458. % gradual_test_11.rkt
  18459. {\if\edition\racketEd
  18460. \begin{lstlisting}
  18461. (define (map_inplace [f : (Any -> Any)]
  18462. [v : (Vector Any Any)]) : Void
  18463. (begin
  18464. (vector-set! v 0 (f (vector-ref v 0)))
  18465. (vector-set! v 1 (f (vector-ref v 1)))))
  18466. (define (inc x) (+ x 1))
  18467. (let ([v (vector 0 41)])
  18468. (begin (map_inplace inc v) (vector-ref v 1)))
  18469. \end{lstlisting}
  18470. \fi}
  18471. {\if\edition\pythonEd
  18472. \begin{lstlisting}
  18473. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  18474. i = 0
  18475. while i != len(v):
  18476. v[i] = f(v[i])
  18477. i = i + 1
  18478. def inc(x : int) -> int:
  18479. return x + 1
  18480. v = [0, 41]
  18481. map_inplace(inc, v)
  18482. print( v[1] )
  18483. \end{lstlisting}
  18484. \fi}
  18485. \end{tcolorbox}
  18486. \caption{An example involving casts on arrays.}
  18487. \label{fig:map-bang}
  18488. \end{figure}
  18489. Instead the interpreter needs to create a new kind of value, a
  18490. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  18491. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  18492. and then applies a
  18493. cast to the resulting value. On a write, the proxy casts the argument
  18494. value and then performs the write to the underlying \racket{tuple}\python{array}.
  18495. \racket{
  18496. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  18497. \code{0} from \INTTY{} to \CANYTY{}.
  18498. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  18499. from \CANYTY{} to \INTTY{}.
  18500. }
  18501. \python{
  18502. For the subscript \code{v[i]} in \code{f([v[i])} of \code{map\_inplace},
  18503. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  18504. For the subscript on the left of the assignment,
  18505. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  18506. }
  18507. The final category of cast that we need to consider consist of casts between
  18508. the \CANYTY{} type and higher-order types such as functions and
  18509. \racket{tuples}\python{lists}. Figure~\ref{fig:map-any} shows a
  18510. variant of \code{map\_inplace} in which parameter \code{v} does not
  18511. have a type annotation, so it is given type \CANYTY{}. In the call to
  18512. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  18513. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  18514. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  18515. \code{Inject}, but that doesn't work because
  18516. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  18517. a flat type. Instead, we must first cast to
  18518. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  18519. and then inject to \CANYTY{}.
  18520. \begin{figure}[tbp]
  18521. \begin{tcolorbox}[colback=white]
  18522. {\if\edition\racketEd
  18523. \begin{lstlisting}
  18524. (define (map_inplace [f : (Any -> Any)] v) : Void
  18525. (begin
  18526. (vector-set! v 0 (f (vector-ref v 0)))
  18527. (vector-set! v 1 (f (vector-ref v 1)))))
  18528. (define (inc x) (+ x 1))
  18529. (let ([v (vector 0 41)])
  18530. (begin (map_inplace inc v) (vector-ref v 1)))
  18531. \end{lstlisting}
  18532. \fi}
  18533. {\if\edition\pythonEd
  18534. \begin{lstlisting}
  18535. def map_inplace(f : Callable[[Any], Any], v) -> None:
  18536. i = 0
  18537. while i != len(v):
  18538. v[i] = f(v[i])
  18539. i = i + 1
  18540. def inc(x):
  18541. return x + 1
  18542. v = [0, 41]
  18543. map_inplace(inc, v)
  18544. print( v[1] )
  18545. \end{lstlisting}
  18546. \fi}
  18547. \end{tcolorbox}
  18548. \caption{Casting an \racket{tuple}\python{array} to \CANYTY{}.}
  18549. \label{fig:map-any}
  18550. \end{figure}
  18551. \begin{figure}[tbp]
  18552. \begin{tcolorbox}[colback=white]
  18553. {\if\edition\racketEd
  18554. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18555. (define/public (apply_cast v s t)
  18556. (match* (s t)
  18557. [(t1 t2) #:when (equal? t1 t2) v]
  18558. [('Any t2)
  18559. (match t2
  18560. [`(,ts ... -> ,rt)
  18561. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18562. (define v^ (apply-project v any->any))
  18563. (apply_cast v^ any->any `(,@ts -> ,rt))]
  18564. [`(Vector ,ts ...)
  18565. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18566. (define v^ (apply-project v vec-any))
  18567. (apply_cast v^ vec-any `(Vector ,@ts))]
  18568. [else (apply-project v t2)])]
  18569. [(t1 'Any)
  18570. (match t1
  18571. [`(,ts ... -> ,rt)
  18572. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  18573. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  18574. (apply-inject v^ (any-tag any->any))]
  18575. [`(Vector ,ts ...)
  18576. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  18577. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  18578. (apply-inject v^ (any-tag vec-any))]
  18579. [else (apply-inject v (any-tag t1))])]
  18580. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18581. (define x (gensym 'x))
  18582. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  18583. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  18584. (define cast-writes
  18585. (for/list ([t1 ts1] [t2 ts2])
  18586. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  18587. `(vector-proxy ,(vector v (apply vector cast-reads)
  18588. (apply vector cast-writes)))]
  18589. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18590. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  18591. `(function ,xs ,(Cast
  18592. (Apply (Value v)
  18593. (for/list ([x xs][t1 ts1][t2 ts2])
  18594. (Cast (Var x) t2 t1)))
  18595. rt1 rt2) ())]
  18596. ))
  18597. \end{lstlisting}
  18598. \fi}
  18599. {\if\edition\pythonEd
  18600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18601. def apply_cast(self, value, src, tgt):
  18602. match (src, tgt):
  18603. case (AnyType(), FunctionType(ps2, rt2)):
  18604. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  18605. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  18606. case (AnyType(), TupleType(ts2)):
  18607. anytup = TupleType([AnyType() for t1 in ts2])
  18608. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  18609. case (AnyType(), ListType(t2)):
  18610. anylist = ListType([AnyType() for t1 in ts2])
  18611. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  18612. case (AnyType(), AnyType()):
  18613. return value
  18614. case (AnyType(), _):
  18615. return self.apply_project(value, tgt)
  18616. case (FunctionType(ps1,rt1), AnyType()):
  18617. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  18618. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  18619. case (TupleType(ts1), AnyType()):
  18620. anytup = TupleType([AnyType() for t1 in ts1])
  18621. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  18622. case (ListType(t1), AnyType()):
  18623. anylist = ListType(AnyType())
  18624. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  18625. case (_, AnyType()):
  18626. return self.apply_inject(value, src)
  18627. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18628. params = [generate_name('x') for p in ps2]
  18629. args = [Cast(Name(x), t2, t1)
  18630. for (x,t1,t2) in zip(params, ps1, ps2)]
  18631. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  18632. return Function('cast', params, [Return(body)], {})
  18633. case (TupleType(ts1), TupleType(ts2)):
  18634. x = generate_name('x')
  18635. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18636. for (t1,t2) in zip(ts1,ts2)]
  18637. return ProxiedTuple(value, reads)
  18638. case (ListType(t1), ListType(t2)):
  18639. x = generate_name('x')
  18640. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  18641. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  18642. return ProxiedList(value, read, write)
  18643. case (t1, t2) if t1 == t2:
  18644. return value
  18645. case (t1, t2):
  18646. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  18647. def apply_inject(self, value, src):
  18648. return Tagged(value, self.type_to_tag(src))
  18649. def apply_project(self, value, tgt):
  18650. match value:
  18651. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  18652. return val
  18653. case _:
  18654. raise Exception('apply_project, unexpected ' + repr(value))
  18655. \end{lstlisting}
  18656. \fi}
  18657. \end{tcolorbox}
  18658. \caption{The \code{apply\_cast} auxiliary method.}
  18659. \label{fig:apply_cast}
  18660. \end{figure}
  18661. The \LangCast{} interpreter uses an auxiliary function named
  18662. \code{apply\_cast} to cast a value from a source type to a target type,
  18663. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  18664. the kinds of casts that we've discussed in this section.
  18665. %
  18666. The definition of the interpreter for \LangCast{} is shown in
  18667. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  18668. dispatching to \code{apply\_cast}.
  18669. \racket{To handle the addition of tuple
  18670. proxies, we update the tuple primitives in \code{interp-op} using the
  18671. functions given in figure~\ref{fig:guarded-tuple}.}
  18672. Next we turn to the individual passes needed for compiling \LangGrad{}.
  18673. \begin{figure}[tbp]
  18674. \begin{tcolorbox}[colback=white]
  18675. {\if\edition\racketEd
  18676. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18677. (define interp-Lcast-class
  18678. (class interp-Llambda-class
  18679. (super-new)
  18680. (inherit apply-fun apply-inject apply-project)
  18681. (define/override (interp-op op)
  18682. (match op
  18683. ['vector-length guarded-vector-length]
  18684. ['vector-ref guarded-vector-ref]
  18685. ['vector-set! guarded-vector-set!]
  18686. ['any-vector-ref (lambda (v i)
  18687. (match v [`(tagged ,v^ ,tg)
  18688. (guarded-vector-ref v^ i)]))]
  18689. ['any-vector-set! (lambda (v i a)
  18690. (match v [`(tagged ,v^ ,tg)
  18691. (guarded-vector-set! v^ i a)]))]
  18692. ['any-vector-length (lambda (v)
  18693. (match v [`(tagged ,v^ ,tg)
  18694. (guarded-vector-length v^)]))]
  18695. [else (super interp-op op)]
  18696. ))
  18697. (define/override ((interp-exp env) e)
  18698. (define (recur e) ((interp-exp env) e))
  18699. (match e
  18700. [(Value v) v]
  18701. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  18702. [else ((super interp-exp env) e)]))
  18703. ))
  18704. (define (interp-Lcast p)
  18705. (send (new interp-Lcast-class) interp-program p))
  18706. \end{lstlisting}
  18707. \fi}
  18708. {\if\edition\pythonEd
  18709. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18710. class InterpLcast(InterpLany):
  18711. def interp_exp(self, e, env):
  18712. match e:
  18713. case Cast(value, src, tgt):
  18714. v = self.interp_exp(value, env)
  18715. return self.apply_cast(v, src, tgt)
  18716. case ValueExp(value):
  18717. return value
  18718. ...
  18719. case _:
  18720. return super().interp_exp(e, env)
  18721. \end{lstlisting}
  18722. \fi}
  18723. \end{tcolorbox}
  18724. \caption{The interpreter for \LangCast{}.}
  18725. \label{fig:interp-Lcast}
  18726. \end{figure}
  18727. {\if\edition\racketEd
  18728. \begin{figure}[tbp]
  18729. \begin{tcolorbox}[colback=white]
  18730. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18731. (define (guarded-vector-ref vec i)
  18732. (match vec
  18733. [`(vector-proxy ,proxy)
  18734. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  18735. (define rd (vector-ref (vector-ref proxy 1) i))
  18736. (apply-fun rd (list val) 'guarded-vector-ref)]
  18737. [else (vector-ref vec i)]))
  18738. (define (guarded-vector-set! vec i arg)
  18739. (match vec
  18740. [`(vector-proxy ,proxy)
  18741. (define wr (vector-ref (vector-ref proxy 2) i))
  18742. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  18743. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  18744. [else (vector-set! vec i arg)]))
  18745. (define (guarded-vector-length vec)
  18746. (match vec
  18747. [`(vector-proxy ,proxy)
  18748. (guarded-vector-length (vector-ref proxy 0))]
  18749. [else (vector-length vec)]))
  18750. \end{lstlisting}
  18751. %% {\if\edition\pythonEd
  18752. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18753. %% UNDER CONSTRUCTION
  18754. %% \end{lstlisting}
  18755. %% \fi}
  18756. \end{tcolorbox}
  18757. \caption{The \code{guarded-vector} auxiliary functions.}
  18758. \label{fig:guarded-tuple}
  18759. \end{figure}
  18760. \fi}
  18761. {\if\edition\pythonEd
  18762. \section{Overload Resolution}
  18763. \label{sec:gradual-resolution}
  18764. Recall that when we added support for arrays in
  18765. section~\ref{sec:arrays}, the syntax for the array operations were the
  18766. same as for tuple operations (e.g., accessing an element, getting the
  18767. length). So we performed overload resolution, with a pass named
  18768. \code{resolve}, to separate the array and tuple operations. In
  18769. particular, we introduced the primitives \code{array\_load},
  18770. \code{array\_store}, and \code{array\_len}.
  18771. For gradual typing, we further overload these operators to work on
  18772. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  18773. updated with new cases for the \CANYTY{} type, translating the element
  18774. access and length operations to the primitives \code{any\_load},
  18775. \code{any\_store}, and \code{any\_len}.
  18776. \fi}
  18777. \section{Cast Insertion}
  18778. \label{sec:gradual-insert-casts}
  18779. In our discussion of type checking of \LangGrad{}, we mentioned how
  18780. the runtime aspect of type checking is carried out by the \code{Cast}
  18781. AST node, which is added to the program by a new pass named
  18782. \code{cast\_insert}. The target of this pass is the \LangCast{}
  18783. language. We now discuss the details of this pass.
  18784. The \code{cast\_insert} pass is closely related to the type checker
  18785. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  18786. In particular, the type checker allows implicit casts between
  18787. consistent types. The job of the \code{cast\_insert} pass is to make
  18788. those casts explicit. It does so by inserting
  18789. \code{Cast} nodes into the AST.
  18790. %
  18791. For the most part, the implicit casts occur in places where the type
  18792. checker checks two types for consistency. Consider the case for
  18793. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  18794. checker requires that the type of the left operand is consistent with
  18795. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  18796. \code{Cast} around the left operand, converting from its type to
  18797. \INTTY{}. The story is similar for the right operand. It is not always
  18798. necessary to insert a cast, e.g., if the left operand already has type
  18799. \INTTY{} then there is no need for a \code{Cast}.
  18800. Some of the implicit casts are not as straightforward. One such case
  18801. arises with the
  18802. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  18803. see that the type checker requires that the two branches have
  18804. consistent types and that type of the conditional expression is the
  18805. meet of the branches' types. In the target language \LangCast{}, both
  18806. branches will need to have the same type, and that type
  18807. will be the type of the conditional expression. Thus, each branch requires
  18808. a \code{Cast} to convert from its type to the meet of the branches' types.
  18809. The case for the function call exhibits another interesting situation. If
  18810. the function expression is of type \CANYTY{}, then it needs to be cast
  18811. to a function type so that it can be used in a function call in
  18812. \LangCast{}. Which function type should it be cast to? The parameter
  18813. and return types are unknown, so we can simply use \CANYTY{} for all
  18814. of them. Furthermore, in \LangCast{} the argument types will need to
  18815. exactly match the parameter types, so we must cast all the arguments
  18816. to type \CANYTY{} (if they are not already of that type).
  18817. {\if\edition\racketEd
  18818. %
  18819. Likewise, the cases for the tuple operators \code{vector-length},
  18820. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  18821. where the tuple expression is of type \CANYTY{}. Instead of
  18822. handling these situations with casts, we recommend translating
  18823. the special-purpose variants of the tuple operators that handle
  18824. tuples of type \CANYTY{}: \code{any-vector-length},
  18825. \code{any-vector-ref}, and \code{any-vector-set!}.
  18826. %
  18827. \fi}
  18828. \section{Lower Casts}
  18829. \label{sec:lower_casts}
  18830. The next step in the journey toward x86 is the \code{lower\_casts}
  18831. pass that translates the casts in \LangCast{} to the lower-level
  18832. \code{Inject} and \code{Project} operators and new operators for
  18833. proxies, extending the \LangLam{} language to \LangProxy{}.
  18834. The \LangProxy{} language can also be described as an extension of
  18835. \LangAny{}, with the addition of proxies. We recommend creating an
  18836. auxiliary function named \code{lower\_cast} that takes an expression
  18837. (in \LangCast{}), a source type, and a target type and translates it
  18838. to an expression in \LangProxy{}.
  18839. The \code{lower\_cast} function can follow a code structure similar to
  18840. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  18841. the interpreter for \LangCast{}, because it must handle the same cases
  18842. as \code{apply\_cast} and it needs to mimic the behavior of
  18843. \code{apply\_cast}. The most interesting cases concern
  18844. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  18845. {\if\edition\racketEd
  18846. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  18847. type to another tuple type is accomplished by creating a proxy that
  18848. intercepts the operations on the underlying tuple. Here we make the
  18849. creation of the proxy explicit with the \code{vector-proxy} AST
  18850. node. It takes three arguments: the first is an expression for the
  18851. tuple, the second is tuple of functions for casting an element that is
  18852. being read from the tuple, and the third is a tuple of functions for
  18853. casting an element that is being written to the array. You can create
  18854. the functions for reading and writing using lambda expressions. Also,
  18855. as we show in the next section, we need to differentiate these tuples
  18856. of functions from the user-created ones, so we recommend using a new
  18857. AST node named \code{raw-vector} instead of \code{vector}.
  18858. %
  18859. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18860. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  18861. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  18862. \fi}
  18863. {\if\edition\pythonEd
  18864. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  18865. type to another array type is accomplished by creating a proxy that
  18866. intercepts the operations on the underlying array. Here we make the
  18867. creation of the proxy explicit with the \code{ListProxy} AST node. It
  18868. takes fives arguments: the first is an expression for the array, the
  18869. second is a function for casting an element that is being read from
  18870. the array, the third is a function for casting an element that is
  18871. being written to the array, the fourth is the type of the underlying
  18872. array, and the fifth is the type of the proxied array. You can create
  18873. the functions for reading and writing using lambda expressions.
  18874. A cast between two tuple types can be handled in a similar manner. We
  18875. create a proxy with the \code{TupleProxy} AST node. Tuples are
  18876. immutable, so there is no need for a function to cast the value during
  18877. a write. Because there is a separate element type for each slot in
  18878. the tuple, we need not just one function for casting during a read,
  18879. but instead a tuple of functions.
  18880. %
  18881. Also, as we show in the next section, we need to differentiate these
  18882. tuples from the user-created ones, so we recommend using a new AST
  18883. node named \code{RawTuple} instead of \code{Tuple} to create the
  18884. tuples of functions.
  18885. %
  18886. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  18887. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  18888. that involved casting an array of integers to an array of \CANYTY{}.
  18889. \fi}
  18890. \begin{figure}[tbp]
  18891. \begin{tcolorbox}[colback=white]
  18892. {\if\edition\racketEd
  18893. \begin{lstlisting}
  18894. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  18895. (begin
  18896. (vector-set! v 0 (f (vector-ref v 0)))
  18897. (vector-set! v 1 (f (vector-ref v 1)))))
  18898. (define (inc [x : Any]) : Any
  18899. (inject (+ (project x Integer) 1) Integer))
  18900. (let ([v (vector 0 41)])
  18901. (begin
  18902. (map_inplace inc (vector-proxy v
  18903. (raw-vector (lambda: ([x9 : Integer]) : Any
  18904. (inject x9 Integer))
  18905. (lambda: ([x9 : Integer]) : Any
  18906. (inject x9 Integer)))
  18907. (raw-vector (lambda: ([x9 : Any]) : Integer
  18908. (project x9 Integer))
  18909. (lambda: ([x9 : Any]) : Integer
  18910. (project x9 Integer)))))
  18911. (vector-ref v 1)))
  18912. \end{lstlisting}
  18913. \fi}
  18914. {\if\edition\pythonEd
  18915. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18916. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  18917. i = 0
  18918. while i != array_len(v):
  18919. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  18920. i = (i + 1)
  18921. def inc(x : int) -> int:
  18922. return (x + 1)
  18923. def main() -> int:
  18924. v = [0, 41]
  18925. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  18926. print(array_load(v, 1))
  18927. return 0
  18928. \end{lstlisting}
  18929. \fi}
  18930. \end{tcolorbox}
  18931. \caption{Output of \code{lower\_casts} on the example shown in
  18932. figure~\ref{fig:map-bang}.}
  18933. \label{fig:map-bang-lower-cast}
  18934. \end{figure}
  18935. A cast from one function type to another function type is accomplished
  18936. by generating a \code{lambda} whose parameter and return types match
  18937. the target function type. The body of the \code{lambda} should cast
  18938. the parameters from the target type to the source type. (Yes,
  18939. backward! Functions are contravariant\index{subject}{contravariant}
  18940. in the parameters.). Afterward, call the underlying function and then
  18941. cast the result from the source return type to the target return type.
  18942. Figure~\ref{fig:map-lower-cast} shows the output of the
  18943. \code{lower\_casts} pass on the \code{map} example give in
  18944. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  18945. call to \code{map} is wrapped in a \code{lambda}.
  18946. \begin{figure}[tbp]
  18947. \begin{tcolorbox}[colback=white]
  18948. {\if\edition\racketEd
  18949. \begin{lstlisting}
  18950. (define (map [f : (Integer -> Integer)]
  18951. [v : (Vector Integer Integer)])
  18952. : (Vector Integer Integer)
  18953. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18954. (define (inc [x : Any]) : Any
  18955. (inject (+ (project x Integer) 1) Integer))
  18956. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  18957. (project (inc (inject x9 Integer)) Integer))
  18958. (vector 0 41)) 1)
  18959. \end{lstlisting}
  18960. \fi}
  18961. {\if\edition\pythonEd
  18962. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  18963. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18964. return (f(v[0]), f(v[1]),)
  18965. def inc(x : any) -> any:
  18966. return inject((project(x, int) + 1), int)
  18967. def main() -> int:
  18968. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  18969. print(t[1])
  18970. return 0
  18971. \end{lstlisting}
  18972. \fi}
  18973. \end{tcolorbox}
  18974. \caption{Output of \code{lower\_casts} on the example shown in
  18975. figure~\ref{fig:gradual-map}.}
  18976. \label{fig:map-lower-cast}
  18977. \end{figure}
  18978. \section{Differentiate Proxies}
  18979. \label{sec:differentiate-proxies}
  18980. So far, the responsibility of differentiating tuples and tuple proxies
  18981. has been the job of the interpreter.
  18982. %
  18983. \racket{For example, the interpreter for \LangCast{} implements
  18984. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  18985. figure~\ref{fig:guarded-tuple}.}
  18986. %
  18987. In the \code{differentiate\_proxies} pass we shift this responsibility
  18988. to the generated code.
  18989. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  18990. we used the type \TUPLETYPENAME{} for both
  18991. real tuples and tuple proxies.
  18992. \python{Similarly, we use the type \code{list} for both arrays and
  18993. array proxies.}
  18994. In \LangPVec{} we return the
  18995. \TUPLETYPENAME{} type to its original
  18996. meaning, as the type of just tuples, and we introduce a new type,
  18997. \PTUPLETYNAME{}, whose values
  18998. can be either real tuples or tuple
  18999. proxies.
  19000. %
  19001. {\if\edition\pythonEd
  19002. Likewise, we return the
  19003. \ARRAYTYPENAME{} type to its original
  19004. meaning, as the type of arrays, and we introduce a new type,
  19005. \PARRAYTYNAME{}, whose values
  19006. can be either arrays or array proxies.
  19007. These new types come with a suite of new primitive operations.
  19008. \fi}
  19009. {\if\edition\racketEd
  19010. A tuple proxy is represented by a tuple containing three things: (1) the
  19011. underlying tuple, (2) a tuple of functions for casting elements that
  19012. are read from the tuple, and (3) a tuple of functions for casting
  19013. values to be written to the tuple. So, we define the following
  19014. abbreviation for the type of a tuple proxy:
  19015. \[
  19016. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  19017. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W) \to \PTUPLETY{T' \ldots})
  19018. \]
  19019. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  19020. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  19021. %
  19022. Next we describe each of the new primitive operations.
  19023. \begin{description}
  19024. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  19025. (\key{PVector} $T \ldots$)]\ \\
  19026. %
  19027. This operation brands a vector as a value of the \code{PVector} type.
  19028. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  19029. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  19030. %
  19031. This operation brands a vector proxy as value of the \code{PVector} type.
  19032. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  19033. \BOOLTY{}] \ \\
  19034. %
  19035. This returns true if the value is a tuple proxy and false if it is a
  19036. real tuple.
  19037. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  19038. (\key{Vector} $T \ldots$)]\ \\
  19039. %
  19040. Assuming that the input is a tuple, this operation returns the
  19041. tuple.
  19042. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  19043. $\to$ \BOOLTY{}]\ \\
  19044. %
  19045. Given a tuple proxy, this operation returns the length of the tuple.
  19046. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  19047. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  19048. %
  19049. Given a tuple proxy, this operation returns the $i$th element of the
  19050. tuple.
  19051. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  19052. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  19053. Given a tuple proxy, this operation writes a value to the $i$th element
  19054. of the tuple.
  19055. \end{description}
  19056. \fi}
  19057. {\if\edition\pythonEd
  19058. %
  19059. A tuple proxy is represented by a tuple containing 1) the underlying
  19060. tuple and 2) a tuple of functions for casting elements that are read
  19061. from the tuple. The \LangPVec{} language includes the following AST
  19062. classes and primitive functions.
  19063. \begin{description}
  19064. \item[\code{InjectTuple}] \ \\
  19065. %
  19066. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  19067. \item[\code{InjectTupleProxy}]\ \\
  19068. %
  19069. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  19070. \item[\code{is\_tuple\_proxy}]\ \\
  19071. %
  19072. This primitive returns true if the value is a tuple proxy and false
  19073. if it is a tuple.
  19074. \item[\code{project\_tuple}]\ \\
  19075. %
  19076. Converts a tuple that is branded as \PTUPLETYNAME{}
  19077. back to a tuple.
  19078. \item[\code{proxy\_tuple\_len}]\ \\
  19079. %
  19080. Given a tuple proxy, returns the length of the underlying tuple.
  19081. \item[\code{proxy\_tuple\_load}]\ \\
  19082. %
  19083. Given a tuple proxy, returns the $i$th element of the underlying
  19084. tuple.
  19085. \end{description}
  19086. An array proxy is represented by a tuple containing 1) the underlying
  19087. array, 2) a function for casting elements that are read from the
  19088. array, and 3) a function for casting elements that are written to the
  19089. array. The \LangPVec{} language includes the following AST classes
  19090. and primitive functions.
  19091. \begin{description}
  19092. \item[\code{InjectList}]\ \\
  19093. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  19094. \item[\code{InjectListProxy}]\ \\
  19095. %
  19096. This AST node brands a array proxy as value of the \PARRAYTYNAME{} type.
  19097. \item[\code{is\_array\_proxy}]\ \\
  19098. %
  19099. Returns true if the value is a array proxy and false if it is an
  19100. array.
  19101. \item[\code{project\_array}]\ \\
  19102. %
  19103. Converts an array that is branded as \PARRAYTYNAME{} back to an
  19104. array.
  19105. \item[\code{proxy\_array\_len}]\ \\
  19106. %
  19107. Given a array proxy, returns the length of the underlying array.
  19108. \item[\code{proxy\_array\_load}]\ \\
  19109. %
  19110. Given a array proxy, returns the $i$th element of the underlying
  19111. array.
  19112. \item[\code{proxy\_array\_store}]\ \\
  19113. %
  19114. Given an array proxy, writes a value to the $i$th element of the
  19115. underlying array.
  19116. \end{description}
  19117. \fi}
  19118. Now we discuss the translation that differentiates tuples and arrays
  19119. from proxies. First, every type annotation in the program is
  19120. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  19121. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  19122. places. For example, we wrap every tuple creation with an
  19123. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  19124. %
  19125. {\if\edition\racketEd
  19126. \begin{minipage}{0.96\textwidth}
  19127. \begin{lstlisting}
  19128. (vector |$e_1 \ldots e_n$|)
  19129. |$\Rightarrow$|
  19130. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  19131. \end{lstlisting}
  19132. \end{minipage}
  19133. \fi}
  19134. {\if\edition\pythonEd
  19135. \begin{lstlisting}
  19136. Tuple(|$e_1, \ldots, e_n$|)
  19137. |$\Rightarrow$|
  19138. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  19139. \end{lstlisting}
  19140. \fi}
  19141. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  19142. AST node that we introduced in the previous
  19143. section does not get injected.
  19144. {\if\edition\racketEd
  19145. \begin{lstlisting}
  19146. (raw-vector |$e_1 \ldots e_n$|)
  19147. |$\Rightarrow$|
  19148. (vector |$e'_1 \ldots e'_n$|)
  19149. \end{lstlisting}
  19150. \fi}
  19151. {\if\edition\pythonEd
  19152. \begin{lstlisting}
  19153. RawTuple(|$e_1, \ldots, e_n$|)
  19154. |$\Rightarrow$|
  19155. Tuple(|$e'_1, \ldots, e'_n$|)
  19156. \end{lstlisting}
  19157. \fi}
  19158. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  19159. translates as follows:
  19160. %
  19161. {\if\edition\racketEd
  19162. \begin{lstlisting}
  19163. (vector-proxy |$e_1~e_2~e_3$|)
  19164. |$\Rightarrow$|
  19165. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  19166. \end{lstlisting}
  19167. \fi}
  19168. {\if\edition\pythonEd
  19169. \begin{lstlisting}
  19170. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  19171. |$\Rightarrow$|
  19172. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  19173. \end{lstlisting}
  19174. \fi}
  19175. We translate the element access operations into conditional
  19176. expressions that check whether the value is a proxy and then dispatch
  19177. to either the appropriate proxy tuple operation or the regular tuple
  19178. operation.
  19179. {\if\edition\racketEd
  19180. \begin{lstlisting}
  19181. (vector-ref |$e_1$| |$i$|)
  19182. |$\Rightarrow$|
  19183. (let ([|$v~e_1$|])
  19184. (if (proxy? |$v$|)
  19185. (proxy-vector-ref |$v$| |$i$|)
  19186. (vector-ref (project-vector |$v$|) |$i$|)
  19187. \end{lstlisting}
  19188. \fi}
  19189. %
  19190. Note that in the branch for a tuple, we must apply
  19191. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  19192. from the tuple.
  19193. The translation of array operations is similar to the ones for tuples.
  19194. \section{Reveal Casts}
  19195. \label{sec:reveal-casts-gradual}
  19196. {\if\edition\racketEd
  19197. Recall that the \code{reveal\_casts} pass
  19198. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  19199. \code{Inject} and \code{Project} into lower-level operations.
  19200. %
  19201. In particular, \code{Project} turns into a conditional expression that
  19202. inspects the tag and retrieves the underlying value. Here we need to
  19203. augment the translation of \code{Project} to handle the situation in which
  19204. the target type is \code{PVector}. Instead of using
  19205. \code{vector-length} we need to use \code{proxy-vector-length}.
  19206. \begin{lstlisting}
  19207. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  19208. |$\Rightarrow$|
  19209. (let |$\itm{tmp}$| |$e'$|
  19210. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  19211. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  19212. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  19213. (exit)))
  19214. \end{lstlisting}
  19215. \fi}
  19216. %
  19217. {\if\edition\pythonEd
  19218. Recall that the $\itm{tagof}$ function determines the bits used to
  19219. identify values of different types and it is used in the \code{reveal\_casts}
  19220. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  19221. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ is
  19222. decimal), just like the tuple and array types.
  19223. \fi}
  19224. %
  19225. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  19226. \section{Closure Conversion}
  19227. \label{sec:closure-conversion-gradual}
  19228. The auxiliary function that translates type annotations needs to be
  19229. updated to handle the \PTUPLETYNAME{}
  19230. \racket{type}\python{and \PARRAYTYNAME{} types}.
  19231. %
  19232. Otherwise, the only other changes are adding cases that copy the new
  19233. AST nodes.
  19234. \section{Select Instructions}
  19235. \label{sec:select-instructions-gradual}
  19236. Recall that the \code{select\_instructions} pass is responsible for
  19237. lowering the primitive operations into x86 instructions. So, we need
  19238. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  19239. to x86. To do so, the first question we need to answer is how to
  19240. differentiate between tuple and tuples proxies\python{, and likewise for
  19241. arrays and array proxies}. We need just one bit to accomplish this;
  19242. we use the bit in position $63$ of the 64-bit tag at the front of
  19243. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  19244. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  19245. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  19246. it that way.
  19247. {\if\edition\racketEd
  19248. \begin{lstlisting}
  19249. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  19250. |$\Rightarrow$|
  19251. movq |$e'_1$|, |$\itm{lhs'}$|
  19252. \end{lstlisting}
  19253. \fi}
  19254. {\if\edition\pythonEd
  19255. \begin{lstlisting}
  19256. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  19257. |$\Rightarrow$|
  19258. movq |$e'_1$|, |$\itm{lhs'}$|
  19259. \end{lstlisting}
  19260. \fi}
  19261. \python{The translation for \code{InjectList} is also a move instruction.}
  19262. \noindent On the other hand,
  19263. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  19264. $63$ to $1$.
  19265. %
  19266. {\if\edition\racketEd
  19267. \begin{lstlisting}
  19268. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  19269. |$\Rightarrow$|
  19270. movq |$e'_1$|, %r11
  19271. movq |$(1 << 63)$|, %rax
  19272. orq 0(%r11), %rax
  19273. movq %rax, 0(%r11)
  19274. movq %r11, |$\itm{lhs'}$|
  19275. \end{lstlisting}
  19276. \fi}
  19277. {\if\edition\pythonEd
  19278. \begin{lstlisting}
  19279. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  19280. |$\Rightarrow$|
  19281. movq |$e'_1$|, %r11
  19282. movq |$(1 << 63)$|, %rax
  19283. orq 0(%r11), %rax
  19284. movq %rax, 0(%r11)
  19285. movq %r11, |$\itm{lhs'}$|
  19286. \end{lstlisting}
  19287. \fi}
  19288. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  19289. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  19290. The \racket{\code{proxy?} operation consumes}%
  19291. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  19292. consume}
  19293. the information so carefully stashed away by the injections. It
  19294. isolates bit $63$ to tell whether the value is a proxy.
  19295. %
  19296. {\if\edition\racketEd
  19297. \begin{lstlisting}
  19298. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  19299. |$\Rightarrow$|
  19300. movq |$e_1'$|, %r11
  19301. movq 0(%r11), %rax
  19302. sarq $63, %rax
  19303. andq $1, %rax
  19304. movq %rax, |$\itm{lhs'}$|
  19305. \end{lstlisting}
  19306. \fi}%
  19307. %
  19308. {\if\edition\pythonEd
  19309. \begin{lstlisting}
  19310. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  19311. |$\Rightarrow$|
  19312. movq |$e_1'$|, %r11
  19313. movq 0(%r11), %rax
  19314. sarq $63, %rax
  19315. andq $1, %rax
  19316. movq %rax, |$\itm{lhs'}$|
  19317. \end{lstlisting}
  19318. \fi}%
  19319. %
  19320. The \racket{\code{project-vector} operation is}
  19321. \python{\code{project\_tuple} and \code{project\_array} operations are}
  19322. straightforward to translate, so we leave that to the reader.
  19323. Regarding the element access operations for tuples\python{ and arrays}, the
  19324. runtime provides procedures that implement them (they are recursive
  19325. functions!), so here we simply need to translate these tuple
  19326. operations into the appropriate function call. For example, here is
  19327. the translation for
  19328. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  19329. {\if\edition\racketEd
  19330. \begin{minipage}{0.96\textwidth}
  19331. \begin{lstlisting}
  19332. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  19333. |$\Rightarrow$|
  19334. movq |$e_1'$|, %rdi
  19335. movq |$e_2'$|, %rsi
  19336. callq proxy_vector_ref
  19337. movq %rax, |$\itm{lhs'}$|
  19338. \end{lstlisting}
  19339. \end{minipage}
  19340. \fi}
  19341. {\if\edition\pythonEd
  19342. \begin{lstlisting}
  19343. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  19344. |$\Rightarrow$|
  19345. movq |$e_1'$|, %rdi
  19346. movq |$e_2'$|, %rsi
  19347. callq proxy_vector_ref
  19348. movq %rax, |$\itm{lhs'}$|
  19349. \end{lstlisting}
  19350. \fi}
  19351. {\if\edition\pythonEd
  19352. % TODO: revisit the names vecof for python -Jeremy
  19353. We translate
  19354. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  19355. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  19356. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  19357. \fi}
  19358. We have another batch of operations to deal with: those for the
  19359. \CANYTY{} type. Recall that we generate an
  19360. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  19361. there is a element access on something of type \CANYTY{}, and
  19362. similarly for
  19363. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  19364. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  19365. section~\ref{sec:select-Lany} we selected instructions for these
  19366. operations on the basis of the idea that the underlying value was a tuple or
  19367. array. But in the current setting, the underlying value is of type
  19368. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  19369. functions to deal with this:
  19370. \code{proxy\_vector\_ref},
  19371. \code{proxy\_vector\_set}, and
  19372. \code{proxy\_vector\_length}, that inspect bit $62$ of the tag
  19373. to determine whether the value is a proxy, and then
  19374. dispatches to the the appropriate code.
  19375. %
  19376. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  19377. can be translated as follows.
  19378. We begin by projecting the underlying value out of the tagged value and
  19379. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  19380. {\if\edition\racketEd
  19381. \begin{lstlisting}
  19382. (Assign |$\itm{lhs}$| (Prim 'any-vec-ref (list |$e_1$| |$e_2$|)))
  19383. |$\Rightarrow$|
  19384. movq |$\neg 111$|, %rdi
  19385. andq |$e_1'$|, %rdi
  19386. movq |$e_2'$|, %rsi
  19387. callq proxy_vector_ref
  19388. movq %rax, |$\itm{lhs'}$|
  19389. \end{lstlisting}
  19390. \fi}
  19391. {\if\edition\pythonEd
  19392. \begin{lstlisting}
  19393. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  19394. |$\Rightarrow$|
  19395. movq |$\neg 111$|, %rdi
  19396. andq |$e_1'$|, %rdi
  19397. movq |$e_2'$|, %rsi
  19398. callq proxy_vector_ref
  19399. movq %rax, |$\itm{lhs'}$|
  19400. \end{lstlisting}
  19401. \fi}
  19402. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  19403. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  19404. are translated in a similar way. Alternatively, you could generate
  19405. instructions to open-code
  19406. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  19407. and \code{proxy\_vector\_length} functions.
  19408. \begin{exercise}\normalfont\normalsize
  19409. Implement a compiler for the gradually typed \LangGrad{} language by
  19410. extending and adapting your compiler for \LangLam{}. Create ten new
  19411. partially typed test programs. In addition to testing with these
  19412. new programs, test your compiler on all the tests for \LangLam{}
  19413. and for \LangDyn{}.
  19414. %
  19415. \racket{Sometimes you may get a type checking error on the
  19416. \LangDyn{} programs, but you can adapt them by inserting a cast to
  19417. the \CANYTY{} type around each subexpression that has caused a type
  19418. error. Although \LangDyn{} does not have explicit casts, you can
  19419. induce one by wrapping the subexpression \code{e} with a call to
  19420. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  19421. %
  19422. \python{Sometimes you may get a type checking error on the
  19423. \LangDyn{} programs but you can adapt them by inserting a
  19424. temporary variable of type \CANYTY{} that is initialized with the
  19425. troublesome expression.}
  19426. \end{exercise}
  19427. \begin{figure}[p]
  19428. \begin{tcolorbox}[colback=white]
  19429. {\if\edition\racketEd
  19430. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  19431. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19432. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  19433. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  19434. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  19435. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19436. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19437. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  19438. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19439. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19440. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19441. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19442. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19443. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  19444. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19445. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19446. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19447. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19448. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  19449. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  19450. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19451. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19452. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  19453. \path[->,bend left=15] (Lgradual) edge [above] node
  19454. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  19455. \path[->,bend left=15] (Lgradual2) edge [above] node
  19456. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  19457. \path[->,bend left=15] (Lgradual3) edge [above] node
  19458. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  19459. \path[->,bend left=15] (Lgradual4) edge [left] node
  19460. {\ttfamily\footnotesize shrink} (Lgradualr);
  19461. \path[->,bend left=15] (Lgradualr) edge [above] node
  19462. {\ttfamily\footnotesize uniquify} (Lgradualp);
  19463. \path[->,bend right=15] (Lgradualp) edge [above] node
  19464. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  19465. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  19466. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  19467. \path[->,bend right=15] (Llambdapp) edge [above] node
  19468. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  19469. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19470. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  19471. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  19472. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19473. \path[->,bend left=15] (F1-2) edge [above] node
  19474. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19475. \path[->,bend left=15] (F1-3) edge [left] node
  19476. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  19477. \path[->,bend left=15] (F1-4) edge [below] node
  19478. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  19479. \path[->,bend right=15] (F1-5) edge [above] node
  19480. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19481. \path[->,bend right=15] (F1-6) edge [above] node
  19482. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19483. \path[->,bend right=15] (C3-2) edge [right] node
  19484. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19485. \path[->,bend right=15] (x86-2) edge [right] node
  19486. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  19487. \path[->,bend right=15] (x86-2-1) edge [below] node
  19488. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  19489. \path[->,bend right=15] (x86-2-2) edge [right] node
  19490. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  19491. \path[->,bend left=15] (x86-3) edge [above] node
  19492. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19493. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19494. \end{tikzpicture}
  19495. \fi}
  19496. {\if\edition\pythonEd
  19497. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  19498. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  19499. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  19500. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  19501. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  19502. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  19503. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  19504. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  19505. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  19506. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  19507. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  19508. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  19509. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  19510. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  19511. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  19512. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  19513. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  19514. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  19515. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  19516. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  19517. \path[->,bend left=15] (Lgradual) edge [above] node
  19518. {\ttfamily\footnotesize shrink} (Lgradual2);
  19519. \path[->,bend left=15] (Lgradual2) edge [above] node
  19520. {\ttfamily\footnotesize uniquify} (Lgradual3);
  19521. \path[->,bend left=15] (Lgradual3) edge [above] node
  19522. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  19523. \path[->,bend left=15] (Lgradual4) edge [left] node
  19524. {\ttfamily\footnotesize resolve} (Lgradualr);
  19525. \path[->,bend left=15] (Lgradualr) edge [below] node
  19526. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  19527. \path[->,bend right=15] (Lgradualp) edge [above] node
  19528. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  19529. \path[->,bend right=15] (Llambdapp) edge [above] node
  19530. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  19531. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  19532. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  19533. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  19534. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  19535. \path[->,bend left=15] (F1-1) edge [above] node
  19536. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  19537. \path[->,bend left=15] (F1-2) edge [above] node
  19538. {\ttfamily\footnotesize limit\_functions} (F1-3);
  19539. \path[->,bend left=15] (F1-3) edge [right] node
  19540. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  19541. \path[->,bend right=15] (F1-5) edge [above] node
  19542. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  19543. \path[->,bend right=15] (F1-6) edge [above] node
  19544. {\ttfamily\footnotesize explicate\_control} (C3-2);
  19545. \path[->,bend right=15] (C3-2) edge [right] node
  19546. {\ttfamily\footnotesize select\_instructions} (x86-2);
  19547. \path[->,bend right=15] (x86-2) edge [below] node
  19548. {\ttfamily\footnotesize assign\_homes} (x86-3);
  19549. \path[->,bend right=15] (x86-3) edge [below] node
  19550. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  19551. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  19552. \end{tikzpicture}
  19553. \fi}
  19554. \end{tcolorbox}
  19555. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  19556. \label{fig:Lgradual-passes}
  19557. \end{figure}
  19558. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  19559. needed for the compilation of \LangGrad{}.
  19560. \section{Further Reading}
  19561. This chapter just scratches the surface of gradual typing. The basic
  19562. approach described here is missing two key ingredients that one would
  19563. want in a implementation of gradual typing: blame
  19564. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  19565. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  19566. problem addressed by blame tracking is that when a cast on a
  19567. higher-order value fails, it often does so at a point in the program
  19568. that is far removed from the original cast. Blame tracking is a
  19569. technique for propagating extra information through casts and proxies
  19570. so that when a cast fails, the error message can point back to the
  19571. original location of the cast in the source program.
  19572. The problem addressed by space-efficient casts also relates to
  19573. higher-order casts. It turns out that in partially typed programs, a
  19574. function or tuple can flow through a great many casts at runtime. With
  19575. the approach described in this chapter, each cast adds another
  19576. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  19577. considerable space, but it also makes the function calls and tuple
  19578. operations slow. For example, a partially typed version of quicksort
  19579. could, in the worst case, build a chain of proxies of length $O(n)$
  19580. around the tuple, changing the overall time complexity of the
  19581. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  19582. solution to this problem by representing casts using the coercion
  19583. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  19584. long chains of proxies by compressing them into a concise normal
  19585. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  19586. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  19587. the Grift compiler:
  19588. \begin{center}
  19589. \url{https://github.com/Gradual-Typing/Grift}
  19590. \end{center}
  19591. There are also interesting interactions between gradual typing and
  19592. other language features, such as generics, information-flow types, and
  19593. type inference, to name a few. We recommend to the reader the
  19594. online gradual typing bibliography for more material:
  19595. \begin{center}
  19596. \url{http://samth.github.io/gradual-typing-bib/}
  19597. \end{center}
  19598. % TODO: challenge problem:
  19599. % type analysis and type specialization?
  19600. % coercions?
  19601. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  19602. \chapter{Generics}
  19603. \label{ch:Lpoly}
  19604. \index{subject}{parametric polymorphism}
  19605. \index{subject}{generics}
  19606. \setcounter{footnote}{0}
  19607. This chapter studies the compilation of
  19608. generics\index{subject}{generics} (aka parametric
  19609. polymorphism\index{subject}{parametric polymorphism}), compiling the
  19610. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  19611. enable programmers to make code more reusable by parameterizing
  19612. functions and data structures with respect to the types on which they
  19613. operate. For example, figure~\ref{fig:map-poly} revisits the
  19614. \code{map} example and this time gives it a more fitting type. This
  19615. \code{map} function is parameterized with respect to the element type
  19616. of the tuple. The type of \code{map} is the following generic type
  19617. specified by the \code{All} type with parameter \code{T}:
  19618. \if\edition\racketEd
  19619. \begin{lstlisting}
  19620. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  19621. \end{lstlisting}
  19622. \fi
  19623. \if\edition\pythonEd
  19624. \begin{lstlisting}
  19625. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  19626. \end{lstlisting}
  19627. \fi
  19628. %
  19629. The idea is that \code{map} can be used at \emph{all} choices of a
  19630. type for parameter \code{T}. In the example shown in
  19631. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  19632. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  19633. \code{T}, but we could have just as well applied \code{map} to a tuple
  19634. of Booleans.
  19635. %
  19636. A \emph{monomorphic} function is simply one that is not generic.
  19637. %
  19638. We use the term \emph{instantiation} for the process (within the
  19639. language implementation) of turning a generic function into a
  19640. monomorphic one, where the type parameters have been replaced by
  19641. types.
  19642. \if\edition\pythonEd
  19643. %
  19644. In Python, when writing a generic function such as \code{map}, one
  19645. does not explicitly write down its generic type (using \code{All}).
  19646. Instead, the fact that it is generic is implied by the use of type
  19647. variables (such as \code{T}) in the type annotations of its
  19648. parameters.
  19649. %
  19650. \fi
  19651. \begin{figure}[tbp]
  19652. % poly_test_2.rkt
  19653. \begin{tcolorbox}[colback=white]
  19654. \if\edition\racketEd
  19655. \begin{lstlisting}
  19656. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  19657. (define (map f v)
  19658. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19659. (define (inc [x : Integer]) : Integer (+ x 1))
  19660. (vector-ref (map inc (vector 0 41)) 1)
  19661. \end{lstlisting}
  19662. \fi
  19663. \if\edition\pythonEd
  19664. \begin{lstlisting}
  19665. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  19666. return (f(tup[0]), f(tup[1]))
  19667. def add1(x : int) -> int:
  19668. return x + 1
  19669. t = map(add1, (0, 41))
  19670. print(t[1])
  19671. \end{lstlisting}
  19672. \fi
  19673. \end{tcolorbox}
  19674. \caption{A generic version of the \code{map} function.}
  19675. \label{fig:map-poly}
  19676. \end{figure}
  19677. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  19678. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  19679. shows the definition of the abstract syntax.
  19680. %
  19681. \if\edition\racketEd
  19682. We add a second form for function definitions in which a type
  19683. declaration comes before the \code{define}. In the abstract syntax,
  19684. the return type in the \code{Def} is \CANYTY{}, but that should be
  19685. ignored in favor of the return type in the type declaration. (The
  19686. \CANYTY{} comes from using the same parser as discussed in
  19687. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  19688. enables the use of an \code{All} type for a function, thereby making
  19689. it generic.
  19690. \fi
  19691. %
  19692. The grammar for types is extended to include the type of a generic
  19693. (\code{All}) and type variables\python{ (\code{GenericVar} in the
  19694. abstract syntax)}.
  19695. \newcommand{\LpolyGrammarRacket}{
  19696. \begin{array}{lcl}
  19697. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19698. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  19699. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  19700. \end{array}
  19701. }
  19702. \newcommand{\LpolyASTRacket}{
  19703. \begin{array}{lcl}
  19704. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  19705. \Def &::=& \DECL{\Var}{\Type} \\
  19706. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  19707. \end{array}
  19708. }
  19709. \newcommand{\LpolyGrammarPython}{
  19710. \begin{array}{lcl}
  19711. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  19712. \end{array}
  19713. }
  19714. \newcommand{\LpolyASTPython}{
  19715. \begin{array}{lcl}
  19716. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  19717. \MID \key{GenericVar}\LP\Var\RP
  19718. \end{array}
  19719. }
  19720. \begin{figure}[tp]
  19721. \centering
  19722. \begin{tcolorbox}[colback=white]
  19723. \footnotesize
  19724. \if\edition\racketEd
  19725. \[
  19726. \begin{array}{l}
  19727. \gray{\LintGrammarRacket{}} \\ \hline
  19728. \gray{\LvarGrammarRacket{}} \\ \hline
  19729. \gray{\LifGrammarRacket{}} \\ \hline
  19730. \gray{\LwhileGrammarRacket} \\ \hline
  19731. \gray{\LtupGrammarRacket} \\ \hline
  19732. \gray{\LfunGrammarRacket} \\ \hline
  19733. \gray{\LlambdaGrammarRacket} \\ \hline
  19734. \LpolyGrammarRacket \\
  19735. \begin{array}{lcl}
  19736. \LangPoly{} &::=& \Def \ldots ~ \Exp
  19737. \end{array}
  19738. \end{array}
  19739. \]
  19740. \fi
  19741. \if\edition\pythonEd
  19742. \[
  19743. \begin{array}{l}
  19744. \gray{\LintGrammarPython{}} \\ \hline
  19745. \gray{\LvarGrammarPython{}} \\ \hline
  19746. \gray{\LifGrammarPython{}} \\ \hline
  19747. \gray{\LwhileGrammarPython} \\ \hline
  19748. \gray{\LtupGrammarPython} \\ \hline
  19749. \gray{\LfunGrammarPython} \\ \hline
  19750. \gray{\LlambdaGrammarPython} \\\hline
  19751. \LpolyGrammarPython \\
  19752. \begin{array}{lcl}
  19753. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  19754. \end{array}
  19755. \end{array}
  19756. \]
  19757. \fi
  19758. \end{tcolorbox}
  19759. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  19760. (figure~\ref{fig:Llam-concrete-syntax}).}
  19761. \label{fig:Lpoly-concrete-syntax}
  19762. \end{figure}
  19763. \begin{figure}[tp]
  19764. \centering
  19765. \begin{tcolorbox}[colback=white]
  19766. \footnotesize
  19767. \if\edition\racketEd
  19768. \[
  19769. \begin{array}{l}
  19770. \gray{\LintOpAST} \\ \hline
  19771. \gray{\LvarASTRacket{}} \\ \hline
  19772. \gray{\LifASTRacket{}} \\ \hline
  19773. \gray{\LwhileASTRacket{}} \\ \hline
  19774. \gray{\LtupASTRacket{}} \\ \hline
  19775. \gray{\LfunASTRacket} \\ \hline
  19776. \gray{\LlambdaASTRacket} \\ \hline
  19777. \LpolyASTRacket \\
  19778. \begin{array}{lcl}
  19779. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  19780. \end{array}
  19781. \end{array}
  19782. \]
  19783. \fi
  19784. \if\edition\pythonEd
  19785. \[
  19786. \begin{array}{l}
  19787. \gray{\LintASTPython} \\ \hline
  19788. \gray{\LvarASTPython{}} \\ \hline
  19789. \gray{\LifASTPython{}} \\ \hline
  19790. \gray{\LwhileASTPython{}} \\ \hline
  19791. \gray{\LtupASTPython{}} \\ \hline
  19792. \gray{\LfunASTPython} \\ \hline
  19793. \gray{\LlambdaASTPython} \\ \hline
  19794. \LpolyASTPython \\
  19795. \begin{array}{lcl}
  19796. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  19797. \end{array}
  19798. \end{array}
  19799. \]
  19800. \fi
  19801. \end{tcolorbox}
  19802. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  19803. (figure~\ref{fig:Llam-syntax}).}
  19804. \label{fig:Lpoly-syntax}
  19805. \end{figure}
  19806. By including the \code{All} type in the $\Type$ nonterminal of the
  19807. grammar we choose to make generics first class, which has interesting
  19808. repercussions on the compiler.\footnote{The Python \code{typing} library does
  19809. not include syntax for the \code{All} type. It is inferred for functions whose
  19810. type annotations contain type variables.} Many languages with generics, such as
  19811. C++~\citep{stroustrup88:_param_types} and Standard
  19812. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  19813. may be helpful to see an example of first-class generics in action. In
  19814. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  19815. whose parameter is a generic function. Indeed, because the grammar for
  19816. $\Type$ includes the \code{All} type, a generic function may also be
  19817. returned from a function or stored inside a tuple. The body of
  19818. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  19819. and also to an integer, which would not be possible if \code{f} were
  19820. not generic.
  19821. \begin{figure}[tbp]
  19822. \begin{tcolorbox}[colback=white]
  19823. \if\edition\racketEd
  19824. \begin{lstlisting}
  19825. (: apply_twice ((All (U) (U -> U)) -> Integer))
  19826. (define (apply_twice f)
  19827. (if (f #t) (f 42) (f 777)))
  19828. (: id (All (T) (T -> T)))
  19829. (define (id x) x)
  19830. (apply_twice id)
  19831. \end{lstlisting}
  19832. \fi
  19833. \if\edition\pythonEd
  19834. \begin{lstlisting}
  19835. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  19836. if f(True):
  19837. return f(42)
  19838. else:
  19839. return f(777)
  19840. def id(x: T) -> T:
  19841. return x
  19842. print(apply_twice(id))
  19843. \end{lstlisting}
  19844. \fi
  19845. \end{tcolorbox}
  19846. \caption{An example illustrating first-class generics.}
  19847. \label{fig:apply-twice}
  19848. \end{figure}
  19849. The type checker for \LangPoly{} shown in
  19850. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  19851. (compared to \LangLam{}) which we discuss in the following paragraphs.
  19852. \if\edition\pythonEd
  19853. %
  19854. Regarding function definitions, if the type annotations on its
  19855. parameters contain generic variables, then the function is generic and
  19856. therefore its type is an \code{All} type wrapped around a function
  19857. type. Otherwise the function is monomorphic and its type is simply
  19858. a function type.
  19859. %
  19860. \fi
  19861. The type checking of a function application is extended to handle the
  19862. case in which the operator expression is a generic function. In that case
  19863. the type arguments are deduced by matching the type of the parameters
  19864. with the types of the arguments.
  19865. %
  19866. The \code{match\_types} auxiliary function
  19867. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  19868. recursively descending through a parameter type \code{param\_ty} and
  19869. the corresponding argument type \code{arg\_ty}, making sure that they
  19870. are equal except when there is a type parameter in the parameter
  19871. type. Upon encountering a type parameter for the first time, the
  19872. algorithm deduces an association of the type parameter to the
  19873. corresponding part of the argument type. If it is not the first time
  19874. that the type parameter has been encountered, the algorithm looks up
  19875. its deduced type and makes sure that it is equal to the corresponding
  19876. part of the argument type. The return type of the application is the
  19877. return type of the generic function with the type parameters
  19878. replaced by the deduced type arguments, using the
  19879. \code{substitute\_type} auxiliary function, which is also listed in
  19880. figure~\ref{fig:type-check-Lpoly-aux}.
  19881. The type checker extends type equality to handle the \code{All} type.
  19882. This is not quite as simple as for other types, such as function and
  19883. tuple types, because two \code{All} types can be syntactically
  19884. different even though they are equivalent. For example,
  19885. %
  19886. \racket{\code{(All (T) (T -> T))}}
  19887. \python{\code{All[[T], Callable[[T], T]]}}
  19888. is equivalent to
  19889. \racket{\code{(All (U) (U -> U))}}
  19890. \python{\code{All[[U], Callable[[U], U]]}}.
  19891. %
  19892. Two generic types should be considered equal if they differ only in
  19893. the choice of the names of the type parameters. The definition of type
  19894. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  19895. parameters in one type to match the type parameters of the other type.
  19896. \if\edition\racketEd
  19897. %
  19898. The type checker also ensures that only defined type variables appear
  19899. in type annotations. The \code{check\_well\_formed} function for which
  19900. the definition is shown in figure~\ref{fig:well-formed-types}
  19901. recursively inspects a type, making sure that each type variable has
  19902. been defined.
  19903. %
  19904. \fi
  19905. \begin{figure}[tbp]
  19906. \begin{tcolorbox}[colback=white]
  19907. \if\edition\racketEd
  19908. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  19909. (define type-check-poly-class
  19910. (class type-check-Llambda-class
  19911. (super-new)
  19912. (inherit check-type-equal?)
  19913. (define/override (type-check-apply env e1 es)
  19914. (define-values (e^ ty) ((type-check-exp env) e1))
  19915. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  19916. ((type-check-exp env) e)))
  19917. (match ty
  19918. [`(,ty^* ... -> ,rt)
  19919. (for ([arg-ty ty*] [param-ty ty^*])
  19920. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  19921. (values e^ es^ rt)]
  19922. [`(All ,xs (,tys ... -> ,rt))
  19923. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  19924. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  19925. (match_types env^^ param-ty arg-ty)))
  19926. (define targs
  19927. (for/list ([x xs])
  19928. (match (dict-ref env^^ x (lambda () #f))
  19929. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  19930. x (Apply e1 es))]
  19931. [ty ty])))
  19932. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  19933. [else (error 'type-check "expected a function, not ~a" ty)]))
  19934. (define/override ((type-check-exp env) e)
  19935. (match e
  19936. [(Lambda `([,xs : ,Ts] ...) rT body)
  19937. (for ([T Ts]) ((check_well_formed env) T))
  19938. ((check_well_formed env) rT)
  19939. ((super type-check-exp env) e)]
  19940. [(HasType e1 ty)
  19941. ((check_well_formed env) ty)
  19942. ((super type-check-exp env) e)]
  19943. [else ((super type-check-exp env) e)]))
  19944. (define/override ((type-check-def env) d)
  19945. (verbose 'type-check "poly/def" d)
  19946. (match d
  19947. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  19948. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  19949. (for ([p ps]) ((check_well_formed ts-env) p))
  19950. ((check_well_formed ts-env) rt)
  19951. (define new-env (append ts-env (map cons xs ps) env))
  19952. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19953. (check-type-equal? ty^ rt body)
  19954. (Generic ts (Def f p:t* rt info body^))]
  19955. [else ((super type-check-def env) d)]))
  19956. (define/override (type-check-program p)
  19957. (match p
  19958. [(Program info body)
  19959. (type-check-program (ProgramDefsExp info '() body))]
  19960. [(ProgramDefsExp info ds body)
  19961. (define ds^ (combine-decls-defs ds))
  19962. (define new-env (for/list ([d ds^])
  19963. (cons (def-name d) (fun-def-type d))))
  19964. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  19965. (define-values (body^ ty) ((type-check-exp new-env) body))
  19966. (check-type-equal? ty 'Integer body)
  19967. (ProgramDefsExp info ds^^ body^)]))
  19968. ))
  19969. \end{lstlisting}
  19970. \fi
  19971. \if\edition\pythonEd
  19972. \begin{lstlisting}[basicstyle=\ttfamily\small]
  19973. def type_check_exp(self, e, env):
  19974. match e:
  19975. case Call(Name(f), args) if f in builtin_functions:
  19976. return super().type_check_exp(e, env)
  19977. case Call(func, args):
  19978. func_t = self.type_check_exp(func, env)
  19979. func.has_type = func_t
  19980. match func_t:
  19981. case AllType(ps, FunctionType(p_tys, rt)):
  19982. for arg in args:
  19983. arg.has_type = self.type_check_exp(arg, env)
  19984. arg_tys = [arg.has_type for arg in args]
  19985. deduced = {}
  19986. for (p, a) in zip(p_tys, arg_tys):
  19987. self.match_types(p, a, deduced, e)
  19988. return self.substitute_type(rt, deduced)
  19989. case _:
  19990. return super().type_check_exp(e, env)
  19991. case _:
  19992. return super().type_check_exp(e, env)
  19993. def type_check(self, p):
  19994. match p:
  19995. case Module(body):
  19996. env = {}
  19997. for s in body:
  19998. match s:
  19999. case FunctionDef(name, params, bod, dl, returns, comment):
  20000. params_t = [t for (x,t) in params]
  20001. ty_params = set()
  20002. for t in params_t:
  20003. ty_params |$\mid$|= self.generic_variables(t)
  20004. ty = FunctionType(params_t, returns)
  20005. if len(ty_params) > 0:
  20006. ty = AllType(list(ty_params), ty)
  20007. env[name] = ty
  20008. self.check_stmts(body, IntType(), env)
  20009. case _:
  20010. raise Exception('type_check: unexpected ' + repr(p))
  20011. \end{lstlisting}
  20012. \fi
  20013. \end{tcolorbox}
  20014. \caption{Type checker for the \LangPoly{} language.}
  20015. \label{fig:type-check-Lpoly}
  20016. \end{figure}
  20017. \begin{figure}[tbp]
  20018. \begin{tcolorbox}[colback=white]
  20019. \if\edition\racketEd
  20020. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20021. (define/override (type-equal? t1 t2)
  20022. (match* (t1 t2)
  20023. [(`(All ,xs ,T1) `(All ,ys ,T2))
  20024. (define env (map cons xs ys))
  20025. (type-equal? (substitute_type env T1) T2)]
  20026. [(other wise)
  20027. (super type-equal? t1 t2)]))
  20028. (define/public (match_types env pt at)
  20029. (match* (pt at)
  20030. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  20031. [('Void 'Void) env] [('Any 'Any) env]
  20032. [(`(Vector ,pts ...) `(Vector ,ats ...))
  20033. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  20034. (match_types env^ pt1 at1))]
  20035. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  20036. (define env^ (match_types env prt art))
  20037. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  20038. (match_types env^^ pt1 at1))]
  20039. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  20040. (define env^ (append (map cons pxs axs) env))
  20041. (match_types env^ pt1 at1)]
  20042. [((? symbol? x) at)
  20043. (match (dict-ref env x (lambda () #f))
  20044. [#f (error 'type-check "undefined type variable ~a" x)]
  20045. ['Type (cons (cons x at) env)]
  20046. [t^ (check-type-equal? at t^ 'matching) env])]
  20047. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  20048. (define/public (substitute_type env pt)
  20049. (match pt
  20050. ['Integer 'Integer] ['Boolean 'Boolean]
  20051. ['Void 'Void] ['Any 'Any]
  20052. [`(Vector ,ts ...)
  20053. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  20054. [`(,ts ... -> ,rt)
  20055. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  20056. [`(All ,xs ,t)
  20057. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  20058. [(? symbol? x) (dict-ref env x)]
  20059. [else (error 'type-check "expected a type not ~a" pt)]))
  20060. (define/public (combine-decls-defs ds)
  20061. (match ds
  20062. ['() '()]
  20063. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  20064. (unless (equal? name f)
  20065. (error 'type-check "name mismatch, ~a != ~a" name f))
  20066. (match type
  20067. [`(All ,xs (,ps ... -> ,rt))
  20068. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20069. (cons (Generic xs (Def name params^ rt info body))
  20070. (combine-decls-defs ds^))]
  20071. [`(,ps ... -> ,rt)
  20072. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  20073. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  20074. [else (error 'type-check "expected a function type, not ~a" type) ])]
  20075. [`(,(Def f params rt info body) . ,ds^)
  20076. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  20077. \end{lstlisting}
  20078. \fi
  20079. \if\edition\pythonEd
  20080. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20081. def match_types(self, param_ty, arg_ty, deduced, e):
  20082. match (param_ty, arg_ty):
  20083. case (GenericVar(id), _):
  20084. if id in deduced:
  20085. self.check_type_equal(arg_ty, deduced[id], e)
  20086. else:
  20087. deduced[id] = arg_ty
  20088. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  20089. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  20090. new_arg_ty = self.substitute_type(arg_ty, rename)
  20091. self.match_types(ty, new_arg_ty, deduced, e)
  20092. case (TupleType(ps), TupleType(ts)):
  20093. for (p, a) in zip(ps, ts):
  20094. self.match_types(p, a, deduced, e)
  20095. case (ListType(p), ListType(a)):
  20096. self.match_types(p, a, deduced, e)
  20097. case (FunctionType(pps, prt), FunctionType(aps, art)):
  20098. for (pp, ap) in zip(pps, aps):
  20099. self.match_types(pp, ap, deduced, e)
  20100. self.match_types(prt, art, deduced, e)
  20101. case (IntType(), IntType()):
  20102. pass
  20103. case (BoolType(), BoolType()):
  20104. pass
  20105. case _:
  20106. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  20107. def substitute_type(self, ty, var_map):
  20108. match ty:
  20109. case GenericVar(id):
  20110. return var_map[id]
  20111. case AllType(ps, ty):
  20112. new_map = copy.deepcopy(var_map)
  20113. for p in ps:
  20114. new_map[p] = GenericVar(p)
  20115. return AllType(ps, self.substitute_type(ty, new_map))
  20116. case TupleType(ts):
  20117. return TupleType([self.substitute_type(t, var_map) for t in ts])
  20118. case ListType(ty):
  20119. return ListType(self.substitute_type(ty, var_map))
  20120. case FunctionType(pts, rt):
  20121. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  20122. self.substitute_type(rt, var_map))
  20123. case IntType():
  20124. return IntType()
  20125. case BoolType():
  20126. return BoolType()
  20127. case _:
  20128. raise Exception('substitute_type: unexpected ' + repr(ty))
  20129. def check_type_equal(self, t1, t2, e):
  20130. match (t1, t2):
  20131. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  20132. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  20133. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  20134. case (_, _):
  20135. return super().check_type_equal(t1, t2, e)
  20136. \end{lstlisting}
  20137. \fi
  20138. \end{tcolorbox}
  20139. \caption{Auxiliary functions for type checking \LangPoly{}.}
  20140. \label{fig:type-check-Lpoly-aux}
  20141. \end{figure}
  20142. \if\edition\racketEd
  20143. \begin{figure}[tbp]
  20144. \begin{tcolorbox}[colback=white]
  20145. \begin{lstlisting}
  20146. (define/public ((check_well_formed env) ty)
  20147. (match ty
  20148. ['Integer (void)]
  20149. ['Boolean (void)]
  20150. ['Void (void)]
  20151. [(? symbol? a)
  20152. (match (dict-ref env a (lambda () #f))
  20153. ['Type (void)]
  20154. [else (error 'type-check "undefined type variable ~a" a)])]
  20155. [`(Vector ,ts ...)
  20156. (for ([t ts]) ((check_well_formed env) t))]
  20157. [`(,ts ... -> ,t)
  20158. (for ([t ts]) ((check_well_formed env) t))
  20159. ((check_well_formed env) t)]
  20160. [`(All ,xs ,t)
  20161. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20162. ((check_well_formed env^) t)]
  20163. [else (error 'type-check "unrecognized type ~a" ty)]))
  20164. \end{lstlisting}
  20165. \end{tcolorbox}
  20166. \caption{Well-formed types.}
  20167. \label{fig:well-formed-types}
  20168. \end{figure}
  20169. \fi
  20170. % TODO: interpreter for R'_10
  20171. \clearpage
  20172. \section{Compiling Generics}
  20173. \label{sec:compiling-poly}
  20174. Broadly speaking, there are four approaches to compiling generics, as
  20175. follows:
  20176. \begin{description}
  20177. \item[Monomorphization] generates a different version of a generic
  20178. function for each set of type arguments with which it is used,
  20179. producing type-specialized code. This approach results in the most
  20180. efficient code but requires whole-program compilation (no separate
  20181. compilation) and may increase code size. Unfortunately,
  20182. monomorphization is incompatible with first-class generics, because
  20183. it is not always possible to determine which generic functions are
  20184. used with which type arguments during compilation. (It can be done
  20185. at runtime, with just-in-time compilation.) Monomorphization is
  20186. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  20187. generic functions in NESL~\citep{Blelloch:1993aa} and
  20188. ML~\citep{Weeks:2006aa}.
  20189. \item[Uniform representation] generates one version of each generic
  20190. function and requires all values to have a common \emph{boxed} format,
  20191. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  20192. generic and monomorphic code is compiled similarly to code in a
  20193. dynamically typed language (like \LangDyn{}), in which primitive
  20194. operators require their arguments to be projected from \CANYTY{} and
  20195. their results to be injected into \CANYTY{}. (In object-oriented
  20196. languages, the projection is accomplished via virtual method
  20197. dispatch.) The uniform representation approach is compatible with
  20198. separate compilation and with first-class generics. However, it
  20199. produces the least efficient code because it introduces overhead in
  20200. the entire program. This approach is used in
  20201. Java~\citep{Bracha:1998fk},
  20202. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  20203. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  20204. \item[Mixed representation] generates one version of each generic
  20205. function, using a boxed representation for type variables. However,
  20206. monomorphic code is compiled as usual (as in \LangLam{}), and
  20207. conversions are performed at the boundaries between monomorphic code
  20208. and polymorphic code (e.g., when a generic function is instantiated
  20209. and called). This approach is compatible with separate compilation
  20210. and first-class generics and maintains efficiency in monomorphic
  20211. code. The trade-off is increased overhead at the boundary between
  20212. monomorphic and generic code. This approach is used in
  20213. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  20214. Java 5 with the addition of autoboxing.
  20215. \item[Type passing] uses the unboxed representation in both
  20216. monomorphic and generic code. Each generic function is compiled to a
  20217. single function with extra parameters that describe the type
  20218. arguments. The type information is used by the generated code to
  20219. determine how to access the unboxed values at runtime. This approach is
  20220. used in implementation of Napier88~\citep{Morrison:1991aa} and
  20221. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  20222. compilation and first-class generics and maintains the
  20223. efficiency for monomorphic code. There is runtime overhead in
  20224. polymorphic code from dispatching on type information.
  20225. \end{description}
  20226. In this chapter we use the mixed representation approach, partly
  20227. because of its favorable attributes and partly because it is
  20228. straightforward to implement using the tools that we have already
  20229. built to support gradual typing. The work of compiling generic
  20230. functions is performed in two passes, \code{resolve} and
  20231. \code{erase\_types}, that we discuss next. The output of
  20232. \code{erase\_types} is \LangCast{}
  20233. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  20234. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  20235. \section{Resolve Instantiation}
  20236. \label{sec:generic-resolve}
  20237. Recall that the type checker for \LangPoly{} deduces the type
  20238. arguments at call sites to a generic function. The purpose of the
  20239. \code{resolve} pass is to turn this implicit instantiation into an
  20240. explicit one, by adding \code{inst} nodes to the syntax of the
  20241. intermediate language. An \code{inst} node records the mapping of
  20242. type parameters to type arguments. The semantics of the \code{inst}
  20243. node is to instantiate the result of its first argument, a generic
  20244. function, to produce a monomorphic function. However, because the
  20245. interpreter never analyzes type annotations, instantiation can be a
  20246. no-op and simply return the generic function.
  20247. %
  20248. The output language of the \code{resolve} pass is \LangInst{},
  20249. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  20250. \if\edition\racketEd
  20251. The \code{resolve} pass combines the type declaration and polymorphic
  20252. function into a single definition, using the \code{Poly} form, to make
  20253. polymorphic functions more convenient to process in the next pass of the
  20254. compiler.
  20255. \fi
  20256. \newcommand{\LinstASTRacket}{
  20257. \begin{array}{lcl}
  20258. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20259. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  20260. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  20261. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  20262. \end{array}
  20263. }
  20264. \newcommand{\LinstASTPython}{
  20265. \begin{array}{lcl}
  20266. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  20267. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  20268. \end{array}
  20269. }
  20270. \begin{figure}[tp]
  20271. \centering
  20272. \begin{tcolorbox}[colback=white]
  20273. \small
  20274. \if\edition\racketEd
  20275. \[
  20276. \begin{array}{l}
  20277. \gray{\LintOpAST} \\ \hline
  20278. \gray{\LvarASTRacket{}} \\ \hline
  20279. \gray{\LifASTRacket{}} \\ \hline
  20280. \gray{\LwhileASTRacket{}} \\ \hline
  20281. \gray{\LtupASTRacket{}} \\ \hline
  20282. \gray{\LfunASTRacket} \\ \hline
  20283. \gray{\LlambdaASTRacket} \\ \hline
  20284. \LinstASTRacket \\
  20285. \begin{array}{lcl}
  20286. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20287. \end{array}
  20288. \end{array}
  20289. \]
  20290. \fi
  20291. \if\edition\pythonEd
  20292. \[
  20293. \begin{array}{l}
  20294. \gray{\LintASTPython} \\ \hline
  20295. \gray{\LvarASTPython{}} \\ \hline
  20296. \gray{\LifASTPython{}} \\ \hline
  20297. \gray{\LwhileASTPython{}} \\ \hline
  20298. \gray{\LtupASTPython{}} \\ \hline
  20299. \gray{\LfunASTPython} \\ \hline
  20300. \gray{\LlambdaASTPython} \\ \hline
  20301. \LinstASTPython \\
  20302. \begin{array}{lcl}
  20303. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20304. \end{array}
  20305. \end{array}
  20306. \]
  20307. \fi
  20308. \end{tcolorbox}
  20309. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  20310. (figure~\ref{fig:Llam-syntax}).}
  20311. \label{fig:Lpoly-prime-syntax}
  20312. \end{figure}
  20313. The output of the \code{resolve} pass on the generic \code{map}
  20314. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  20315. of \code{map} is wrapped in an \code{inst} node, with the parameter
  20316. \code{T} chosen to be \racket{\code{Integer}} \python{\code{int}}.
  20317. \begin{figure}[tbp]
  20318. % poly_test_2.rkt
  20319. \begin{tcolorbox}[colback=white]
  20320. \if\edition\racketEd
  20321. \begin{lstlisting}
  20322. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  20323. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  20324. (define (inc [x : Integer]) : Integer (+ x 1))
  20325. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20326. (Integer))
  20327. inc (vector 0 41)) 1)
  20328. \end{lstlisting}
  20329. \fi
  20330. \if\edition\pythonEd
  20331. \begin{lstlisting}
  20332. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20333. return (f(tup[0]), f(tup[1]))
  20334. def add1(x : int) -> int:
  20335. return x + 1
  20336. t = inst(map, {T: int})(add1, (0, 41))
  20337. print(t[1])
  20338. \end{lstlisting}
  20339. \fi
  20340. \end{tcolorbox}
  20341. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  20342. \label{fig:map-resolve}
  20343. \end{figure}
  20344. \section{Erase Types}
  20345. \label{sec:erase_types}
  20346. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  20347. represent type variables. For example, figure~\ref{fig:map-erase}
  20348. shows the output of the \code{erase\_types} pass on the generic
  20349. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  20350. type parameter \code{a} are replaced by \CANYTY{}, and the generic
  20351. \code{All} types are removed from the type of \code{map}.
  20352. \begin{figure}[tbp]
  20353. \begin{tcolorbox}[colback=white]
  20354. \if\edition\racketEd
  20355. \begin{lstlisting}
  20356. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  20357. : (Vector Any Any)
  20358. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20359. (define (inc [x : Integer]) : Integer (+ x 1))
  20360. (vector-ref ((cast map
  20361. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20362. ((Integer -> Integer) (Vector Integer Integer)
  20363. -> (Vector Integer Integer)))
  20364. inc (vector 0 41)) 1)
  20365. \end{lstlisting}
  20366. \fi
  20367. \if\edition\pythonEd
  20368. \begin{lstlisting}
  20369. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  20370. return (f(tup[0]), f(tup[1]))
  20371. def add1(x : int) -> int:
  20372. return (x + 1)
  20373. def main() -> int:
  20374. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  20375. print(t[1])
  20376. return 0
  20377. \end{lstlisting}
  20378. {\small
  20379. where\\
  20380. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  20381. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  20382. }
  20383. \fi
  20384. \end{tcolorbox}
  20385. \caption{The generic \code{map} example after type erasure.}
  20386. \label{fig:map-erase}
  20387. \end{figure}
  20388. This process of type erasure creates a challenge at points of
  20389. instantiation. For example, consider the instantiation of
  20390. \code{map} shown in figure~\ref{fig:map-resolve}.
  20391. The type of \code{map} is
  20392. %
  20393. \if\edition\racketEd
  20394. \begin{lstlisting}
  20395. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20396. \end{lstlisting}
  20397. \fi
  20398. \if\edition\pythonEd
  20399. \begin{lstlisting}
  20400. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  20401. \end{lstlisting}
  20402. \fi
  20403. %
  20404. and it is instantiated to
  20405. %
  20406. \if\edition\racketEd
  20407. \begin{lstlisting}
  20408. ((Integer -> Integer) (Vector Integer Integer)
  20409. -> (Vector Integer Integer))
  20410. \end{lstlisting}
  20411. \fi
  20412. \if\edition\pythonEd
  20413. \begin{lstlisting}
  20414. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  20415. \end{lstlisting}
  20416. \fi
  20417. %
  20418. After erasure, the type of \code{map} is
  20419. %
  20420. \if\edition\racketEd
  20421. \begin{lstlisting}
  20422. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  20423. \end{lstlisting}
  20424. \fi
  20425. \if\edition\pythonEd
  20426. \begin{lstlisting}
  20427. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  20428. \end{lstlisting}
  20429. \fi
  20430. %
  20431. but we need to convert it to the instantiated type. This is easy to
  20432. do in the language \LangCast{} with a single \code{cast}. In the
  20433. example shown in figure~\ref{fig:map-erase}, the instantiation of
  20434. \code{map} has been compiled to a \code{cast} from the type of
  20435. \code{map} to the instantiated type. The source and the target type of a
  20436. cast must be consistent (figure~\ref{fig:consistent}), which indeed is
  20437. the case because both the source and target are obtained from the same
  20438. generic type of \code{map}, replacing the type parameters with
  20439. \CANYTY{} in the former and with the deduced type arguments in the
  20440. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  20441. To implement the \code{erase\_types} pass, we first recommend defining
  20442. a recursive function that translates types, named
  20443. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  20444. follows.
  20445. %
  20446. \if\edition\racketEd
  20447. \begin{lstlisting}
  20448. |$T$|
  20449. |$\Rightarrow$|
  20450. Any
  20451. \end{lstlisting}
  20452. \fi
  20453. \if\edition\pythonEd
  20454. \begin{lstlisting}
  20455. GenericVar(|$T$|)
  20456. |$\Rightarrow$|
  20457. Any
  20458. \end{lstlisting}
  20459. \fi
  20460. %
  20461. \noindent The \code{erase\_type} function also removes the generic
  20462. \code{All} types.
  20463. %
  20464. \if\edition\racketEd
  20465. \begin{lstlisting}
  20466. (All |$xs$| |$T_1$|)
  20467. |$\Rightarrow$|
  20468. |$T'_1$|
  20469. \end{lstlisting}
  20470. \fi
  20471. \if\edition\pythonEd
  20472. \begin{lstlisting}
  20473. AllType(|$xs$|, |$T_1$|)
  20474. |$\Rightarrow$|
  20475. |$T'_1$|
  20476. \end{lstlisting}
  20477. \fi
  20478. where $T'_1$ is the result of applying \code{erase\_type} to $T_1$.
  20479. %
  20480. In this compiler pass, apply the \code{erase\_type} function to all
  20481. the type annotations in the program.
  20482. Regarding the translation of expressions, the case for \code{Inst} is
  20483. the interesting one. We translate it into a \code{Cast}, as shown
  20484. next.
  20485. The type of the subexpression $e$ is a generic type of the form
  20486. \racket{$\LP\key{All}~\itm{xs}~T\RP$}
  20487. \python{$\key{AllType}\LP\itm{xs}, T\RP$}. The source type of the
  20488. cast is the erasure of $T$, the type $T_s$.
  20489. %
  20490. \if\edition\racketEd
  20491. %
  20492. The target type $T_t$ is the result of substituting the argument types
  20493. $ts$ for the type parameters $xs$ in $T$ followed by doing type
  20494. erasure.
  20495. %
  20496. \begin{lstlisting}
  20497. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  20498. |$\Rightarrow$|
  20499. (Cast |$e'$| |$T_s$| |$T_t$|)
  20500. \end{lstlisting}
  20501. %
  20502. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  20503. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  20504. \fi
  20505. \if\edition\pythonEd
  20506. %
  20507. The target type $T_t$ is the result of substituting the deduced
  20508. argument types $d$ in $T$ followed by doing type erasure.
  20509. %
  20510. \begin{lstlisting}
  20511. Inst(|$e$|, |$d$|)
  20512. |$\Rightarrow$|
  20513. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  20514. \end{lstlisting}
  20515. %
  20516. where
  20517. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  20518. \fi
  20519. Finally, each generic function is translated to a regular
  20520. function in which type erasure has been applied to all the type
  20521. annotations and the body.
  20522. %% \begin{lstlisting}
  20523. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  20524. %% |$\Rightarrow$|
  20525. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  20526. %% \end{lstlisting}
  20527. \begin{exercise}\normalfont\normalsize
  20528. Implement a compiler for the polymorphic language \LangPoly{} by
  20529. extending and adapting your compiler for \LangGrad{}. Create six new
  20530. test programs that use polymorphic functions. Some of them should
  20531. make use of first-class generics.
  20532. \end{exercise}
  20533. \begin{figure}[tbp]
  20534. \begin{tcolorbox}[colback=white]
  20535. \if\edition\racketEd
  20536. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20537. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  20538. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  20539. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  20540. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  20541. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  20542. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  20543. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  20544. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20545. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20546. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20547. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20548. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20549. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20550. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20551. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20552. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20553. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20554. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20555. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20556. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20557. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20558. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20559. \path[->,bend left=15] (Lpoly) edge [above] node
  20560. {\ttfamily\footnotesize resolve} (Lpolyp);
  20561. \path[->,bend left=15] (Lpolyp) edge [above] node
  20562. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  20563. \path[->,bend left=15] (Lgradualp) edge [above] node
  20564. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20565. \path[->,bend left=15] (Llambdapp) edge [left] node
  20566. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  20567. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  20568. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  20569. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  20570. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  20571. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  20572. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  20573. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20574. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20575. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20576. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20577. \path[->,bend left=15] (F1-1) edge [above] node
  20578. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20579. \path[->,bend left=15] (F1-2) edge [above] node
  20580. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20581. \path[->,bend left=15] (F1-3) edge [left] node
  20582. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20583. \path[->,bend left=15] (F1-4) edge [below] node
  20584. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20585. \path[->,bend right=15] (F1-5) edge [above] node
  20586. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20587. \path[->,bend right=15] (F1-6) edge [above] node
  20588. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20589. \path[->,bend right=15] (C3-2) edge [right] node
  20590. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20591. \path[->,bend right=15] (x86-2) edge [right] node
  20592. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20593. \path[->,bend right=15] (x86-2-1) edge [below] node
  20594. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20595. \path[->,bend right=15] (x86-2-2) edge [right] node
  20596. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20597. \path[->,bend left=15] (x86-3) edge [above] node
  20598. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20599. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20600. \end{tikzpicture}
  20601. \fi
  20602. \if\edition\pythonEd
  20603. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20604. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  20605. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  20606. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  20607. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  20608. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  20609. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  20610. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  20611. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  20612. \node (F1-1) at (0,0) {\large \LangPVec{}};
  20613. \node (F1-2) at (4,0) {\large \LangPVec{}};
  20614. \node (F1-3) at (8,0) {\large \LangPVec{}};
  20615. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  20616. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  20617. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20618. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20619. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20620. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20621. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20622. \path[->,bend left=15] (Lgradual) edge [above] node
  20623. {\ttfamily\footnotesize shrink} (Lgradual2);
  20624. \path[->,bend left=15] (Lgradual2) edge [above] node
  20625. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20626. \path[->,bend left=15] (Lgradual3) edge [above] node
  20627. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20628. \path[->,bend left=15] (Lgradual4) edge [left] node
  20629. {\ttfamily\footnotesize resolve} (Lgradualr);
  20630. \path[->,bend left=15] (Lgradualr) edge [below] node
  20631. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  20632. \path[->,bend right=15] (Llambdapp) edge [above] node
  20633. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20634. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  20635. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20636. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  20637. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20638. \path[->,bend right=15] (F1-1) edge [below] node
  20639. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20640. \path[->,bend right=15] (F1-2) edge [below] node
  20641. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20642. \path[->,bend left=15] (F1-3) edge [above] node
  20643. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20644. \path[->,bend left=15] (F1-5) edge [left] node
  20645. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20646. \path[->,bend left=5] (F1-6) edge [below] node
  20647. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20648. \path[->,bend right=15] (C3-2) edge [right] node
  20649. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20650. \path[->,bend right=15] (x86-2) edge [below] node
  20651. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20652. \path[->,bend right=15] (x86-3) edge [below] node
  20653. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20654. \path[->,bend left=15] (x86-4) edge [above] node
  20655. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20656. \end{tikzpicture}
  20657. \fi
  20658. \end{tcolorbox}
  20659. \caption{Diagram of the passes for \LangPoly{} (generics).}
  20660. \label{fig:Lpoly-passes}
  20661. \end{figure}
  20662. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  20663. needed to compile \LangPoly{}.
  20664. % TODO: challenge problem: specialization of instantiations
  20665. % Further Reading
  20666. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20667. \clearpage
  20668. \appendix
  20669. \chapter{Appendix}
  20670. \setcounter{footnote}{0}
  20671. \if\edition\racketEd
  20672. \section{Interpreters}
  20673. \label{appendix:interp}
  20674. \index{subject}{interpreter}
  20675. We provide interpreters for each of the source languages \LangInt{},
  20676. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  20677. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  20678. intermediate languages \LangCVar{} and \LangCIf{} are in
  20679. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  20680. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  20681. \key{interp.rkt} file.
  20682. \section{Utility Functions}
  20683. \label{appendix:utilities}
  20684. The utility functions described in this section are in the
  20685. \key{utilities.rkt} file of the support code.
  20686. \paragraph{\code{interp-tests}}
  20687. This function runs the compiler passes and the interpreters on each of
  20688. the specified tests to check whether each pass is correct. The
  20689. \key{interp-tests} function has the following parameters:
  20690. \begin{description}
  20691. \item[name (a string)] A name to identify the compiler,
  20692. \item[typechecker] A function of exactly one argument that either
  20693. raises an error using the \code{error} function when it encounters a
  20694. type error or returns \code{\#f} when it encounters a type
  20695. error. If there is no type error, the type checker returns the
  20696. program.
  20697. \item[passes] A list with one entry per pass. An entry is a list
  20698. consisting of four things:
  20699. \begin{enumerate}
  20700. \item a string giving the name of the pass;
  20701. \item the function that implements the pass (a translator from AST
  20702. to AST);
  20703. \item a function that implements the interpreter (a function from
  20704. AST to result value) for the output language; and,
  20705. \item a type checker for the output language. Type checkers for
  20706. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  20707. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  20708. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  20709. type checker entry is optional. The support code does not provide
  20710. type checkers for the x86 languages.
  20711. \end{enumerate}
  20712. \item[source-interp] An interpreter for the source language. The
  20713. interpreters from appendix~\ref{appendix:interp} make a good choice.
  20714. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  20715. \item[tests] A list of test numbers that specifies which tests to
  20716. run (explained next).
  20717. \end{description}
  20718. %
  20719. The \key{interp-tests} function assumes that the subdirectory
  20720. \key{tests} has a collection of Racket programs whose names all start
  20721. with the family name, followed by an underscore and then the test
  20722. number, and ending with the file extension \key{.rkt}. Also, for each test
  20723. program that calls \code{read} one or more times, there is a file with
  20724. the same name except that the file extension is \key{.in}, which
  20725. provides the input for the Racket program. If the test program is
  20726. expected to fail type checking, then there should be an empty file of
  20727. the same name with extension \key{.tyerr}.
  20728. \paragraph{\code{compiler-tests}}
  20729. This function runs the compiler passes to generate x86 (a \key{.s}
  20730. file) and then runs the GNU C compiler (gcc) to generate machine code.
  20731. It runs the machine code and checks that the output is $42$. The
  20732. parameters to the \code{compiler-tests} function are similar to those
  20733. of the \code{interp-tests} function, and they consist of
  20734. \begin{itemize}
  20735. \item a compiler name (a string),
  20736. \item a type checker,
  20737. \item description of the passes,
  20738. \item name of a test-family, and
  20739. \item a list of test numbers.
  20740. \end{itemize}
  20741. \paragraph{\code{compile-file}}
  20742. This function takes a description of the compiler passes (see the
  20743. comment for \key{interp-tests}) and returns a function that, given a
  20744. program file name (a string ending in \key{.rkt}), applies all the
  20745. passes and writes the output to a file whose name is the same as the
  20746. program file name with extension \key{.rkt} replaced by \key{.s}.
  20747. \paragraph{\code{read-program}}
  20748. This function takes a file path and parses that file (it must be a
  20749. Racket program) into an abstract syntax tree.
  20750. \paragraph{\code{parse-program}}
  20751. This function takes an S-expression representation of an abstract
  20752. syntax tree and converts it into the struct-based representation.
  20753. \paragraph{\code{assert}}
  20754. This function takes two parameters, a string (\code{msg}) and Boolean
  20755. (\code{bool}), and displays the message \key{msg} if the Boolean
  20756. \key{bool} is false.
  20757. \paragraph{\code{lookup}}
  20758. % remove discussion of lookup? -Jeremy
  20759. This function takes a key and an alist and returns the first value that is
  20760. associated with the given key, if there is one. If not, an error is
  20761. triggered. The alist may contain both immutable pairs (built with
  20762. \key{cons}) and mutable pairs (built with \key{mcons}).
  20763. %The \key{map2} function ...
  20764. \fi %\racketEd
  20765. \section{x86 Instruction Set Quick Reference}
  20766. \label{sec:x86-quick-reference}
  20767. \index{subject}{x86}
  20768. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  20769. do. We write $A \to B$ to mean that the value of $A$ is written into
  20770. location $B$. Address offsets are given in bytes. The instruction
  20771. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  20772. registers (such as \code{\%rax}), or memory references (such as
  20773. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  20774. reference per instruction. Other operands must be immediates or
  20775. registers.
  20776. \begin{table}[tbp]
  20777. \centering
  20778. \begin{tabular}{l|l}
  20779. \textbf{Instruction} & \textbf{Operation} \\ \hline
  20780. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  20781. \texttt{negq} $A$ & $- A \to A$ \\
  20782. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  20783. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  20784. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  20785. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  20786. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  20787. \texttt{retq} & Pops the return address and jumps to it \\
  20788. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  20789. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  20790. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  20791. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  20792. be an immediate) \\
  20793. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  20794. matches the condition code of the instruction; otherwise go to the
  20795. next instructions. The condition codes are \key{e} for \emph{equal},
  20796. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  20797. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  20798. \texttt{jl} $L$ & \\
  20799. \texttt{jle} $L$ & \\
  20800. \texttt{jg} $L$ & \\
  20801. \texttt{jge} $L$ & \\
  20802. \texttt{jmp} $L$ & Jump to label $L$ \\
  20803. \texttt{movq} $A$, $B$ & $A \to B$ \\
  20804. \texttt{movzbq} $A$, $B$ &
  20805. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  20806. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  20807. and the extra bytes of $B$ are set to zero.} \\
  20808. & \\
  20809. & \\
  20810. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  20811. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  20812. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  20813. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  20814. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  20815. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  20816. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  20817. description of the condition codes. $A$ must be a single byte register
  20818. (e.g., \texttt{al} or \texttt{cl}).} \\
  20819. \texttt{setl} $A$ & \\
  20820. \texttt{setle} $A$ & \\
  20821. \texttt{setg} $A$ & \\
  20822. \texttt{setge} $A$ &
  20823. \end{tabular}
  20824. \vspace{5pt}
  20825. \caption{Quick reference for the x86 instructions used in this book.}
  20826. \label{tab:x86-instr}
  20827. \end{table}
  20828. %% \if\edition\racketEd
  20829. %% \cleardoublepage
  20830. %% \section{Concrete Syntax for Intermediate Languages}
  20831. %% The concrete syntax of \LangAny{} is defined in
  20832. %% figure~\ref{fig:Lany-concrete-syntax}.
  20833. %% \begin{figure}[tp]
  20834. %% \centering
  20835. %% \fbox{
  20836. %% \begin{minipage}{0.97\textwidth}\small
  20837. %% \[
  20838. %% \begin{array}{lcl}
  20839. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  20840. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  20841. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  20842. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  20843. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  20844. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  20845. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  20846. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  20847. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  20848. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  20849. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  20850. %% \MID \LP\key{void?}\;\Exp\RP \\
  20851. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  20852. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  20853. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  20854. %% \end{array}
  20855. %% \]
  20856. %% \end{minipage}
  20857. %% }
  20858. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  20859. %% (figure~\ref{fig:Llam-syntax}).}
  20860. %% \label{fig:Lany-concrete-syntax}
  20861. %% \end{figure}
  20862. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  20863. %% \LangCFun{} is defined in figures~\ref{fig:c0-concrete-syntax},
  20864. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  20865. %% \ref{fig:c3-concrete-syntax}, respectively.
  20866. %% \begin{figure}[tbp]
  20867. %% \fbox{
  20868. %% \begin{minipage}{0.96\textwidth}
  20869. %% \small
  20870. %% \[
  20871. %% \begin{array}{lcl}
  20872. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  20873. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20874. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  20875. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  20876. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  20877. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  20878. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  20879. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  20880. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  20881. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  20882. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  20883. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  20884. %% \end{array}
  20885. %% \]
  20886. %% \end{minipage}
  20887. %% }
  20888. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  20889. %% \label{fig:c2-concrete-syntax}
  20890. %% \end{figure}
  20891. %% \begin{figure}[tp]
  20892. %% \fbox{
  20893. %% \begin{minipage}{0.96\textwidth}
  20894. %% \small
  20895. %% \[
  20896. %% \begin{array}{lcl}
  20897. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  20898. %% \\
  20899. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  20900. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  20901. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  20902. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  20903. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  20904. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  20905. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  20906. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  20907. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  20908. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  20909. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  20910. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  20911. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  20912. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  20913. %% \LangCFunM{} & ::= & \Def\ldots
  20914. %% \end{array}
  20915. %% \]
  20916. %% \end{minipage}
  20917. %% }
  20918. %% \caption{The \LangCFun{} language, extending \LangCVec{} (figure~\ref{fig:c2-concrete-syntax}) with functions.}
  20919. %% \label{fig:c3-concrete-syntax}
  20920. %% \end{figure}
  20921. %% \fi % racketEd
  20922. \backmatter
  20923. \addtocontents{toc}{\vspace{11pt}}
  20924. %% \addtocontents{toc}{\vspace{11pt}}
  20925. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  20926. \nocite{*}\let\bibname\refname
  20927. \addcontentsline{toc}{fmbm}{\refname}
  20928. \printbibliography
  20929. %\printindex{authors}{Author Index}
  20930. \printindex{subject}{Index}
  20931. \end{document}
  20932. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  20933. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  20934. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  20935. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  20936. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  20937. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  20938. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  20939. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  20940. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  20941. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  20942. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  20943. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  20944. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  20945. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  20946. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  20947. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  20948. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  20949. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  20950. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  20951. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  20952. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  20953. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  20954. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  20955. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  20956. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  20957. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  20958. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  20959. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  20960. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  20961. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  20962. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  20963. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  20964. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  20965. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  20966. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  20967. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  20968. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  20969. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  20970. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  20971. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  20972. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  20973. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  20974. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  20975. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  20976. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  20977. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  20978. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  20979. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  20980. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  20981. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  20982. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  20983. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  20984. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  20985. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  20986. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  20987. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  20988. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  20989. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  20990. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  20991. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  20992. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  20993. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  20994. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  20995. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  20996. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  20997. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  20998. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  20999. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21000. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21001. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21002. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21003. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21004. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21005. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21006. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21007. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21008. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21009. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21010. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21011. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith
  21012. % LocalWords: racketEd subparts subpart nonterminal nonterminals
  21013. % LocalWords: pseudocode underapproximation underapproximations
  21014. % LocalWords: semilattices overapproximate incrementing
  21015. % LocalWords: multilanguage