book.tex 829 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816
  1. \documentclass[7x10]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. %
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \usepackage{url}
  19. \definecolor{lightgray}{gray}{1}
  20. \newcommand{\black}[1]{{\color{black} #1}}
  21. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  22. \newcommand{\gray}[1]{{\color{gray} #1}}
  23. \def\racketEd{0}
  24. \def\pythonEd{1}
  25. \def\edition{1}
  26. % material that is specific to the Racket edition of the book
  27. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  28. % would like a command for: \if\edition\racketEd\color{olive}
  29. % and : \fi\color{black}
  30. %\newcommand{\pythonColor}[0]{\color{purple}}
  31. \newcommand{\pythonColor}[0]{}
  32. % material that is specific to the Python edition of the book
  33. \newcommand{\python}[1]{{\if\edition\pythonEd\pythonColor #1\fi}}
  34. \makeatletter
  35. \newcommand{\captionabove}[2][]{%
  36. \vskip-\abovecaptionskip
  37. \vskip+\belowcaptionskip
  38. \ifx\@nnil#1\@nnil
  39. \caption{#2}%
  40. \else
  41. \caption[#1]{#2}%
  42. \fi
  43. \vskip+\abovecaptionskip
  44. \vskip-\belowcaptionskip
  45. }
  46. %% For multiple indices:
  47. %\usepackage{multind} moved this to the file TimesAPriori_MIT.cls. -Jeremy
  48. \makeindex{subject}
  49. %\makeindex{authors}
  50. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  51. \if\edition\racketEd
  52. \lstset{%
  53. language=Lisp,
  54. basicstyle=\ttfamily\small,
  55. morekeywords={lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  56. deletekeywords={read,mapping,vector},
  57. escapechar=|,
  58. columns=flexible,
  59. %moredelim=[is][\color{red}]{~}{~},
  60. showstringspaces=false
  61. }
  62. \fi
  63. \if\edition\pythonEd
  64. \lstset{%
  65. language=Python,
  66. basicstyle=\ttfamily\small,
  67. morekeywords={match,case,bool,int,let,begin,if,else,closure},
  68. deletekeywords={},
  69. escapechar=|,
  70. columns=flexible,
  71. %moredelim=[is][\color{red}]{~}{~},
  72. showstringspaces=false
  73. }
  74. \fi
  75. %%% Any shortcut own defined macros place here
  76. %% sample of author macro:
  77. \input{defs}
  78. \newtheorem{exercise}[theorem]{Exercise}
  79. \numberwithin{theorem}{chapter}
  80. \numberwithin{definition}{chapter}
  81. \numberwithin{equation}{chapter}
  82. % Adjusted settings
  83. \setlength{\columnsep}{4pt}
  84. %% \begingroup
  85. %% \setlength{\intextsep}{0pt}%
  86. %% \setlength{\columnsep}{0pt}%
  87. %% \begin{wrapfigure}{r}{0.5\textwidth}
  88. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  89. %% \caption{Basic layout}
  90. %% \end{wrapfigure}
  91. %% \lipsum[1]
  92. %% \endgroup
  93. \newbox\oiintbox
  94. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  95. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  96. \def\oiint{\copy\oiintbox}
  97. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  98. %\usepackage{showframe}
  99. \def\ShowFrameLinethickness{0.125pt}
  100. \addbibresource{book.bib}
  101. \if\edition\pythonEd
  102. \addbibresource{python.bib}
  103. \fi
  104. \begin{document}
  105. \frontmatter
  106. %\HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  107. \HalfTitle{Essentials of Compilation}
  108. \halftitlepage
  109. \clearemptydoublepage
  110. \Title{Essentials of Compilation}
  111. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  112. %\edition{First Edition}
  113. \BookAuthor{Jeremy G. Siek}
  114. \imprint{The MIT Press\\
  115. Cambridge, Massachusetts\\
  116. London, England}
  117. \begin{copyrightpage}
  118. \textcopyright\ 2023 Jeremy G. Siek \\[2ex]
  119. This work is subject to a Creative Commons CC-BY-ND-NC license. \\[2ex]
  120. Subject to such license, all rights are reserved. \\[2ex]
  121. \includegraphics{CCBY-logo}
  122. The MIT Press would like to thank the anonymous peer reviewers who
  123. provided comments on drafts of this book. The generous work of
  124. academic experts is essential for establishing the authority and
  125. quality of our publications. We acknowledge with gratitude the
  126. contributions of these otherwise uncredited readers.
  127. This book was set in Times LT Std Roman by the author. Printed and
  128. bound in the United States of America.
  129. {\if\edition\racketEd
  130. Library of Congress Cataloging-in-Publication Data\\
  131. \ \\
  132. Names: Siek, Jeremy, author. \\
  133. Title: Essentials of compilation : an incremental approach in Racket / Jeremy G. Siek. \\
  134. Description: Cambridge, Massachusetts : The MIT Press, [2023] | Includes bibliographical references and index. \\
  135. Identifiers: LCCN 2022015399 (print) | LCCN 2022015400 (ebook) | ISBN 9780262047760 (hardcover) | ISBN 9780262373272 (epub) | ISBN 9780262373289 (pdf) \\
  136. Subjects: LCSH: Racket (Computer program language) | Compilers (Computer programs) \\
  137. Classification: LCC QA76.73.R33 S54 2023 (print) | LCC QA76.73.R33 (ebook) | DDC 005.13/3--dc23/eng/20220705 \\
  138. LC record available at https://lccn.loc.gov/2022015399\\
  139. LC ebook record available at https://lccn.loc.gov/2022015400\\
  140. \ \\
  141. \fi}
  142. 10 9 8 7 6 5 4 3 2 1
  143. %% Jeremy G. Siek. Available for free viewing
  144. %% or personal downloading under the
  145. %% \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  146. %% license.
  147. %% Copyright in this monograph has been licensed exclusively to The MIT
  148. %% Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  149. %% version to the public in 2022. All inquiries regarding rights should
  150. %% be addressed to The MIT Press, Rights and Permissions Department.
  151. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  152. %% All rights reserved. No part of this book may be reproduced in any
  153. %% form by any electronic or mechanical means (including photocopying,
  154. %% recording, or information storage and retrieval) without permission in
  155. %% writing from the publisher.
  156. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  157. %% United States of America.
  158. %% Library of Congress Cataloging-in-Publication Data is available.
  159. %% ISBN:
  160. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  161. \end{copyrightpage}
  162. \dedication{This book is dedicated to Katie, my partner in everything,
  163. my children, who grew up during the writing of this book, and the
  164. programming language students at Indiana University, whose
  165. thoughtful questions made this a better book.}
  166. %% \begin{epigraphpage}
  167. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  168. %% \textit{Book Name if any}}
  169. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  170. %% \end{epigraphpage}
  171. \tableofcontents
  172. %\listoffigures
  173. %\listoftables
  174. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  175. \chapter*{Preface}
  176. \addcontentsline{toc}{fmbm}{Preface}
  177. There is a magical moment when a programmer presses the \emph{run}
  178. button and the software begins to execute. Somehow a program written
  179. in a high-level language is running on a computer that is capable only
  180. of shuffling bits. Here we reveal the wizardry that makes that moment
  181. possible. Beginning with the groundbreaking work of Backus and
  182. colleagues in the 1950s, computer scientists developed techniques for
  183. constructing programs called \emph{compilers} that automatically
  184. translate high-level programs into machine code.
  185. We take you on a journey through constructing your own compiler for a
  186. small but powerful language. Along the way we explain the essential
  187. concepts, algorithms, and data structures that underlie compilers. We
  188. develop your understanding of how programs are mapped onto computer
  189. hardware, which is helpful in reasoning about properties at the
  190. junction of hardware and software, such as execution time, software
  191. errors, and security vulnerabilities. For those interested in
  192. pursuing compiler construction as a career, our goal is to provide a
  193. stepping-stone to advanced topics such as just-in-time compilation,
  194. program analysis, and program optimization. For those interested in
  195. designing and implementing programming languages, we connect language
  196. design choices to their impact on the compiler and the generated code.
  197. A compiler is typically organized as a sequence of stages that
  198. progressively translate a program to the code that runs on
  199. hardware. We take this approach to the extreme by partitioning our
  200. compiler into a large number of \emph{nanopasses}, each of which
  201. performs a single task. This enables the testing of each pass in
  202. isolation and focuses our attention, making the compiler far easier to
  203. understand.
  204. The most familiar approach to describing compilers is to dedicate each
  205. chapter to one pass. The problem with that approach is that it
  206. obfuscates how language features motivate design choices in a
  207. compiler. We instead take an \emph{incremental} approach in which we
  208. build a complete compiler in each chapter, starting with a small input
  209. language that includes only arithmetic and variables. We add new
  210. language features in subsequent chapters, extending the compiler as
  211. necessary.
  212. Our choice of language features is designed to elicit fundamental
  213. concepts and algorithms used in compilers.
  214. \begin{itemize}
  215. \item We begin with integer arithmetic and local variables in
  216. chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  217. the fundamental tools of compiler construction: \emph{abstract
  218. syntax trees} and \emph{recursive functions}.
  219. {\if\edition\pythonEd\pythonColor
  220. \item In chapter~\ref{ch:parsing} we learn how to use the Lark
  221. parser framework to create a parser for the language of integer
  222. arithmetic and local variables. We learn about the parsing
  223. algorithms inside Lark, including Earley and LALR(1).
  224. %
  225. \fi}
  226. \item In chapter~\ref{ch:register-allocation-Lvar} we apply
  227. \emph{graph coloring} to assign variables to machine registers.
  228. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  229. motivates an elegant recursive algorithm for translating them into
  230. conditional \code{goto} statements.
  231. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  232. variables}. This elicits the need for \emph{dataflow
  233. analysis} in the register allocator.
  234. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  235. \emph{garbage collection}.
  236. \item Chapter~\ref{ch:Lfun} adds functions as first-class values
  237. without lexical scoping, similar to functions in the C programming
  238. language~\citep{Kernighan:1988nx}. The reader learns about the
  239. procedure call stack and \emph{calling conventions} and how they interact
  240. with register allocation and garbage collection. The chapter also
  241. describes how to generate efficient tail calls.
  242. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  243. scoping, that is, \emph{lambda} expressions. The reader learns about
  244. \emph{closure conversion}, in which lambdas are translated into a
  245. combination of functions and tuples.
  246. % Chapter about classes and objects?
  247. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  248. point the input languages are statically typed. The reader extends
  249. the statically typed language with an \code{Any} type that serves
  250. as a target for compiling the dynamically typed language.
  251. %% {\if\edition\pythonEd\pythonColor
  252. %% \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  253. %% \emph{classes}.
  254. %% \fi}
  255. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type introduced in
  256. chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  257. in which different regions of a program may be static or dynamically
  258. typed. The reader implements runtime support for \emph{proxies} that
  259. allow values to safely move between regions.
  260. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  261. leveraging the \code{Any} type and type casts developed in chapters
  262. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  263. \end{itemize}
  264. There are many language features that we do not include. Our choices
  265. balance the incidental complexity of a feature versus the fundamental
  266. concepts that it exposes. For example, we include tuples and not
  267. records because although they both elicit the study of heap allocation and
  268. garbage collection, records come with more incidental complexity.
  269. Since 2009, drafts of this book have served as the textbook for
  270. sixteen-week compiler courses for upper-level undergraduates and
  271. first-year graduate students at the University of Colorado and Indiana
  272. University.
  273. %
  274. Students come into the course having learned the basics of
  275. programming, data structures and algorithms, and discrete
  276. mathematics.
  277. %
  278. At the beginning of the course, students form groups of two to four
  279. people. The groups complete approximately one chapter every two
  280. weeks, starting with chapter~\ref{ch:Lvar} and including chapters
  281. according to the students interests while respecting the dependencies
  282. between chapters shown in
  283. figure~\ref{fig:chapter-dependences}. Chapter~\ref{ch:Lfun}
  284. (functions) depends on chapter~\ref{ch:Lvec} (tuples) only in the
  285. implementation of efficient tail calls.
  286. %
  287. The last two weeks of the course involve a final project in which
  288. students design and implement a compiler extension of their choosing.
  289. The last few chapters can be used in support of these projects. Many
  290. chapters include a challenge problem that we assign to the graduate
  291. students.
  292. For compiler courses at universities on the quarter system
  293. (about ten weeks in length), we recommend completing the course
  294. through chapter~\ref{ch:Lvec} or chapter~\ref{ch:Lfun} and providing
  295. some scaffolding code to the students for each compiler pass.
  296. %
  297. The course can be adapted to emphasize functional languages by
  298. skipping chapter~\ref{ch:Lwhile} (loops) and including
  299. chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  300. dynamically typed languages by including chapter~\ref{ch:Ldyn}.
  301. %
  302. %% \python{A course that emphasizes object-oriented languages would
  303. %% include Chapter~\ref{ch:Lobject}.}
  304. This book has been used in compiler courses at California Polytechnic
  305. State University, Portland State University, Rose–Hulman Institute of
  306. Technology, University of Freiburg, University of Massachusetts
  307. Lowell, and the University of Vermont.
  308. \begin{figure}[tp]
  309. \begin{tcolorbox}[colback=white]
  310. {\if\edition\racketEd
  311. \begin{tikzpicture}[baseline=(current bounding box.center)]
  312. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  313. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  314. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  315. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  316. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  317. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  318. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  319. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  320. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  321. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  322. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  323. \path[->] (C1) edge [above] node {} (C2);
  324. \path[->] (C2) edge [above] node {} (C3);
  325. \path[->] (C3) edge [above] node {} (C4);
  326. \path[->] (C4) edge [above] node {} (C5);
  327. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  328. \path[->] (C5) edge [above] node {} (C7);
  329. \path[->] (C6) edge [above] node {} (C7);
  330. \path[->] (C4) edge [above] node {} (C8);
  331. \path[->] (C4) edge [above] node {} (C9);
  332. \path[->] (C7) edge [above] node {} (C10);
  333. \path[->] (C8) edge [above] node {} (C10);
  334. \path[->] (C10) edge [above] node {} (C11);
  335. \end{tikzpicture}
  336. \fi}
  337. {\if\edition\pythonEd\pythonColor
  338. \begin{tikzpicture}[baseline=(current bounding box.center)]
  339. \node (Prelim) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  340. \node (Var) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  341. \node (Parse) at (8,1.5) {\small Ch.~\ref{ch:parsing} Parsing};
  342. \node (Reg) at (0,0) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  343. \node (Cond) at (4,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  344. \node (Loop) at (8,0) {\small Ch.~\ref{ch:Lwhile} Loops};
  345. \node (Fun) at (0,-1.5) {\small Ch.~\ref{ch:Lfun} Functions};
  346. \node (Tuple) at (4,-1.5) {\small Ch.~\ref{ch:Lvec} Tuples};
  347. \node (Dyn) at (8,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  348. % \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  349. \node (Lam) at (0,-3) {\small Ch.~\ref{ch:Llambda} Lambda};
  350. \node (Gradual) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  351. \node (Generic) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  352. \path[->] (Prelim) edge [above] node {} (Var);
  353. \path[->] (Var) edge [above] node {} (Reg);
  354. \path[->] (Var) edge [above] node {} (Parse);
  355. \path[->] (Reg) edge [above] node {} (Cond);
  356. \path[->] (Cond) edge [above] node {} (Tuple);
  357. \path[->,style=dotted] (Tuple) edge [above] node {} (Fun);
  358. \path[->] (Cond) edge [above] node {} (Fun);
  359. \path[->] (Tuple) edge [above] node {} (Lam);
  360. \path[->] (Fun) edge [above] node {} (Lam);
  361. \path[->] (Cond) edge [above] node {} (Dyn);
  362. \path[->] (Cond) edge [above] node {} (Loop);
  363. \path[->] (Lam) edge [above] node {} (Gradual);
  364. \path[->] (Dyn) edge [above] node {} (Gradual);
  365. % \path[->] (Dyn) edge [above] node {} (CO);
  366. \path[->] (Gradual) edge [above] node {} (Generic);
  367. \end{tikzpicture}
  368. \fi}
  369. \end{tcolorbox}
  370. \caption{Diagram of chapter dependencies.}
  371. \label{fig:chapter-dependences}
  372. \end{figure}
  373. \racket{We use the \href{https://racket-lang.org/}{Racket} language both for
  374. the implementation of the compiler and for the input language, so the
  375. reader should be proficient with Racket or Scheme. There are many
  376. excellent resources for learning Scheme and
  377. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.}
  378. %
  379. \python{This edition of the book uses \href{https://www.python.org/}{Python}
  380. both for the implementation of the compiler and for the input language, so the
  381. reader should be proficient with Python. There are many
  382. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.}%
  383. %
  384. The support code for this book is in the GitHub repository at
  385. the following location:
  386. \begin{center}\small\texttt
  387. https://github.com/IUCompilerCourse/
  388. \end{center}
  389. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  390. is helpful but not necessary for the reader to have taken a computer
  391. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  392. assembly language that are needed in the compiler.
  393. %
  394. We follow the System V calling
  395. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  396. that we generate works with the runtime system (written in C) when it
  397. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  398. operating systems on Intel hardware.
  399. %
  400. On the Windows operating system, \code{gcc} uses the Microsoft x64
  401. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  402. assembly code that we generate does \emph{not} work with the runtime
  403. system on Windows. One workaround is to use a virtual machine with
  404. Linux as the guest operating system.
  405. \section*{Acknowledgments}
  406. The tradition of compiler construction at Indiana University goes back
  407. to research and courses on programming languages by Daniel Friedman in
  408. the 1970s and 1980s. One of his students, Kent Dybvig, implemented
  409. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  410. compiler for Scheme. Throughout the 1990s and 2000s, Dybvig taught
  411. the compiler course and continued the development of Chez Scheme.
  412. %
  413. The compiler course evolved to incorporate novel pedagogical ideas
  414. while also including elements of real-world compilers. One of
  415. Friedman's ideas was to split the compiler into many small
  416. passes. Another idea, called ``the game,'' was to test the code
  417. generated by each pass using interpreters.
  418. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  419. developed infrastructure to support this approach and evolved the
  420. course to use even smaller
  421. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  422. design decisions in this book are inspired by the assignment
  423. descriptions of \citet{Dybvig:2010aa}. In the mid 2000s, a student of
  424. Dybvig named Abdulaziz Ghuloum observed that the front-to-back
  425. organization of the course made it difficult for students to
  426. understand the rationale for the compiler design. Ghuloum proposed the
  427. incremental approach~\citep{Ghuloum:2006bh} on which this book is
  428. based.
  429. I thank the many students who served as teaching assistants for the
  430. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  431. Swords, and Chris Wailes. I thank Andre Kuhlenschmidt for work on the
  432. garbage collector and x86 interpreter, Michael Vollmer for work on
  433. efficient tail calls, and Michael Vitousek for help with the first
  434. offering of the incremental compiler course at IU.
  435. I thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  436. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  437. Michael Wollowski for teaching courses based on drafts of this book
  438. and for their feedback. I thank the National Science Foundation for
  439. the grants that helped to support this work: Grant Numbers 1518844,
  440. 1763922, and 1814460.
  441. I thank Ronald Garcia for helping me survive Dybvig's compiler
  442. course in the early 2000s and especially for finding the bug that
  443. sent our garbage collector on a wild goose chase!
  444. \mbox{}\\
  445. \noindent Jeremy G. Siek \\
  446. Bloomington, Indiana
  447. \mainmatter
  448. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  449. \chapter{Preliminaries}
  450. \label{ch:trees-recur}
  451. \setcounter{footnote}{0}
  452. In this chapter we introduce the basic tools needed to implement a
  453. compiler. Programs are typically input by a programmer as text, that
  454. is, a sequence of characters. The program-as-text representation is
  455. called \emph{concrete syntax}. We use concrete syntax to concisely
  456. write down and talk about programs. Inside the compiler, we use
  457. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  458. that efficiently supports the operations that the compiler needs to
  459. perform.\index{subject}{concrete syntax}\index{subject}{abstract
  460. syntax}\index{subject}{abstract syntax
  461. tree}\index{subject}{AST}\index{subject}{program}
  462. The process of translating concrete syntax to abstract syntax is
  463. called \emph{parsing}\index{subject}{parsing}\python{\ and is studied in
  464. chapter~\ref{ch:parsing}}.
  465. \racket{This book does not cover the theory and implementation of parsing.
  466. We refer the readers interested in parsing to the thorough treatment
  467. of parsing by \citet{Aho:2006wb}.}%
  468. %
  469. \racket{A parser is provided in the support code for translating from
  470. concrete to abstract syntax.}%
  471. %
  472. \python{For now we use the \code{parse} function in Python's
  473. \code{ast} module to translate from concrete to abstract syntax.}
  474. ASTs can be represented inside the compiler in many different ways,
  475. depending on the programming language used to write the compiler.
  476. %
  477. \racket{We use Racket's
  478. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  479. feature to represent ASTs (section~\ref{sec:ast}).}
  480. %
  481. \python{We use Python classes and objects to represent ASTs, especially the
  482. classes defined in the standard \code{ast} module for the Python
  483. source language.}
  484. %
  485. We use grammars to define the abstract syntax of programming languages
  486. (section~\ref{sec:grammar}) and pattern matching to inspect individual
  487. nodes in an AST (section~\ref{sec:pattern-matching}). We use
  488. recursive functions to construct and deconstruct ASTs
  489. (section~\ref{sec:recursion}). This chapter provides a brief
  490. introduction to these components.
  491. \racket{\index{subject}{struct}}
  492. \python{\index{subject}{class}\index{subject}{object}}
  493. \section{Abstract Syntax Trees}
  494. \label{sec:ast}
  495. Compilers use abstract syntax trees to represent programs because they
  496. often need to ask questions such as, for a given part of a program,
  497. what kind of language feature is it? What are its subparts? Consider
  498. the program on the left and the diagram of its AST on the
  499. right~\eqref{eq:arith-prog}. This program is an addition operation
  500. that has two subparts, a \racket{read}\python{input} operation and a
  501. negation. The negation has another subpart, the integer constant
  502. \code{8}. By using a tree to represent the program, we can easily
  503. follow the links to go from one part of a program to its subparts.
  504. \begin{center}
  505. \begin{minipage}{0.4\textwidth}
  506. {\if\edition\racketEd
  507. \begin{lstlisting}
  508. (+ (read) (- 8))
  509. \end{lstlisting}
  510. \fi}
  511. {\if\edition\pythonEd\pythonColor
  512. \begin{lstlisting}
  513. input_int() + -8
  514. \end{lstlisting}
  515. \fi}
  516. \end{minipage}
  517. \begin{minipage}{0.4\textwidth}
  518. \begin{equation}
  519. \begin{tikzpicture}
  520. \node[draw] (plus) at (0 , 0) {\key{+}};
  521. \node[draw] (read) at (-1, -1) {\racket{\footnotesize\key{read}}\python{\key{input\_int()}}};
  522. \node[draw] (minus) at (1 , -1) {$\key{-}$};
  523. \node[draw] (8) at (1 , -2) {\key{8}};
  524. \draw[->] (plus) to (read);
  525. \draw[->] (plus) to (minus);
  526. \draw[->] (minus) to (8);
  527. \end{tikzpicture}
  528. \label{eq:arith-prog}
  529. \end{equation}
  530. \end{minipage}
  531. \end{center}
  532. We use the standard terminology for trees to describe ASTs: each
  533. rectangle above is called a \emph{node}. The arrows connect a node to its
  534. \emph{children}, which are also nodes. The top-most node is the
  535. \emph{root}. Every node except for the root has a \emph{parent} (the
  536. node of which it is the child). If a node has no children, it is a
  537. \emph{leaf} node; otherwise it is an \emph{internal} node.
  538. \index{subject}{node}
  539. \index{subject}{children}
  540. \index{subject}{root}
  541. \index{subject}{parent}
  542. \index{subject}{leaf}
  543. \index{subject}{internal node}
  544. %% Recall that an \emph{symbolic expression} (S-expression) is either
  545. %% \begin{enumerate}
  546. %% \item an atom, or
  547. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  548. %% where $e_1$ and $e_2$ are each an S-expression.
  549. %% \end{enumerate}
  550. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  551. %% null value \code{'()}, etc. We can create an S-expression in Racket
  552. %% simply by writing a backquote (called a quasi-quote in Racket)
  553. %% followed by the textual representation of the S-expression. It is
  554. %% quite common to use S-expressions to represent a list, such as $a, b
  555. %% ,c$ in the following way:
  556. %% \begin{lstlisting}
  557. %% `(a . (b . (c . ())))
  558. %% \end{lstlisting}
  559. %% Each element of the list is in the first slot of a pair, and the
  560. %% second slot is either the rest of the list or the null value, to mark
  561. %% the end of the list. Such lists are so common that Racket provides
  562. %% special notation for them that removes the need for the periods
  563. %% and so many parenthesis:
  564. %% \begin{lstlisting}
  565. %% `(a b c)
  566. %% \end{lstlisting}
  567. %% The following expression creates an S-expression that represents AST
  568. %% \eqref{eq:arith-prog}.
  569. %% \begin{lstlisting}
  570. %% `(+ (read) (- 8))
  571. %% \end{lstlisting}
  572. %% When using S-expressions to represent ASTs, the convention is to
  573. %% represent each AST node as a list and to put the operation symbol at
  574. %% the front of the list. The rest of the list contains the children. So
  575. %% in the above case, the root AST node has operation \code{`+} and its
  576. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  577. %% diagram \eqref{eq:arith-prog}.
  578. %% To build larger S-expressions one often needs to splice together
  579. %% several smaller S-expressions. Racket provides the comma operator to
  580. %% splice an S-expression into a larger one. For example, instead of
  581. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  582. %% we could have first created an S-expression for AST
  583. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  584. %% S-expression.
  585. %% \begin{lstlisting}
  586. %% (define ast1.4 `(- 8))
  587. %% (define ast1_1 `(+ (read) ,ast1.4))
  588. %% \end{lstlisting}
  589. %% In general, the Racket expression that follows the comma (splice)
  590. %% can be any expression that produces an S-expression.
  591. {\if\edition\racketEd
  592. We define a Racket \code{struct} for each kind of node. For this
  593. chapter we require just two kinds of nodes: one for integer constants
  594. (aka literals\index{subject}{literals})
  595. and one for primitive operations. The following is the \code{struct}
  596. definition for integer constants.\footnote{All the AST structures are
  597. defined in the file \code{utilities.rkt} in the support code.}
  598. \begin{lstlisting}
  599. (struct Int (value))
  600. \end{lstlisting}
  601. An integer node contains just one thing: the integer value.
  602. We establish the convention that \code{struct} names, such
  603. as \code{Int}, are capitalized.
  604. To create an AST node for the integer $8$, we write \INT{8}.
  605. \begin{lstlisting}
  606. (define eight (Int 8))
  607. \end{lstlisting}
  608. We say that the value created by \INT{8} is an
  609. \emph{instance} of the
  610. \code{Int} structure.
  611. The following is the \code{struct} definition for primitive operations.
  612. \begin{lstlisting}
  613. (struct Prim (op args))
  614. \end{lstlisting}
  615. A primitive operation node includes an operator symbol \code{op} and a
  616. list of child arguments called \code{args}. For example, to create an
  617. AST that negates the number $8$, we write the following.
  618. \begin{lstlisting}
  619. (define neg-eight (Prim '- (list eight)))
  620. \end{lstlisting}
  621. Primitive operations may have zero or more children. The \code{read}
  622. operator has zero:
  623. \begin{lstlisting}
  624. (define rd (Prim 'read '()))
  625. \end{lstlisting}
  626. The addition operator has two children:
  627. \begin{lstlisting}
  628. (define ast1_1 (Prim '+ (list rd neg-eight)))
  629. \end{lstlisting}
  630. We have made a design choice regarding the \code{Prim} structure.
  631. Instead of using one structure for many different operations
  632. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  633. structure for each operation, as follows:
  634. \begin{lstlisting}
  635. (struct Read ())
  636. (struct Add (left right))
  637. (struct Neg (value))
  638. \end{lstlisting}
  639. The reason that we choose to use just one structure is that many parts
  640. of the compiler can use the same code for the different primitive
  641. operators, so we might as well just write that code once by using a
  642. single structure.
  643. %
  644. \fi}
  645. {\if\edition\pythonEd\pythonColor
  646. We use a Python \code{class} for each kind of node.
  647. The following is the class definition for
  648. constants (aka literals\index{subject}{literals})
  649. from the Python \code{ast} module.
  650. \begin{lstlisting}
  651. class Constant:
  652. def __init__(self, value):
  653. self.value = value
  654. \end{lstlisting}
  655. An integer constant node includes just one thing: the integer value.
  656. To create an AST node for the integer $8$, we write \INT{8}.
  657. \begin{lstlisting}
  658. eight = Constant(8)
  659. \end{lstlisting}
  660. We say that the value created by \INT{8} is an
  661. \emph{instance} of the \code{Constant} class.
  662. The following is the class definition for unary operators.
  663. \begin{lstlisting}
  664. class UnaryOp:
  665. def __init__(self, op, operand):
  666. self.op = op
  667. self.operand = operand
  668. \end{lstlisting}
  669. The specific operation is specified by the \code{op} parameter. For
  670. example, the class \code{USub} is for unary subtraction.
  671. (More unary operators are introduced in later chapters.) To create an AST that
  672. negates the number $8$, we write the following.
  673. \begin{lstlisting}
  674. neg_eight = UnaryOp(USub(), eight)
  675. \end{lstlisting}
  676. The call to the \code{input\_int} function is represented by the
  677. \code{Call} and \code{Name} classes.
  678. \begin{lstlisting}
  679. class Call:
  680. def __init__(self, func, args):
  681. self.func = func
  682. self.args = args
  683. class Name:
  684. def __init__(self, id):
  685. self.id = id
  686. \end{lstlisting}
  687. To create an AST node that calls \code{input\_int}, we write
  688. \begin{lstlisting}
  689. read = Call(Name('input_int'), [])
  690. \end{lstlisting}
  691. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  692. the \code{BinOp} class for binary operators.
  693. \begin{lstlisting}
  694. class BinOp:
  695. def __init__(self, left, op, right):
  696. self.op = op
  697. self.left = left
  698. self.right = right
  699. \end{lstlisting}
  700. Similar to \code{UnaryOp}, the specific operation is specified by the
  701. \code{op} parameter, which for now is just an instance of the
  702. \code{Add} class. So to create the AST
  703. node that adds negative eight to some user input, we write the following.
  704. \begin{lstlisting}
  705. ast1_1 = BinOp(read, Add(), neg_eight)
  706. \end{lstlisting}
  707. \fi}
  708. To compile a program such as \eqref{eq:arith-prog}, we need to know
  709. that the operation associated with the root node is addition and we
  710. need to be able to access its two
  711. children. \racket{Racket}\python{Python} provides pattern matching to
  712. support these kinds of queries, as we see in
  713. section~\ref{sec:pattern-matching}.
  714. We often write down the concrete syntax of a program even when we
  715. actually have in mind the AST, because the concrete syntax is more
  716. concise. We recommend that you always think of programs as abstract
  717. syntax trees.
  718. \section{Grammars}
  719. \label{sec:grammar}
  720. \index{subject}{integer}
  721. %\index{subject}{constant}
  722. A programming language can be thought of as a \emph{set} of programs.
  723. The set is infinite (that is, one can always create larger programs),
  724. so one cannot simply describe a language by listing all the
  725. programs in the language. Instead we write down a set of rules, a
  726. \emph{context-free grammar}, for building programs. Grammars are often used to
  727. define the concrete syntax of a language, but they can also be used to
  728. describe the abstract syntax. We write our rules in a variant of
  729. Backus-Naur form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  730. \index{subject}{Backus-Naur form}\index{subject}{BNF} As an example,
  731. we describe a small language, named \LangInt{}, that consists of
  732. integers and arithmetic operations.\index{subject}{grammar}
  733. \index{subject}{context-free grammar}
  734. The first grammar rule for the abstract syntax of \LangInt{} says that an
  735. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  736. \begin{equation}
  737. \Exp ::= \INT{\Int} \label{eq:arith-int}
  738. \end{equation}
  739. %
  740. Each rule has a left-hand side and a right-hand side.
  741. If you have an AST node that matches the
  742. right-hand side, then you can categorize it according to the
  743. left-hand side.
  744. %
  745. Symbols in typewriter font, such as \racket{\code{Int}}\python{\code{Constant}},
  746. are \emph{terminal} symbols and must literally appear in the program for the
  747. rule to be applicable.\index{subject}{terminal}
  748. %
  749. Our grammars do not mention \emph{white space}, that is, delimiter
  750. characters like spaces, tabs, and new lines. White space may be
  751. inserted between symbols for disambiguation and to improve
  752. readability. \index{subject}{white space}
  753. %
  754. A name such as $\Exp$ that is defined by the grammar rules is a
  755. \emph{nonterminal}. \index{subject}{nonterminal}
  756. %
  757. The name $\Int$ is also a nonterminal, but instead of defining it with
  758. a grammar rule, we define it with the following explanation. An
  759. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  760. $-$ (for negative integers), such that the sequence of decimals
  761. %
  762. \racket{represents an integer in the range $-2^{62}$ to $2^{62}-1$. This
  763. enables the representation of integers using 63 bits, which simplifies
  764. several aspects of compilation.
  765. %
  766. Thus, these integers correspond to the Racket \texttt{fixnum}
  767. datatype on a 64-bit machine.}
  768. %
  769. \python{represents an integer in the range $-2^{63}$ to $2^{63}-1$. This
  770. enables the representation of integers using 64 bits, which simplifies
  771. several aspects of compilation. In contrast, integers in Python have
  772. unlimited precision, but the techniques needed to handle unlimited
  773. precision fall outside the scope of this book.}
  774. The second grammar rule is the \READOP{} operation, which receives an
  775. input integer from the user of the program.
  776. \begin{equation}
  777. \Exp ::= \READ{} \label{eq:arith-read}
  778. \end{equation}
  779. The third rule categorizes the negation of an $\Exp$ node as an
  780. $\Exp$.
  781. \begin{equation}
  782. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  783. \end{equation}
  784. We can apply these rules to categorize the ASTs that are in the
  785. \LangInt{} language. For example, by rule \eqref{eq:arith-int},
  786. \INT{8} is an $\Exp$, and then by rule \eqref{eq:arith-neg} the
  787. following AST is an $\Exp$.
  788. \begin{center}
  789. \begin{minipage}{0.5\textwidth}
  790. \NEG{\INT{\code{8}}}
  791. \end{minipage}
  792. \begin{minipage}{0.25\textwidth}
  793. \begin{equation}
  794. \begin{tikzpicture}
  795. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  796. \node[draw, circle] (8) at (0, -1.2) {$8$};
  797. \draw[->] (minus) to (8);
  798. \end{tikzpicture}
  799. \label{eq:arith-neg8}
  800. \end{equation}
  801. \end{minipage}
  802. \end{center}
  803. The next two grammar rules are for addition and subtraction expressions:
  804. \begin{align}
  805. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  806. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  807. \end{align}
  808. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  809. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  810. \eqref{eq:arith-read}, and we have already categorized
  811. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  812. to show that
  813. \[
  814. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  815. \]
  816. is an $\Exp$ in the \LangInt{} language.
  817. If you have an AST for which these rules do not apply, then the
  818. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  819. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  820. because there is no rule for the \key{*} operator. Whenever we
  821. define a language with a grammar, the language includes only those
  822. programs that are justified by the grammar rules.
  823. {\if\edition\pythonEd\pythonColor
  824. The language \LangInt{} includes a second nonterminal $\Stmt$ for statements.
  825. There is a statement for printing the value of an expression
  826. \[
  827. \Stmt{} ::= \PRINT{\Exp}
  828. \]
  829. and a statement that evaluates an expression but ignores the result.
  830. \[
  831. \Stmt{} ::= \EXPR{\Exp}
  832. \]
  833. \fi}
  834. {\if\edition\racketEd
  835. The last grammar rule for \LangInt{} states that there is a
  836. \code{Program} node to mark the top of the whole program:
  837. \[
  838. \LangInt{} ::= \PROGRAM{\code{\textquotesingle()}}{\Exp}
  839. \]
  840. The \code{Program} structure is defined as follows:
  841. \begin{lstlisting}
  842. (struct Program (info body))
  843. \end{lstlisting}
  844. where \code{body} is an expression. In further chapters, the \code{info}
  845. part is used to store auxiliary information, but for now it is
  846. just the empty list.
  847. \fi}
  848. {\if\edition\pythonEd\pythonColor
  849. The last grammar rule for \LangInt{} states that there is a
  850. \code{Module} node to mark the top of the whole program:
  851. \[
  852. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  853. \]
  854. The asterisk $*$ indicates a list of the preceding grammar item, in
  855. this case a list of statements.
  856. %
  857. The \code{Module} class is defined as follows:
  858. \begin{lstlisting}
  859. class Module:
  860. def __init__(self, body):
  861. self.body = body
  862. \end{lstlisting}
  863. where \code{body} is a list of statements.
  864. \fi}
  865. It is common to have many grammar rules with the same left-hand side
  866. but different right-hand sides, such as the rules for $\Exp$ in the
  867. grammar of \LangInt{}. As shorthand, a vertical bar can be used to
  868. combine several right-hand sides into a single rule.
  869. The concrete syntax for \LangInt{} is shown in
  870. figure~\ref{fig:r0-concrete-syntax} and the abstract syntax for
  871. \LangInt{} is shown in figure~\ref{fig:r0-syntax}.%
  872. %
  873. \racket{The \code{read-program} function provided in
  874. \code{utilities.rkt} of the support code reads a program from a file
  875. (the sequence of characters in the concrete syntax of Racket) and
  876. parses it into an abstract syntax tree. Refer to the description of
  877. \code{read-program} in appendix~\ref{appendix:utilities} for more
  878. details.}
  879. %
  880. \python{We recommend using the \code{parse} function in Python's
  881. \code{ast} module to convert the concrete syntax into an abstract
  882. syntax tree.}
  883. \newcommand{\LintGrammarRacket}{
  884. \begin{array}{rcl}
  885. \Type &::=& \key{Integer} \\
  886. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  887. \MID \CSUB{\Exp}{\Exp}
  888. \end{array}
  889. }
  890. \newcommand{\LintASTRacket}{
  891. \begin{array}{rcl}
  892. \Type &::=& \key{Integer} \\
  893. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  894. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  895. \end{array}
  896. }
  897. \newcommand{\LintGrammarPython}{
  898. \begin{array}{rcl}
  899. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  900. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  901. \end{array}
  902. }
  903. \newcommand{\LintASTPython}{
  904. \begin{array}{rcl}
  905. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  906. &\MID& \UNIOP{\key{USub()}}{\Exp} \MID \BINOP{\Exp}{\key{Add()}}{\Exp}\\
  907. &\MID& \BINOP{\Exp}{\key{Sub()}}{\Exp}\\
  908. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  909. \end{array}
  910. }
  911. \begin{figure}[tp]
  912. \begin{tcolorbox}[colback=white]
  913. {\if\edition\racketEd
  914. \[
  915. \begin{array}{l}
  916. \LintGrammarRacket \\
  917. \begin{array}{rcl}
  918. \LangInt{} &::=& \Exp
  919. \end{array}
  920. \end{array}
  921. \]
  922. \fi}
  923. {\if\edition\pythonEd\pythonColor
  924. \[
  925. \begin{array}{l}
  926. \LintGrammarPython \\
  927. \begin{array}{rcl}
  928. \LangInt{} &::=& \Stmt^{*}
  929. \end{array}
  930. \end{array}
  931. \]
  932. \fi}
  933. \end{tcolorbox}
  934. \caption{The concrete syntax of \LangInt{}.}
  935. \label{fig:r0-concrete-syntax}
  936. \end{figure}
  937. \begin{figure}[tp]
  938. \begin{tcolorbox}[colback=white]
  939. {\if\edition\racketEd
  940. \[
  941. \begin{array}{l}
  942. \LintASTRacket{} \\
  943. \begin{array}{rcl}
  944. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  945. \end{array}
  946. \end{array}
  947. \]
  948. \fi}
  949. {\if\edition\pythonEd\pythonColor
  950. \[
  951. \begin{array}{l}
  952. \LintASTPython\\
  953. \begin{array}{rcl}
  954. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  955. \end{array}
  956. \end{array}
  957. \]
  958. \fi}
  959. \end{tcolorbox}
  960. \python{
  961. \index{subject}{Constant@\texttt{Constant}}
  962. \index{subject}{UnaryOp@\texttt{UnaryOp}}
  963. \index{subject}{USub@\texttt{USub}}
  964. \index{subject}{inputint@\texttt{input\_int}}
  965. \index{subject}{Call@\texttt{Call}}
  966. \index{subject}{Name@\texttt{Name}}
  967. \index{subject}{BinOp@\texttt{BinOp}}
  968. \index{subject}{Add@\texttt{Add}}
  969. \index{subject}{Sub@\texttt{Sub}}
  970. \index{subject}{print@\texttt{print}}
  971. \index{subject}{Expr@\texttt{Expr}}
  972. \index{subject}{Module@\texttt{Module}}
  973. }
  974. \caption{The abstract syntax of \LangInt{}.}
  975. \label{fig:r0-syntax}
  976. \end{figure}
  977. \section{Pattern Matching}
  978. \label{sec:pattern-matching}
  979. As mentioned in section~\ref{sec:ast}, compilers often need to access
  980. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python}
  981. provides the \texttt{match} feature to access the parts of a value.
  982. Consider the following example: \index{subject}{match} \index{subject}{pattern matching}
  983. \begin{center}
  984. \begin{minipage}{1.0\textwidth}
  985. {\if\edition\racketEd
  986. \begin{lstlisting}
  987. (match ast1_1
  988. [(Prim op (list child1 child2))
  989. (print op)])
  990. \end{lstlisting}
  991. \fi}
  992. {\if\edition\pythonEd\pythonColor
  993. \begin{lstlisting}
  994. match ast1_1:
  995. case BinOp(child1, op, child2):
  996. print(op)
  997. \end{lstlisting}
  998. \fi}
  999. \end{minipage}
  1000. \end{center}
  1001. {\if\edition\racketEd
  1002. %
  1003. In this example, the \texttt{match} form checks whether the AST
  1004. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1005. three pattern variables \texttt{op}, \texttt{child1}, and
  1006. \texttt{child2}. In general, a match clause consists of a
  1007. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1008. recursively defined to be a pattern variable, a structure name
  1009. followed by a pattern for each of the structure's arguments, or an
  1010. S-expression (a symbol, list, etc.). (See chapter 12 of The Racket
  1011. Guide\footnote{See \url{https://docs.racket-lang.org/guide/match.html}.}
  1012. and chapter 9 of The Racket
  1013. Reference\footnote{See \url{https://docs.racket-lang.org/reference/match.html}.}
  1014. for complete descriptions of \code{match}.)
  1015. %
  1016. The body of a match clause may contain arbitrary Racket code. The
  1017. pattern variables can be used in the scope of the body, such as
  1018. \code{op} in \code{(print op)}.
  1019. %
  1020. \fi}
  1021. %
  1022. %
  1023. {\if\edition\pythonEd\pythonColor
  1024. %
  1025. In the example above, the \texttt{match} form checks whether the AST
  1026. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  1027. three pattern variables (\texttt{child1}, \texttt{op}, and
  1028. \texttt{child2}). In general, each \code{case} consists of a
  1029. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  1030. recursively defined to be one of the following: a pattern variable, a
  1031. class name followed by a pattern for each of its constructor's
  1032. arguments, or other literals\index{subject}{literals} such as strings
  1033. or lists.
  1034. %
  1035. The body of each \code{case} may contain arbitrary Python code. The
  1036. pattern variables can be used in the body, such as \code{op} in
  1037. \code{print(op)}.
  1038. %
  1039. \fi}
  1040. A \code{match} form may contain several clauses, as in the following
  1041. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  1042. the AST. The \code{match} proceeds through the clauses in order,
  1043. checking whether the pattern can match the input AST. The body of the
  1044. first clause that matches is executed. The output of \code{leaf} for
  1045. several ASTs is shown on the right side of the following:
  1046. \begin{center}
  1047. \begin{minipage}{0.6\textwidth}
  1048. {\if\edition\racketEd
  1049. \begin{lstlisting}
  1050. (define (leaf arith)
  1051. (match arith
  1052. [(Int n) #t]
  1053. [(Prim 'read '()) #t]
  1054. [(Prim '- (list e1)) #f]
  1055. [(Prim '+ (list e1 e2)) #f]
  1056. [(Prim '- (list e1 e2)) #f]))
  1057. (leaf (Prim 'read '()))
  1058. (leaf (Prim '- (list (Int 8))))
  1059. (leaf (Int 8))
  1060. \end{lstlisting}
  1061. \fi}
  1062. {\if\edition\pythonEd\pythonColor
  1063. \begin{lstlisting}
  1064. def leaf(arith):
  1065. match arith:
  1066. case Constant(n):
  1067. return True
  1068. case Call(Name('input_int'), []):
  1069. return True
  1070. case UnaryOp(USub(), e1):
  1071. return False
  1072. case BinOp(e1, Add(), e2):
  1073. return False
  1074. case BinOp(e1, Sub(), e2):
  1075. return False
  1076. print(leaf(Call(Name('input_int'), [])))
  1077. print(leaf(UnaryOp(USub(), eight)))
  1078. print(leaf(Constant(8)))
  1079. \end{lstlisting}
  1080. \fi}
  1081. \end{minipage}
  1082. \vrule
  1083. \begin{minipage}{0.25\textwidth}
  1084. {\if\edition\racketEd
  1085. \begin{lstlisting}
  1086. #t
  1087. #f
  1088. #t
  1089. \end{lstlisting}
  1090. \fi}
  1091. {\if\edition\pythonEd\pythonColor
  1092. \begin{lstlisting}
  1093. True
  1094. False
  1095. True
  1096. \end{lstlisting}
  1097. \fi}
  1098. \end{minipage}
  1099. \index{subject}{True@\TRUE{}}
  1100. \index{subject}{False@\FALSE{}}
  1101. \end{center}
  1102. When constructing a \code{match} expression, we refer to the grammar
  1103. definition to identify which nonterminal we are expecting to match
  1104. against, and then we make sure that (1) we have one
  1105. \racket{clause}\python{case} for each alternative of that nonterminal
  1106. and (2) the pattern in each \racket{clause}\python{case}
  1107. corresponds to the corresponding right-hand side of a grammar
  1108. rule. For the \code{match} in the \code{leaf} function, we refer to
  1109. the grammar for \LangInt{} shown in figure~\ref{fig:r0-syntax}. The $\Exp$
  1110. nonterminal has five alternatives, so the \code{match} has five
  1111. \racket{clauses}\python{cases}. The pattern in each
  1112. \racket{clause}\python{case} corresponds to the right-hand side of a
  1113. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1114. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1115. translating from grammars to patterns, replace nonterminals such as
  1116. $\Exp$ with pattern variables of your choice (such as \code{e1} and
  1117. \code{e2}).
  1118. \section{Recursive Functions}
  1119. \label{sec:recursion}
  1120. \index{subject}{recursive function}
  1121. Programs are inherently recursive. For example, an expression is often
  1122. made of smaller expressions. Thus, the natural way to process an
  1123. entire program is to use a recursive function. As a first example of
  1124. such a recursive function, we define the function \code{is\_exp} as
  1125. shown in figure~\ref{fig:exp-predicate}, to take an arbitrary
  1126. value and determine whether or not it is an expression in \LangInt{}.
  1127. %
  1128. We say that a function is defined by \emph{structural recursion} if
  1129. it is defined using a sequence of match \racket{clauses}\python{cases}
  1130. that correspond to a grammar and the body of each
  1131. \racket{clause}\python{case} makes a recursive call on each child
  1132. node.\footnote{This principle of structuring code according to the
  1133. data definition is advocated in the book \emph{How to Design
  1134. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1135. second function, named \code{is\_stmt}, that recognizes whether a value
  1136. is a \LangInt{} statement.} \python{Finally, }
  1137. figure~\ref{fig:exp-predicate} \racket{also} contains the definition of
  1138. \code{is\_Lint}, which determines whether an AST is a program in \LangInt{}.
  1139. In general, we can write one recursive function to handle each
  1140. nonterminal in a grammar.\index{subject}{structural recursion} Of the
  1141. two examples at the bottom of the figure, the first is in
  1142. \LangInt{} and the second is not.
  1143. \begin{figure}[tp]
  1144. \begin{tcolorbox}[colback=white]
  1145. {\if\edition\racketEd
  1146. \begin{lstlisting}
  1147. (define (is_exp ast)
  1148. (match ast
  1149. [(Int n) #t]
  1150. [(Prim 'read '()) #t]
  1151. [(Prim '- (list e)) (is_exp e)]
  1152. [(Prim '+ (list e1 e2))
  1153. (and (is_exp e1) (is_exp e2))]
  1154. [(Prim '- (list e1 e2))
  1155. (and (is_exp e1) (is_exp e2))]
  1156. [else #f]))
  1157. (define (is_Lint ast)
  1158. (match ast
  1159. [(Program '() e) (is_exp e)]
  1160. [else #f]))
  1161. (is_Lint (Program '() ast1_1)
  1162. (is_Lint (Program '()
  1163. (Prim '* (list (Prim 'read '())
  1164. (Prim '+ (list (Int 8)))))))
  1165. \end{lstlisting}
  1166. \fi}
  1167. {\if\edition\pythonEd\pythonColor
  1168. \begin{lstlisting}
  1169. def is_exp(e):
  1170. match e:
  1171. case Constant(n):
  1172. return True
  1173. case Call(Name('input_int'), []):
  1174. return True
  1175. case UnaryOp(USub(), e1):
  1176. return is_exp(e1)
  1177. case BinOp(e1, Add(), e2):
  1178. return is_exp(e1) and is_exp(e2)
  1179. case BinOp(e1, Sub(), e2):
  1180. return is_exp(e1) and is_exp(e2)
  1181. case _:
  1182. return False
  1183. def is_stmt(s):
  1184. match s:
  1185. case Expr(Call(Name('print'), [e])):
  1186. return is_exp(e)
  1187. case Expr(e):
  1188. return is_exp(e)
  1189. case _:
  1190. return False
  1191. def is_Lint(p):
  1192. match p:
  1193. case Module(body):
  1194. return all([is_stmt(s) for s in body])
  1195. case _:
  1196. return False
  1197. print(is_Lint(Module([Expr(ast1_1)])))
  1198. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1199. UnaryOp(Add(), Constant(8))))])))
  1200. \end{lstlisting}
  1201. \fi}
  1202. \end{tcolorbox}
  1203. \caption{Example of recursive functions for \LangInt{}. These functions
  1204. recognize whether an AST is in \LangInt{}.}
  1205. \label{fig:exp-predicate}
  1206. \end{figure}
  1207. %% You may be tempted to merge the two functions into one, like this:
  1208. %% \begin{center}
  1209. %% \begin{minipage}{0.5\textwidth}
  1210. %% \begin{lstlisting}
  1211. %% (define (Lint ast)
  1212. %% (match ast
  1213. %% [(Int n) #t]
  1214. %% [(Prim 'read '()) #t]
  1215. %% [(Prim '- (list e)) (Lint e)]
  1216. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1217. %% [(Program '() e) (Lint e)]
  1218. %% [else #f]))
  1219. %% \end{lstlisting}
  1220. %% \end{minipage}
  1221. %% \end{center}
  1222. %% %
  1223. %% Sometimes such a trick will save a few lines of code, especially when
  1224. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1225. %% \emph{not} recommended because it can get you into trouble.
  1226. %% %
  1227. %% For example, the above function is subtly wrong:
  1228. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1229. %% returns true when it should return false.
  1230. \section{Interpreters}
  1231. \label{sec:interp_Lint}
  1232. \index{subject}{interpreter}
  1233. The behavior of a program is defined by the specification of the
  1234. programming language.
  1235. %
  1236. \racket{For example, the Scheme language is defined in the report by
  1237. \citet{SPERBER:2009aa}. The Racket language is defined in its
  1238. reference manual~\citep{plt-tr}.}
  1239. %
  1240. \python{For example, the Python language is defined in the Python
  1241. language reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1242. %
  1243. In this book we use interpreters to specify each language that we
  1244. consider. An interpreter that is designated as the definition of a
  1245. language is called a \emph{definitional
  1246. interpreter}~\citep{reynolds72:_def_interp}.
  1247. \index{subject}{definitional interpreter} We warm up by creating a
  1248. definitional interpreter for the \LangInt{} language. This interpreter
  1249. serves as a second example of structural recursion. The definition of the
  1250. \code{interp\_Lint} function is shown in
  1251. figure~\ref{fig:interp_Lint}.
  1252. %
  1253. \racket{The body of the function is a match on the input program
  1254. followed by a call to the \lstinline{interp_exp} auxiliary function,
  1255. which in turn has one match clause per grammar rule for \LangInt{}
  1256. expressions.}
  1257. %
  1258. \python{The body of the function matches on the \code{Module} AST node
  1259. and then invokes \code{interp\_stmt} on each statement in the
  1260. module. The \code{interp\_stmt} function includes a case for each
  1261. grammar rule of the \Stmt{} nonterminal, and it calls
  1262. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1263. function includes a case for each grammar rule of the \Exp{}
  1264. nonterminal. We use several auxiliary functions such as \code{add64}
  1265. and \code{input\_int} that are defined in the support code for this book.}
  1266. \begin{figure}[tp]
  1267. \begin{tcolorbox}[colback=white]
  1268. {\if\edition\racketEd
  1269. \begin{lstlisting}
  1270. (define (interp_exp e)
  1271. (match e
  1272. [(Int n) n]
  1273. [(Prim 'read '())
  1274. (define r (read))
  1275. (cond [(fixnum? r) r]
  1276. [else (error 'interp_exp "read expected an integer" r)])]
  1277. [(Prim '- (list e))
  1278. (define v (interp_exp e))
  1279. (fx- 0 v)]
  1280. [(Prim '+ (list e1 e2))
  1281. (define v1 (interp_exp e1))
  1282. (define v2 (interp_exp e2))
  1283. (fx+ v1 v2)]
  1284. [(Prim '- (list e1 e2))
  1285. (define v1 (interp_exp e1))
  1286. (define v2 (interp_exp e2))
  1287. (fx- v1 v2)]))
  1288. (define (interp_Lint p)
  1289. (match p
  1290. [(Program '() e) (interp_exp e)]))
  1291. \end{lstlisting}
  1292. \fi}
  1293. {\if\edition\pythonEd\pythonColor
  1294. \begin{lstlisting}
  1295. def interp_exp(e):
  1296. match e:
  1297. case BinOp(left, Add(), right):
  1298. l = interp_exp(left); r = interp_exp(right)
  1299. return add64(l, r)
  1300. case BinOp(left, Sub(), right):
  1301. l = interp_exp(left); r = interp_exp(right)
  1302. return sub64(l, r)
  1303. case UnaryOp(USub(), v):
  1304. return neg64(interp_exp(v))
  1305. case Constant(value):
  1306. return value
  1307. case Call(Name('input_int'), []):
  1308. return input_int()
  1309. def interp_stmt(s):
  1310. match s:
  1311. case Expr(Call(Name('print'), [arg])):
  1312. print(interp_exp(arg))
  1313. case Expr(value):
  1314. interp_exp(value)
  1315. def interp_Lint(p):
  1316. match p:
  1317. case Module(body):
  1318. for s in body:
  1319. interp_stmt(s)
  1320. \end{lstlisting}
  1321. \fi}
  1322. \end{tcolorbox}
  1323. \caption{Interpreter for the \LangInt{} language.}
  1324. \label{fig:interp_Lint}
  1325. \end{figure}
  1326. Let us consider the result of interpreting a few \LangInt{} programs. The
  1327. following program adds two integers:
  1328. {\if\edition\racketEd
  1329. \begin{lstlisting}
  1330. (+ 10 32)
  1331. \end{lstlisting}
  1332. \fi}
  1333. {\if\edition\pythonEd\pythonColor
  1334. \begin{lstlisting}
  1335. print(10 + 32)
  1336. \end{lstlisting}
  1337. \fi}
  1338. %
  1339. \noindent The result is \key{42}, the answer to life, the universe,
  1340. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1341. the Galaxy} by Douglas Adams.}
  1342. %
  1343. We wrote this program in concrete syntax, whereas the parsed
  1344. abstract syntax is
  1345. {\if\edition\racketEd
  1346. \begin{lstlisting}
  1347. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1348. \end{lstlisting}
  1349. \fi}
  1350. {\if\edition\pythonEd\pythonColor
  1351. \begin{lstlisting}
  1352. Module([Expr(Call(Name('print'),
  1353. [BinOp(Constant(10), Add(), Constant(32))]))])
  1354. \end{lstlisting}
  1355. \fi}
  1356. The following program demonstrates that expressions may be nested within
  1357. each other, in this case nesting several additions and negations.
  1358. {\if\edition\racketEd
  1359. \begin{lstlisting}
  1360. (+ 10 (- (+ 12 20)))
  1361. \end{lstlisting}
  1362. \fi}
  1363. {\if\edition\pythonEd\pythonColor
  1364. \begin{lstlisting}
  1365. print(10 + -(12 + 20))
  1366. \end{lstlisting}
  1367. \fi}
  1368. %
  1369. \noindent What is the result of this program?
  1370. {\if\edition\racketEd
  1371. As mentioned previously, the \LangInt{} language does not support
  1372. arbitrarily large integers but only $63$-bit integers, so we
  1373. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1374. in Racket.
  1375. Suppose that
  1376. \[
  1377. n = 999999999999999999
  1378. \]
  1379. which indeed fits in $63$ bits. What happens when we run the
  1380. following program in our interpreter?
  1381. \begin{lstlisting}
  1382. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1383. \end{lstlisting}
  1384. It produces the following error:
  1385. \begin{lstlisting}
  1386. fx+: result is not a fixnum
  1387. \end{lstlisting}
  1388. We establish the convention that if running the definitional
  1389. interpreter on a program produces an error, then the meaning of that
  1390. program is \emph{unspecified}\index{subject}{unspecified behavior} unless the
  1391. error is a \code{trapped-error}. A compiler for the language is under
  1392. no obligation regarding programs with unspecified behavior; it does
  1393. not have to produce an executable, and if it does, that executable can
  1394. do anything. On the other hand, if the error is a
  1395. \code{trapped-error}, then the compiler must produce an executable and
  1396. it is required to report that an error occurred. To signal an error,
  1397. exit with a return code of \code{255}. The interpreters in chapters
  1398. \ref{ch:Ldyn} and \ref{ch:Lgrad} and in section \ref{sec:arrays} use
  1399. \code{trapped-error}.
  1400. \fi}
  1401. % TODO: how to deal with too-large integers in the Python interpreter?
  1402. %% This convention applies to the languages defined in this
  1403. %% book, as a way to simplify the student's task of implementing them,
  1404. %% but this convention is not applicable to all programming languages.
  1405. %%
  1406. The last feature of the \LangInt{} language, the \READOP{} operation,
  1407. prompts the user of the program for an integer. Recall that program
  1408. \eqref{eq:arith-prog} requests an integer input and then subtracts
  1409. \code{8}. So, if we run {\if\edition\racketEd
  1410. \begin{lstlisting}
  1411. (interp_Lint (Program '() ast1_1))
  1412. \end{lstlisting}
  1413. \fi}
  1414. {\if\edition\pythonEd\pythonColor
  1415. \begin{lstlisting}
  1416. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1417. \end{lstlisting}
  1418. \fi}
  1419. \noindent and if the input is \code{50}, the result is \code{42}.
  1420. We include the \READOP{} operation in \LangInt{} so that a clever
  1421. student cannot implement a compiler for \LangInt{} that simply runs
  1422. the interpreter during compilation to obtain the output and then
  1423. generates the trivial code to produce the output.\footnote{Yes, a
  1424. clever student did this in the first instance of this course!}
  1425. The job of a compiler is to translate a program in one language into a
  1426. program in another language so that the output program behaves the
  1427. same way as the input program. This idea is depicted in the
  1428. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1429. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1430. Given a compiler that translates from language $\mathcal{L}_1$ to
  1431. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1432. compiler must translate it into some program $P_2$ such that
  1433. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1434. same input $i$ yields the same output $o$.
  1435. \begin{equation} \label{eq:compile-correct}
  1436. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1437. \node (p1) at (0, 0) {$P_1$};
  1438. \node (p2) at (3, 0) {$P_2$};
  1439. \node (o) at (3, -2.5) {$o$};
  1440. \path[->] (p1) edge [above] node {compile} (p2);
  1441. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1442. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1443. \end{tikzpicture}
  1444. \end{equation}
  1445. \python{We establish the convention that if running the definitional
  1446. interpreter on a program produces an error, then the meaning of that
  1447. program is \emph{unspecified}\index{subject}{unspecified behavior}
  1448. unless the exception raised is a \code{TrappedError}. A compiler for
  1449. the language is under no obligation regarding programs with
  1450. unspecified behavior; it does not have to produce an executable, and
  1451. if it does, that executable can do anything. On the other hand, if
  1452. the error is a \code{TrappedError}, then the compiler must produce
  1453. an executable and it is required to report that an error
  1454. occurred. To signal an error, exit with a return code of \code{255}.
  1455. The interpreters in chapters \ref{ch:Ldyn} and \ref{ch:Lgrad} and in
  1456. section \ref{sec:arrays} use \code{TrappedError}.}
  1457. In the next section we see our first example of a compiler.
  1458. \section{Example Compiler: A Partial Evaluator}
  1459. \label{sec:partial-evaluation}
  1460. In this section we consider a compiler that translates \LangInt{}
  1461. programs into \LangInt{} programs that may be more efficient. The
  1462. compiler eagerly computes the parts of the program that do not depend
  1463. on any inputs, a process known as \emph{partial
  1464. evaluation}~\citep{Jones:1993uq}.\index{subject}{partialevaluation@partial evaluation}
  1465. For example, given the following program
  1466. {\if\edition\racketEd
  1467. \begin{lstlisting}
  1468. (+ (read) (- (+ 5 3)))
  1469. \end{lstlisting}
  1470. \fi}
  1471. {\if\edition\pythonEd\pythonColor
  1472. \begin{lstlisting}
  1473. print(input_int() + -(5 + 3) )
  1474. \end{lstlisting}
  1475. \fi}
  1476. \noindent our compiler translates it into the program
  1477. {\if\edition\racketEd
  1478. \begin{lstlisting}
  1479. (+ (read) -8)
  1480. \end{lstlisting}
  1481. \fi}
  1482. {\if\edition\pythonEd\pythonColor
  1483. \begin{lstlisting}
  1484. print(input_int() + -8)
  1485. \end{lstlisting}
  1486. \fi}
  1487. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1488. evaluator for the \LangInt{} language. The output of the partial evaluator
  1489. is a program in \LangInt{}. In figure~\ref{fig:pe-arith}, the structural
  1490. recursion over $\Exp$ is captured in the \code{pe\_exp} function,
  1491. whereas the code for partially evaluating the negation and addition
  1492. operations is factored into three auxiliary functions:
  1493. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1494. functions is the output of partially evaluating the children.
  1495. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1496. arguments are integers and if they are, perform the appropriate
  1497. arithmetic. Otherwise, they create an AST node for the arithmetic
  1498. operation.
  1499. \begin{figure}[tp]
  1500. \begin{tcolorbox}[colback=white]
  1501. {\if\edition\racketEd
  1502. \begin{lstlisting}
  1503. (define (pe_neg r)
  1504. (match r
  1505. [(Int n) (Int (fx- 0 n))]
  1506. [else (Prim '- (list r))]))
  1507. (define (pe_add r1 r2)
  1508. (match* (r1 r2)
  1509. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1510. [(_ _) (Prim '+ (list r1 r2))]))
  1511. (define (pe_sub r1 r2)
  1512. (match* (r1 r2)
  1513. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1514. [(_ _) (Prim '- (list r1 r2))]))
  1515. (define (pe_exp e)
  1516. (match e
  1517. [(Int n) (Int n)]
  1518. [(Prim 'read '()) (Prim 'read '())]
  1519. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1520. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1521. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1522. (define (pe_Lint p)
  1523. (match p
  1524. [(Program '() e) (Program '() (pe_exp e))]))
  1525. \end{lstlisting}
  1526. \fi}
  1527. {\if\edition\pythonEd\pythonColor
  1528. \begin{lstlisting}
  1529. def pe_neg(r):
  1530. match r:
  1531. case Constant(n):
  1532. return Constant(neg64(n))
  1533. case _:
  1534. return UnaryOp(USub(), r)
  1535. def pe_add(r1, r2):
  1536. match (r1, r2):
  1537. case (Constant(n1), Constant(n2)):
  1538. return Constant(add64(n1, n2))
  1539. case _:
  1540. return BinOp(r1, Add(), r2)
  1541. def pe_sub(r1, r2):
  1542. match (r1, r2):
  1543. case (Constant(n1), Constant(n2)):
  1544. return Constant(sub64(n1, n2))
  1545. case _:
  1546. return BinOp(r1, Sub(), r2)
  1547. def pe_exp(e):
  1548. match e:
  1549. case BinOp(left, Add(), right):
  1550. return pe_add(pe_exp(left), pe_exp(right))
  1551. case BinOp(left, Sub(), right):
  1552. return pe_sub(pe_exp(left), pe_exp(right))
  1553. case UnaryOp(USub(), v):
  1554. return pe_neg(pe_exp(v))
  1555. case Constant(value):
  1556. return e
  1557. case Call(Name('input_int'), []):
  1558. return e
  1559. def pe_stmt(s):
  1560. match s:
  1561. case Expr(Call(Name('print'), [arg])):
  1562. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1563. case Expr(value):
  1564. return Expr(pe_exp(value))
  1565. def pe_P_int(p):
  1566. match p:
  1567. case Module(body):
  1568. new_body = [pe_stmt(s) for s in body]
  1569. return Module(new_body)
  1570. \end{lstlisting}
  1571. \fi}
  1572. \end{tcolorbox}
  1573. \caption{A partial evaluator for \LangInt{}.}
  1574. \label{fig:pe-arith}
  1575. \end{figure}
  1576. To gain some confidence that the partial evaluator is correct, we can
  1577. test whether it produces programs that produce the same result as the
  1578. input programs. That is, we can test whether it satisfies the diagram
  1579. of \eqref{eq:compile-correct}.
  1580. %
  1581. {\if\edition\racketEd
  1582. The following code runs the partial evaluator on several examples and
  1583. tests the output program. The \texttt{parse-program} and
  1584. \texttt{assert} functions are defined in
  1585. appendix~\ref{appendix:utilities}.\\
  1586. \begin{minipage}{1.0\textwidth}
  1587. \begin{lstlisting}
  1588. (define (test_pe p)
  1589. (assert "testing pe_Lint"
  1590. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1591. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1592. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1593. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1594. \end{lstlisting}
  1595. \end{minipage}
  1596. \fi}
  1597. % TODO: python version of testing the PE
  1598. \begin{exercise}\normalfont\normalsize
  1599. Create three programs in the \LangInt{} language and test whether
  1600. partially evaluating them with \code{pe\_Lint} and then
  1601. interpreting them with \code{interp\_Lint} gives the same result
  1602. as directly interpreting them with \code{interp\_Lint}.
  1603. \end{exercise}
  1604. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1605. \chapter{Integers and Variables}
  1606. \label{ch:Lvar}
  1607. \setcounter{footnote}{0}
  1608. This chapter covers compiling a subset of
  1609. \racket{Racket}\python{Python} to x86-64 assembly
  1610. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1611. integer arithmetic and local variables. We often refer to x86-64
  1612. simply as x86. The chapter first describes the \LangVar{} language
  1613. (section~\ref{sec:s0}) and then introduces x86 assembly
  1614. (section~\ref{sec:x86}). Because x86 assembly language is large, we
  1615. discuss only the instructions needed for compiling \LangVar{}. We
  1616. introduce more x86 instructions in subsequent chapters. After
  1617. introducing \LangVar{} and x86, we reflect on their differences and
  1618. create a plan to break down the translation from \LangVar{} to x86
  1619. into a handful of steps (section~\ref{sec:plan-s0-x86}). The rest of
  1620. the chapter gives detailed hints regarding each step. We aim to give
  1621. enough hints that the well-prepared reader, together with a few
  1622. friends, can implement a compiler from \LangVar{} to x86 in a short
  1623. time. To suggest the scale of this first compiler, we note that the
  1624. instructor solution for the \LangVar{} compiler is approximately
  1625. \racket{500}\python{300} lines of code.
  1626. \section{The \LangVar{} Language}
  1627. \label{sec:s0}
  1628. \index{subject}{variable}
  1629. The \LangVar{} language extends the \LangInt{} language with
  1630. variables. The concrete syntax of the \LangVar{} language is defined
  1631. by the grammar presented in figure~\ref{fig:Lvar-concrete-syntax}, and
  1632. the abstract syntax is presented in figure~\ref{fig:Lvar-syntax}. The
  1633. nonterminal \Var{} may be any \racket{Racket}\python{Python}
  1634. identifier. As in \LangInt{}, \READOP{} is a nullary operator,
  1635. \key{-} is a unary operator, and \key{+} is a binary operator.
  1636. Similarly to \LangInt{}, the abstract syntax of \LangVar{} includes the
  1637. \racket{\key{Program} struct}\python{\key{Module} instance} to mark
  1638. the top of the program.
  1639. %% The $\itm{info}$
  1640. %% field of the \key{Program} structure contains an \emph{association
  1641. %% list} (a list of key-value pairs) that is used to communicate
  1642. %% auxiliary data from one compiler pass the next.
  1643. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1644. exhibit several compilation techniques.
  1645. \newcommand{\LvarGrammarRacket}{
  1646. \begin{array}{rcl}
  1647. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1648. \end{array}
  1649. }
  1650. \newcommand{\LvarASTRacket}{
  1651. \begin{array}{rcl}
  1652. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1653. \end{array}
  1654. }
  1655. \newcommand{\LvarGrammarPython}{
  1656. \begin{array}{rcl}
  1657. \Exp &::=& \Var{} \\
  1658. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1659. \end{array}
  1660. }
  1661. \newcommand{\LvarASTPython}{
  1662. \begin{array}{rcl}
  1663. \Exp{} &::=& \VAR{\Var{}} \\
  1664. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1665. \end{array}
  1666. }
  1667. \begin{figure}[tp]
  1668. \centering
  1669. \begin{tcolorbox}[colback=white]
  1670. {\if\edition\racketEd
  1671. \[
  1672. \begin{array}{l}
  1673. \gray{\LintGrammarRacket{}} \\ \hline
  1674. \LvarGrammarRacket{} \\
  1675. \begin{array}{rcl}
  1676. \LangVarM{} &::=& \Exp
  1677. \end{array}
  1678. \end{array}
  1679. \]
  1680. \fi}
  1681. {\if\edition\pythonEd\pythonColor
  1682. \[
  1683. \begin{array}{l}
  1684. \gray{\LintGrammarPython} \\ \hline
  1685. \LvarGrammarPython \\
  1686. \begin{array}{rcl}
  1687. \LangVarM{} &::=& \Stmt^{*}
  1688. \end{array}
  1689. \end{array}
  1690. \]
  1691. \fi}
  1692. \end{tcolorbox}
  1693. \caption{The concrete syntax of \LangVar{}.}
  1694. \label{fig:Lvar-concrete-syntax}
  1695. \end{figure}
  1696. \begin{figure}[tp]
  1697. \centering
  1698. \begin{tcolorbox}[colback=white]
  1699. {\if\edition\racketEd
  1700. \[
  1701. \begin{array}{l}
  1702. \gray{\LintASTRacket{}} \\ \hline
  1703. \LvarASTRacket \\
  1704. \begin{array}{rcl}
  1705. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1706. \end{array}
  1707. \end{array}
  1708. \]
  1709. \fi}
  1710. {\if\edition\pythonEd\pythonColor
  1711. \[
  1712. \begin{array}{l}
  1713. \gray{\LintASTPython}\\ \hline
  1714. \LvarASTPython \\
  1715. \begin{array}{rcl}
  1716. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1717. \end{array}
  1718. \end{array}
  1719. \]
  1720. \fi}
  1721. \end{tcolorbox}
  1722. \caption{The abstract syntax of \LangVar{}.}
  1723. \label{fig:Lvar-syntax}
  1724. \end{figure}
  1725. {\if\edition\racketEd
  1726. Let us dive further into the syntax and semantics of the \LangVar{}
  1727. language. The \key{let} feature defines a variable for use within its
  1728. body and initializes the variable with the value of an expression.
  1729. The abstract syntax for \key{let} is shown in
  1730. figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1731. \begin{lstlisting}
  1732. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1733. \end{lstlisting}
  1734. For example, the following program initializes \code{x} to $32$ and then
  1735. evaluates the body \code{(+ 10 x)}, producing $42$.
  1736. \begin{lstlisting}
  1737. (let ([x (+ 12 20)]) (+ 10 x))
  1738. \end{lstlisting}
  1739. \fi}
  1740. %
  1741. {\if\edition\pythonEd\pythonColor
  1742. %
  1743. The \LangVar{} language includes an assignment statement, which defines a
  1744. variable for use in later statements and initializes the variable with
  1745. the value of an expression. The abstract syntax for assignment is
  1746. defined in figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1747. assignment is \index{subject}{Assign@\texttt{Assign}}
  1748. \begin{lstlisting}
  1749. |$\itm{var}$| = |$\itm{exp}$|
  1750. \end{lstlisting}
  1751. For example, the following program initializes the variable \code{x}
  1752. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1753. \begin{lstlisting}
  1754. x = 12 + 20
  1755. print(10 + x)
  1756. \end{lstlisting}
  1757. \fi}
  1758. {\if\edition\racketEd
  1759. %
  1760. When there are multiple \key{let}s for the same variable, the closest
  1761. enclosing \key{let} is used. That is, variable definitions overshadow
  1762. prior definitions. Consider the following program with two \key{let}s
  1763. that define two variables named \code{x}. Can you figure out the
  1764. result?
  1765. \begin{lstlisting}
  1766. (let ([x 32]) (+ (let ([x 10]) x) x))
  1767. \end{lstlisting}
  1768. For the purposes of depicting which variable occurrences correspond to
  1769. which definitions, the following shows the \code{x}'s annotated with
  1770. subscripts to distinguish them. Double-check that your answer for the
  1771. previous program is the same as your answer for this annotated version
  1772. of the program.
  1773. \begin{lstlisting}
  1774. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1775. \end{lstlisting}
  1776. The initializing expression is always evaluated before the body of the
  1777. \key{let}, so in the following, the \key{read} for \code{x} is
  1778. performed before the \key{read} for \code{y}. Given the input
  1779. $52$ then $10$, the following produces $42$ (not $-42$).
  1780. \begin{lstlisting}
  1781. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1782. \end{lstlisting}
  1783. \fi}
  1784. \subsection{Extensible Interpreters via Method Overriding}
  1785. \label{sec:extensible-interp}
  1786. \index{subject}{method overriding}
  1787. To prepare for discussing the interpreter of \LangVar{}, we explain
  1788. why we implement it in an object-oriented style. Throughout this book
  1789. we define many interpreters, one for each language that we
  1790. study. Because each language builds on the prior one, there is a lot
  1791. of commonality between these interpreters. We want to write down the
  1792. common parts just once instead of many times. A naive interpreter for
  1793. \LangVar{} would handle the \racket{cases for variables and
  1794. \code{let}} \python{case for variables} but dispatch to an
  1795. interpreter for \LangInt{} in the rest of the cases. The following
  1796. code sketches this idea. (We explain the \code{env} parameter in
  1797. section~\ref{sec:interp-Lvar}.)
  1798. \begin{center}
  1799. {\if\edition\racketEd
  1800. \begin{minipage}{0.45\textwidth}
  1801. \begin{lstlisting}
  1802. (define ((interp_Lint env) e)
  1803. (match e
  1804. [(Prim '- (list e1))
  1805. (fx- 0 ((interp_Lint env) e1))]
  1806. ...))
  1807. \end{lstlisting}
  1808. \end{minipage}
  1809. \begin{minipage}{0.45\textwidth}
  1810. \begin{lstlisting}
  1811. (define ((interp_Lvar env) e)
  1812. (match e
  1813. [(Var x)
  1814. (dict-ref env x)]
  1815. [(Let x e body)
  1816. (define v ((interp_Lvar env) e))
  1817. (define env^ (dict-set env x v))
  1818. ((interp_Lvar env^) body)]
  1819. [else ((interp_Lint env) e)]))
  1820. \end{lstlisting}
  1821. \end{minipage}
  1822. \fi}
  1823. {\if\edition\pythonEd\pythonColor
  1824. \begin{minipage}{0.45\textwidth}
  1825. \begin{lstlisting}
  1826. def interp_Lint(e, env):
  1827. match e:
  1828. case UnaryOp(USub(), e1):
  1829. return - interp_Lint(e1, env)
  1830. ...
  1831. \end{lstlisting}
  1832. \end{minipage}
  1833. \begin{minipage}{0.45\textwidth}
  1834. \begin{lstlisting}
  1835. def interp_Lvar(e, env):
  1836. match e:
  1837. case Name(id):
  1838. return env[id]
  1839. case _:
  1840. return interp_Lint(e, env)
  1841. \end{lstlisting}
  1842. \end{minipage}
  1843. \fi}
  1844. \end{center}
  1845. The problem with this naive approach is that it does not handle
  1846. situations in which an \LangVar{} feature, such as a variable, is
  1847. nested inside an \LangInt{} feature, such as the \code{-} operator, as
  1848. in the following program.
  1849. {\if\edition\racketEd
  1850. \begin{lstlisting}
  1851. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1852. \end{lstlisting}
  1853. \fi}
  1854. {\if\edition\pythonEd\pythonColor
  1855. \begin{minipage}{1.0\textwidth}
  1856. \begin{lstlisting}
  1857. y = 10
  1858. print(-y)
  1859. \end{lstlisting}
  1860. \end{minipage}
  1861. \fi}
  1862. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1863. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1864. then it recursively calls \code{interp\_Lint} again on its argument.
  1865. Because there is no case for \racket{\code{Var}}\python{\code{Name}} in
  1866. \code{interp\_Lint}, we get an error!
  1867. To make our interpreters extensible we need something called
  1868. \emph{open recursion}\index{subject}{open recursion}, in which the
  1869. tying of the recursive knot is delayed until the functions are
  1870. composed. Object-oriented languages provide open recursion via method
  1871. overriding. The following code uses
  1872. method overriding to interpret \LangInt{} and \LangVar{} using
  1873. %
  1874. \racket{the
  1875. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1876. \index{subject}{class} feature of Racket.}%
  1877. %
  1878. \python{Python \code{class} definitions.}
  1879. %
  1880. We define one class for each language and define a method for
  1881. interpreting expressions inside each class. The class for \LangVar{}
  1882. inherits from the class for \LangInt{}, and the method
  1883. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1884. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1885. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1886. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1887. \code{interp\_exp} in \LangInt{}.
  1888. \begin{center}
  1889. \hspace{-20pt}
  1890. {\if\edition\racketEd
  1891. \begin{minipage}{0.45\textwidth}
  1892. \begin{lstlisting}
  1893. (define interp-Lint-class
  1894. (class object%
  1895. (define/public ((interp_exp env) e)
  1896. (match e
  1897. [(Prim '- (list e))
  1898. (fx- 0 ((interp_exp env) e))]
  1899. ...))
  1900. ...))
  1901. \end{lstlisting}
  1902. \end{minipage}
  1903. \begin{minipage}{0.45\textwidth}
  1904. \begin{lstlisting}
  1905. (define interp-Lvar-class
  1906. (class interp-Lint-class
  1907. (define/override ((interp_exp env) e)
  1908. (match e
  1909. [(Var x)
  1910. (dict-ref env x)]
  1911. [(Let x e body)
  1912. (define v ((interp_exp env) e))
  1913. (define env^ (dict-set env x v))
  1914. ((interp_exp env^) body)]
  1915. [else
  1916. (super (interp_exp env) e)]))
  1917. ...
  1918. ))
  1919. \end{lstlisting}
  1920. \end{minipage}
  1921. \fi}
  1922. {\if\edition\pythonEd\pythonColor
  1923. \begin{minipage}{0.45\textwidth}
  1924. \begin{lstlisting}
  1925. class InterpLint:
  1926. def interp_exp(e):
  1927. match e:
  1928. case UnaryOp(USub(), e1):
  1929. return neg64(self.interp_exp(e1))
  1930. ...
  1931. ...
  1932. \end{lstlisting}
  1933. \end{minipage}
  1934. \begin{minipage}{0.45\textwidth}
  1935. \begin{lstlisting}
  1936. def InterpLvar(InterpLint):
  1937. def interp_exp(e):
  1938. match e:
  1939. case Name(id):
  1940. return env[id]
  1941. case _:
  1942. return super().interp_exp(e)
  1943. ...
  1944. \end{lstlisting}
  1945. \end{minipage}
  1946. \fi}
  1947. \end{center}
  1948. We return to the troublesome example, repeated here:
  1949. {\if\edition\racketEd
  1950. \begin{lstlisting}
  1951. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1952. \end{lstlisting}
  1953. \fi}
  1954. {\if\edition\pythonEd\pythonColor
  1955. \begin{lstlisting}
  1956. y = 10
  1957. print(-y)
  1958. \end{lstlisting}
  1959. \fi}
  1960. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}%
  1961. \racket{on this expression,}
  1962. \python{on the \code{-y} expression,}
  1963. %
  1964. which we call \code{e0}, by creating an object of the \LangVar{} class
  1965. and calling the \code{interp\_exp} method
  1966. {\if\edition\racketEd
  1967. \begin{lstlisting}
  1968. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1969. \end{lstlisting}
  1970. \fi}
  1971. {\if\edition\pythonEd\pythonColor
  1972. \begin{lstlisting}
  1973. InterpLvar().interp_exp(e0)
  1974. \end{lstlisting}
  1975. \fi}
  1976. \noindent To process the \code{-} operator, the default case of
  1977. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1978. method in \LangInt{}. But then for the recursive method call, it
  1979. dispatches to \code{interp\_exp} in \LangVar{}, where the
  1980. \racket{\code{Var}}\python{\code{Name}} node is handled correctly.
  1981. Thus, method overriding gives us the open recursion that we need to
  1982. implement our interpreters in an extensible way.
  1983. \subsection{Definitional Interpreter for \LangVar{}}
  1984. \label{sec:interp-Lvar}
  1985. Having justified the use of classes and methods to implement
  1986. interpreters, we revisit the definitional interpreter for \LangInt{}
  1987. shown in figure~\ref{fig:interp-Lint-class} and then extend it to
  1988. create an interpreter for \LangVar{}, shown in
  1989. figure~\ref{fig:interp-Lvar}.
  1990. %
  1991. \python{We change the \code{interp\_stmt} method in the interpreter
  1992. for \LangInt{} to take two extra parameters named \code{env}, which
  1993. we discuss in the next paragraph, and \code{cont} for
  1994. \emph{continuation}, which is the technical name for what comes
  1995. after a particular point in a program. The \code{cont} parameter is
  1996. the list of statements that follow the current statement. Note
  1997. that \code{interp\_stmts} invokes \code{interp\_stmt} on the first
  1998. statement and passes the rest of the statements as the argument for
  1999. \code{cont}. This organization enables each statement to decide what
  2000. if anything should be evaluated after it, for example, allowing a
  2001. \code{return} statement to exit early from a function (see
  2002. Chapter~\ref{ch:Lfun}).}
  2003. The interpreter for \LangVar{} adds two new cases for
  2004. variables and \racket{\key{let}}\python{assignment}. For
  2005. \racket{\key{let}}\python{assignment}, we need a way to communicate the
  2006. value bound to a variable to all the uses of the variable. To
  2007. accomplish this, we maintain a mapping from variables to values called
  2008. an \emph{environment}\index{subject}{environment}.
  2009. %
  2010. We use
  2011. %
  2012. \racket{an association list (alist) }%
  2013. %
  2014. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  2015. %
  2016. to represent the environment.
  2017. %
  2018. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  2019. and the \code{racket/dict} package.}
  2020. %
  2021. The \code{interp\_exp} function takes the current environment,
  2022. \code{env}, as an extra parameter. When the interpreter encounters a
  2023. variable, it looks up the corresponding value in the environment. If
  2024. the variable is not in the environment (because the variable was not
  2025. defined) then the lookup will fail and the interpreter will
  2026. halt with an error. Recall that the compiler is not obligated to
  2027. compile such programs (Section~\ref{sec:interp_Lint}).\footnote{In
  2028. Chapter~\ref{ch:Lif} we introduce type checking rules that
  2029. prohibit access to undefined variables.}
  2030. %
  2031. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  2032. initializing expression, extends the environment with the result
  2033. value bound to the variable, using \code{dict-set}, then evaluates
  2034. the body of the \key{Let}.}
  2035. %
  2036. \python{When the interpreter encounters an assignment, it evaluates
  2037. the initializing expression and then associates the resulting value
  2038. with the variable in the environment.}
  2039. \begin{figure}[tp]
  2040. \begin{tcolorbox}[colback=white]
  2041. {\if\edition\racketEd
  2042. \begin{lstlisting}
  2043. (define interp-Lint-class
  2044. (class object%
  2045. (super-new)
  2046. (define/public ((interp_exp env) e)
  2047. (match e
  2048. [(Int n) n]
  2049. [(Prim 'read '())
  2050. (define r (read))
  2051. (cond [(fixnum? r) r]
  2052. [else (error 'interp_exp "expected an integer" r)])]
  2053. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  2054. [(Prim '+ (list e1 e2))
  2055. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  2056. [(Prim '- (list e1 e2))
  2057. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  2058. (define/public (interp_program p)
  2059. (match p
  2060. [(Program '() e) ((interp_exp '()) e)]))
  2061. ))
  2062. \end{lstlisting}
  2063. \fi}
  2064. {\if\edition\pythonEd\pythonColor
  2065. \begin{lstlisting}
  2066. class InterpLint:
  2067. def interp_exp(self, e, env):
  2068. match e:
  2069. case BinOp(left, Add(), right):
  2070. l = self.interp_exp(left, env)
  2071. r = self.interp_exp(right, env)
  2072. return add64(l, r)
  2073. case BinOp(left, Sub(), right):
  2074. l = self.interp_exp(left, env)
  2075. r = self.interp_exp(right, env)
  2076. return sub64(l, r)
  2077. case UnaryOp(USub(), v):
  2078. return neg64(self.interp_exp(v, env))
  2079. case Constant(value):
  2080. return value
  2081. case Call(Name('input_int'), []):
  2082. return int(input())
  2083. def interp_stmt(self, s, env, cont):
  2084. match s:
  2085. case Expr(Call(Name('print'), [arg])):
  2086. val = self.interp_exp(arg, env)
  2087. print(val, end='')
  2088. return self.interp_stmts(cont, env)
  2089. case Expr(value):
  2090. self.interp_exp(value, env)
  2091. return self.interp_stmts(cont, env)
  2092. case _:
  2093. raise Exception('error in interp_stmt, unexpected ' + repr(s))
  2094. def interp_stmts(self, ss, env):
  2095. match ss:
  2096. case []:
  2097. return 0
  2098. case [s, *ss]:
  2099. return self.interp_stmt(s, env, ss)
  2100. def interp(self, p):
  2101. match p:
  2102. case Module(body):
  2103. self.interp_stmts(body, {})
  2104. def interp_Lint(p):
  2105. return InterpLint().interp(p)
  2106. \end{lstlisting}
  2107. \fi}
  2108. \end{tcolorbox}
  2109. \caption{Interpreter for \LangInt{} as a class.}
  2110. \label{fig:interp-Lint-class}
  2111. \end{figure}
  2112. \begin{figure}[tp]
  2113. \begin{tcolorbox}[colback=white]
  2114. {\if\edition\racketEd
  2115. \begin{lstlisting}
  2116. (define interp-Lvar-class
  2117. (class interp-Lint-class
  2118. (super-new)
  2119. (define/override ((interp_exp env) e)
  2120. (match e
  2121. [(Var x) (dict-ref env x)]
  2122. [(Let x e body)
  2123. (define new-env (dict-set env x ((interp_exp env) e)))
  2124. ((interp_exp new-env) body)]
  2125. [else ((super interp_exp env) e)]))
  2126. ))
  2127. (define (interp_Lvar p)
  2128. (send (new interp-Lvar-class) interp_program p))
  2129. \end{lstlisting}
  2130. \fi}
  2131. {\if\edition\pythonEd\pythonColor
  2132. \begin{lstlisting}
  2133. class InterpLvar(InterpLint):
  2134. def interp_exp(self, e, env):
  2135. match e:
  2136. case Name(id):
  2137. return env[id]
  2138. case _:
  2139. return super().interp_exp(e, env)
  2140. def interp_stmt(self, s, env, cont):
  2141. match s:
  2142. case Assign([Name(id)], value):
  2143. env[id] = self.interp_exp(value, env)
  2144. return self.interp_stmts(cont, env)
  2145. case _:
  2146. return super().interp_stmt(s, env, cont)
  2147. def interp_Lvar(p):
  2148. return InterpLvar().interp(p)
  2149. \end{lstlisting}
  2150. \fi}
  2151. \end{tcolorbox}
  2152. \caption{Interpreter for the \LangVar{} language.}
  2153. \label{fig:interp-Lvar}
  2154. \end{figure}
  2155. {\if\edition\racketEd
  2156. \begin{figure}[tp]
  2157. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  2158. \small
  2159. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  2160. An \emph{association list} (called an alist) is a list of key-value pairs.
  2161. For example, we can map people to their ages with an alist
  2162. \index{subject}{alist}\index{subject}{association list}
  2163. \begin{lstlisting}[basicstyle=\ttfamily]
  2164. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  2165. \end{lstlisting}
  2166. The \emph{dictionary} interface is for mapping keys to values.
  2167. Every alist implements this interface. \index{subject}{dictionary}
  2168. The package
  2169. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  2170. provides many functions for working with dictionaries, such as
  2171. \begin{description}
  2172. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  2173. returns the value associated with the given $\itm{key}$.
  2174. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  2175. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  2176. and otherwise is the same as $\itm{dict}$.
  2177. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  2178. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  2179. of keys and values in $\itm{dict}$. For example, the following
  2180. creates a new alist in which the ages are incremented:
  2181. \end{description}
  2182. \vspace{-10pt}
  2183. \begin{lstlisting}[basicstyle=\ttfamily]
  2184. (for/list ([(k v) (in-dict ages)])
  2185. (cons k (add1 v)))
  2186. \end{lstlisting}
  2187. \end{tcolorbox}
  2188. %\end{wrapfigure}
  2189. \caption{Association lists implement the dictionary interface.}
  2190. \label{fig:alist}
  2191. \end{figure}
  2192. \fi}
  2193. The goal for this chapter is to implement a compiler that translates
  2194. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2195. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2196. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2197. That is, they output the same integer $n$. We depict this correctness
  2198. criteria in the following diagram:
  2199. \[
  2200. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2201. \node (p1) at (0, 0) {$P_1$};
  2202. \node (p2) at (4, 0) {$P_2$};
  2203. \node (o) at (4, -2) {$n$};
  2204. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2205. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2206. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2207. \end{tikzpicture}
  2208. \]
  2209. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2210. compiling \LangVar{}.
  2211. \section{The \LangXInt{} Assembly Language}
  2212. \label{sec:x86}
  2213. \index{subject}{x86}
  2214. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2215. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2216. assembler.
  2217. %
  2218. A program begins with a \code{main} label followed by a sequence of
  2219. instructions. The \key{globl} directive makes the \key{main} procedure
  2220. externally visible so that the operating system can call it.
  2221. %
  2222. An x86 program is stored in the computer's memory. For our purposes,
  2223. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2224. values. The computer has a \emph{program counter}
  2225. (PC)\index{subject}{program counter}\index{subject}{PC} stored in the
  2226. \code{rip} register that points to the address of the next instruction
  2227. to be executed. For most instructions, the program counter is
  2228. incremented after the instruction is executed so that it points to the
  2229. next instruction in memory. Most x86 instructions take two operands,
  2230. each of which is an integer constant (called an \emph{immediate
  2231. value}\index{subject}{immediate value}), a
  2232. \emph{register}\index{subject}{register}, or a memory location.
  2233. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2234. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2235. && \key{r8} \MID \key{r9} \MID \key{r10}
  2236. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2237. \MID \key{r14} \MID \key{r15}}
  2238. \newcommand{\GrammarXInt}{
  2239. \begin{array}{rcl}
  2240. \Reg &::=& \allregisters{} \\
  2241. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2242. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2243. \key{subq} \; \Arg\key{,} \Arg \MID
  2244. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2245. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2246. \key{callq} \; \mathit{label} \MID
  2247. \key{retq} \MID
  2248. \key{jmp}\,\itm{label} \MID \\
  2249. && \itm{label}\key{:}\; \Instr
  2250. \end{array}
  2251. }
  2252. \begin{figure}[tp]
  2253. \begin{tcolorbox}[colback=white]
  2254. {\if\edition\racketEd
  2255. \[
  2256. \begin{array}{l}
  2257. \GrammarXInt \\
  2258. \begin{array}{lcl}
  2259. \LangXIntM{} &::= & \key{.globl main}\\
  2260. & & \key{main:} \; \Instr\ldots
  2261. \end{array}
  2262. \end{array}
  2263. \]
  2264. \fi}
  2265. {\if\edition\pythonEd\pythonColor
  2266. \[
  2267. \begin{array}{lcl}
  2268. \Reg &::=& \allregisters{} \\
  2269. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2270. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2271. \key{subq} \; \Arg\key{,} \Arg \MID
  2272. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2273. && \key{callq} \; \mathit{label} \MID
  2274. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2275. \LangXIntM{} &::= & \key{.globl main}\\
  2276. & & \key{main:} \; \Instr^{*}
  2277. \end{array}
  2278. \]
  2279. \fi}
  2280. \end{tcolorbox}
  2281. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2282. \label{fig:x86-int-concrete}
  2283. \end{figure}
  2284. A register is a special kind of variable that holds a 64-bit
  2285. value. There are 16 general-purpose registers in the computer; their
  2286. names are given in figure~\ref{fig:x86-int-concrete}. A register is
  2287. written with a percent sign, \key{\%}, followed by its name,
  2288. for example \key{\%rax}.
  2289. An immediate value is written using the notation \key{\$}$n$ where $n$
  2290. is an integer.
  2291. %
  2292. %
  2293. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2294. which obtains the address stored in register $r$ and then adds $n$
  2295. bytes to the address. The resulting address is used to load or to store
  2296. to memory depending on whether it occurs as a source or destination
  2297. argument of an instruction.
  2298. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from
  2299. the source $s$ and destination $d$, applies the arithmetic operation,
  2300. and then writes the result to the destination $d$. \index{subject}{instruction}
  2301. %
  2302. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2303. stores the result in $d$.
  2304. %
  2305. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2306. specified by the label, and $\key{retq}$ returns from a procedure to
  2307. its caller.
  2308. %
  2309. We discuss procedure calls in more detail further in this chapter and
  2310. in chapter~\ref{ch:Lfun}.
  2311. %
  2312. The last letter \key{q} indicates that these instructions operate on
  2313. quadwords, which are 64-bit values.
  2314. %
  2315. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2316. counter to the address of the instruction immediately after the
  2317. specified label.}
  2318. Appendix~\ref{sec:x86-quick-reference} contains a reference for
  2319. all the x86 instructions used in this book.
  2320. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2321. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2322. \lstinline{movq $10, %rax}
  2323. puts $10$ into register \key{rax}, and then \lstinline{addq $32, %rax}
  2324. adds $32$ to the $10$ in \key{rax} and
  2325. puts the result, $42$, into \key{rax}.
  2326. %
  2327. The last instruction \key{retq} finishes the \key{main} function by
  2328. returning the integer in \key{rax} to the operating system. The
  2329. operating system interprets this integer as the program's exit
  2330. code. By convention, an exit code of 0 indicates that a program has
  2331. completed successfully, and all other exit codes indicate various
  2332. errors.
  2333. %
  2334. \racket{However, in this book we return the result of the program
  2335. as the exit code.}
  2336. \begin{figure}[tbp]
  2337. \begin{minipage}{0.45\textwidth}
  2338. \begin{tcolorbox}[colback=white]
  2339. \begin{lstlisting}
  2340. .globl main
  2341. main:
  2342. movq $10, %rax
  2343. addq $32, %rax
  2344. retq
  2345. \end{lstlisting}
  2346. \end{tcolorbox}
  2347. \end{minipage}
  2348. \caption{An x86 program that computes
  2349. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2350. \label{fig:p0-x86}
  2351. \end{figure}
  2352. We exhibit the use of memory for storing intermediate results in the
  2353. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2354. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2355. uses a region of memory called the \emph{procedure call stack}
  2356. (\emph{stack} for
  2357. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2358. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2359. for each procedure call. The memory layout for an individual frame is
  2360. shown in figure~\ref{fig:frame}. The register \key{rsp} is called the
  2361. \emph{stack pointer}\index{subject}{stack pointer} and contains the
  2362. address of the item at the top of the stack. In general, we use the
  2363. term \emph{pointer}\index{subject}{pointer} for something that
  2364. contains an address. The stack grows downward in memory, so we
  2365. increase the size of the stack by subtracting from the stack pointer.
  2366. In the context of a procedure call, the \emph{return
  2367. address}\index{subject}{return address} is the location of the
  2368. instruction that immediately follows the call instruction on the
  2369. caller side. The function call instruction, \code{callq}, pushes the
  2370. return address onto the stack prior to jumping to the procedure. The
  2371. register \key{rbp} is the \emph{base pointer}\index{subject}{base
  2372. pointer} and is used to access variables that are stored in the
  2373. frame of the current procedure call. The base pointer of the caller
  2374. is stored immediately after the return address.
  2375. Figure~\ref{fig:frame} shows the memory layout of a frame with storage
  2376. for $n$ variables, which are numbered from $1$ to $n$. Variable $1$ is
  2377. stored at address $-8\key{(\%rbp)}$, variable $2$ at
  2378. $-16\key{(\%rbp)}$, and so on.
  2379. \begin{figure}[tbp]
  2380. \begin{minipage}{0.66\textwidth}
  2381. \begin{tcolorbox}[colback=white]
  2382. {\if\edition\racketEd
  2383. \begin{lstlisting}
  2384. start:
  2385. movq $10, -8(%rbp)
  2386. negq -8(%rbp)
  2387. movq -8(%rbp), %rax
  2388. addq $52, %rax
  2389. jmp conclusion
  2390. .globl main
  2391. main:
  2392. pushq %rbp
  2393. movq %rsp, %rbp
  2394. subq $16, %rsp
  2395. jmp start
  2396. conclusion:
  2397. addq $16, %rsp
  2398. popq %rbp
  2399. retq
  2400. \end{lstlisting}
  2401. \fi}
  2402. {\if\edition\pythonEd\pythonColor
  2403. \begin{lstlisting}
  2404. .globl main
  2405. main:
  2406. pushq %rbp
  2407. movq %rsp, %rbp
  2408. subq $16, %rsp
  2409. movq $10, -8(%rbp)
  2410. negq -8(%rbp)
  2411. movq -8(%rbp), %rax
  2412. addq $52, %rax
  2413. addq $16, %rsp
  2414. popq %rbp
  2415. retq
  2416. \end{lstlisting}
  2417. \fi}
  2418. \end{tcolorbox}
  2419. \end{minipage}
  2420. \caption{An x86 program that computes
  2421. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2422. \label{fig:p1-x86}
  2423. \end{figure}
  2424. \begin{figure}[tbp]
  2425. \begin{minipage}{0.66\textwidth}
  2426. \begin{tcolorbox}[colback=white]
  2427. \centering
  2428. \begin{tabular}{|r|l|} \hline
  2429. Position & Contents \\ \hline
  2430. $8$(\key{\%rbp}) & return address \\
  2431. $0$(\key{\%rbp}) & old \key{rbp} \\
  2432. $-8$(\key{\%rbp}) & variable $1$ \\
  2433. $-16$(\key{\%rbp}) & variable $2$ \\
  2434. \ldots & \ldots \\
  2435. $0$(\key{\%rsp}) & variable $n$\\ \hline
  2436. \end{tabular}
  2437. \end{tcolorbox}
  2438. \end{minipage}
  2439. \caption{Memory layout of a frame.}
  2440. \label{fig:frame}
  2441. \end{figure}
  2442. In the program shown in figure~\ref{fig:p1-x86}, consider how control
  2443. is transferred from the operating system to the \code{main} function.
  2444. The operating system issues a \code{callq main} instruction that
  2445. pushes its return address on the stack and then jumps to
  2446. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2447. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2448. that when control arrives at \code{main}, the \code{rsp} is 8 bytes
  2449. out of alignment (because the \code{callq} pushed the return address).
  2450. The first three instructions are the typical
  2451. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2452. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2453. pointer \code{rsp} and then saves the base pointer of the caller at
  2454. address \code{rsp} on the stack. The next instruction \code{movq
  2455. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2456. which is pointing to the location of the old base pointer. The
  2457. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2458. make enough room for storing variables. This program needs one
  2459. variable ($8$ bytes), but we round up to 16 bytes so that \code{rsp} is
  2460. 16-byte-aligned, and then we are ready to make calls to other functions.
  2461. \racket{The last instruction of the prelude is \code{jmp start}, which
  2462. transfers control to the instructions that were generated from the
  2463. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2464. \racket{The first instruction under the \code{start} label is}
  2465. %
  2466. \python{The first instruction after the prelude is}
  2467. %
  2468. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2469. %
  2470. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2471. $1$ to $-10$.
  2472. %
  2473. The next instruction moves the $-10$ from variable $1$ into the
  2474. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2475. the value in \code{rax}, updating its contents to $42$.
  2476. \racket{The three instructions under the label \code{conclusion} are the
  2477. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2478. %
  2479. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2480. \code{main} function consists of the last three instructions.}
  2481. %
  2482. The first two restore the \code{rsp} and \code{rbp} registers to their
  2483. states at the beginning of the procedure. In particular,
  2484. \key{addq \$16, \%rsp} moves the stack pointer to point to the
  2485. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2486. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2487. \key{retq}, jumps back to the procedure that called this one and adds
  2488. $8$ to the stack pointer.
  2489. Our compiler needs a convenient representation for manipulating x86
  2490. programs, so we define an abstract syntax for x86, shown in
  2491. figure~\ref{fig:x86-int-ast}. We refer to this language as
  2492. \LangXInt{}.
  2493. %
  2494. {\if\edition\pythonEd\pythonColor%
  2495. The main difference between this and the concrete syntax of \LangXInt{}
  2496. (figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2497. names, and register names are explicitly represented by strings.
  2498. \fi} %
  2499. {\if\edition\racketEd
  2500. The main difference between this and the concrete syntax of \LangXInt{}
  2501. (figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2502. front of every instruction. Instead instructions are grouped into
  2503. \emph{basic blocks}\index{subject}{basic block} with a
  2504. label associated with every basic block; this is why the \key{X86Program}
  2505. struct includes an alist mapping labels to basic blocks. The reason for this
  2506. organization becomes apparent in chapter~\ref{ch:Lif} when we
  2507. introduce conditional branching. The \code{Block} structure includes
  2508. an $\itm{info}$ field that is not needed in this chapter but becomes
  2509. useful in chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2510. $\itm{info}$ field should contain an empty list.
  2511. \fi}
  2512. %
  2513. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2514. node includes an integer for representing the arity of the function,
  2515. that is, the number of arguments, which is helpful to know during
  2516. register allocation (chapter~\ref{ch:register-allocation-Lvar}).
  2517. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2518. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2519. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2520. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2521. \MID \skey{r14} \MID \skey{r15}}
  2522. \newcommand{\ASTXIntRacket}{
  2523. \begin{array}{lcl}
  2524. \Reg &::=& \allregisters{} \\
  2525. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2526. \MID \DEREF{\Reg}{\Int} \\
  2527. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2528. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}\\
  2529. &\MID& \UNIINSTR{\code{negq}}{\Arg}
  2530. \MID \BININSTR{\code{movq}}{\Arg}{\Arg}\\
  2531. &\MID& \PUSHQ{\Arg}
  2532. \MID \POPQ{\Arg} \\
  2533. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2534. \MID \RETQ{}
  2535. \MID \JMP{\itm{label}} \\
  2536. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2537. \end{array}
  2538. }
  2539. \newcommand{\ASTXIntPython}{
  2540. \begin{array}{lcl}
  2541. \Reg &::=& \allregisters{} \\
  2542. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2543. \MID \DEREF{\Reg}{\Int} \\
  2544. \Instr &::=& \BININSTR{\skey{addq}}{\Arg}{\Arg}
  2545. \MID \BININSTR{\skey{subq}}{\Arg}{\Arg}\\
  2546. &\MID& \UNIINSTR{\skey{negq}}{\Arg}
  2547. \MID \BININSTR{\skey{movq}}{\Arg}{\Arg}\\
  2548. &\MID& \PUSHQ{\Arg}
  2549. \MID \POPQ{\Arg} \\
  2550. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2551. \MID \RETQ{}
  2552. \MID \JMP{\itm{label}} \\
  2553. \Block &::= & \Instr^{+}
  2554. \end{array}
  2555. }
  2556. \begin{figure}[tp]
  2557. \begin{tcolorbox}[colback=white]
  2558. \small
  2559. {\if\edition\racketEd
  2560. \[\arraycolsep=3pt
  2561. \begin{array}{l}
  2562. \ASTXIntRacket \\
  2563. \begin{array}{lcl}
  2564. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2565. \end{array}
  2566. \end{array}
  2567. \]
  2568. \fi}
  2569. {\if\edition\pythonEd\pythonColor
  2570. \[
  2571. \begin{array}{lcl}
  2572. \Reg &::=& \allastregisters{} \\
  2573. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2574. \MID \DEREF{\Reg}{\Int} \\
  2575. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2576. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2577. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2578. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2579. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2580. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2581. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2582. \end{array}
  2583. \]
  2584. \fi}
  2585. \end{tcolorbox}
  2586. \caption{The abstract syntax of \LangXInt{} assembly.}
  2587. \label{fig:x86-int-ast}
  2588. \end{figure}
  2589. \section{Planning the Trip to x86}
  2590. \label{sec:plan-s0-x86}
  2591. To compile one language to another, it helps to focus on the
  2592. differences between the two languages because the compiler will need
  2593. to bridge those differences. What are the differences between \LangVar{}
  2594. and x86 assembly? Here are some of the most important ones:
  2595. \begin{enumerate}
  2596. \item x86 arithmetic instructions typically have two arguments and
  2597. update the second argument in place. In contrast, \LangVar{}
  2598. arithmetic operations take two arguments and produce a new value.
  2599. An x86 instruction may have at most one memory-accessing argument.
  2600. Furthermore, some x86 instructions place special restrictions on
  2601. their arguments.
  2602. \item An argument of an \LangVar{} operator can be a deeply nested
  2603. expression, whereas x86 instructions restrict their arguments to be
  2604. integer constants, registers, and memory locations.
  2605. {\if\edition\racketEd
  2606. \item The order of execution in x86 is explicit in the syntax, which
  2607. is a sequence of instructions and jumps to labeled positions,
  2608. whereas in \LangVar{} the order of evaluation is a left-to-right
  2609. depth-first traversal of the abstract syntax tree. \fi}
  2610. \item A program in \LangVar{} can have any number of variables,
  2611. whereas x86 has 16 registers and the procedure call stack.
  2612. {\if\edition\racketEd
  2613. \item Variables in \LangVar{} can shadow other variables with the
  2614. same name. In x86, registers have unique names, and memory locations
  2615. have unique addresses.
  2616. \fi}
  2617. \end{enumerate}
  2618. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2619. down the problem into several steps, which deal with these differences
  2620. one at a time. Each of these steps is called a \emph{pass} of the
  2621. compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2622. %
  2623. This term indicates that each step passes over, or traverses, the AST
  2624. of the program.
  2625. %
  2626. Furthermore, we follow the nanopass approach, which means that we
  2627. strive for each pass to accomplish one clear objective rather than two
  2628. or three at the same time.
  2629. %
  2630. We begin by sketching how we might implement each pass and give each
  2631. pass a name. We then figure out an ordering of the passes and the
  2632. input/output language for each pass. The very first pass has
  2633. \LangVar{} as its input language, and the last pass has \LangXInt{} as
  2634. its output language. In between these two passes, we can choose
  2635. whichever language is most convenient for expressing the output of
  2636. each pass, whether that be \LangVar{}, \LangXInt{}, or a new
  2637. \emph{intermediate language} of our own design. Finally, to
  2638. implement each pass we write one recursive function per nonterminal in
  2639. the grammar of the input language of the pass.
  2640. \index{subject}{intermediate language}
  2641. Our compiler for \LangVar{} consists of the following passes:
  2642. %
  2643. \begin{description}
  2644. {\if\edition\racketEd
  2645. \item[\key{uniquify}] deals with the shadowing of variables by
  2646. renaming every variable to a unique name.
  2647. \fi}
  2648. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2649. of a primitive operation or function call is a variable or integer,
  2650. that is, an \emph{atomic} expression. We refer to nonatomic
  2651. expressions as \emph{complex}. This pass introduces temporary
  2652. variables to hold the results of complex
  2653. subexpressions.\index{subject}{atomic
  2654. expression}\index{subject}{complex expression}%
  2655. {\if\edition\racketEd
  2656. \item[\key{explicate\_control}] makes the execution order of the
  2657. program explicit. It converts the abstract syntax tree
  2658. representation into a graph in which each node is a labeled sequence
  2659. of statements and the edges are \code{goto} statements.
  2660. \fi}
  2661. \item[\key{select\_instructions}]\index{subject}{select instructions}
  2662. handles the difference between
  2663. \LangVar{} operations and x86 instructions. This pass converts each
  2664. \LangVar{} operation to a short sequence of instructions that
  2665. accomplishes the same task.
  2666. \item[\key{assign\_homes}] replaces variables with registers or stack
  2667. locations.
  2668. \end{description}
  2669. %
  2670. {\if\edition\racketEd
  2671. %
  2672. Our treatment of \code{remove\_complex\_operands} and
  2673. \code{explicate\_control} as separate passes is an example of the
  2674. nanopass approach.\footnote{For analogous decompositions of the
  2675. translation into continuation passing style, see the work of
  2676. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.} The traditional
  2677. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2678. %
  2679. \fi}
  2680. The next question is, in what order should we apply these passes? This
  2681. question can be challenging because it is difficult to know ahead of
  2682. time which orderings will be better (that is, will be easier to
  2683. implement, produce more efficient code, and so on), and therefore
  2684. ordering often involves trial and error. Nevertheless, we can plan
  2685. ahead and make educated choices regarding the ordering.
  2686. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2687. \key{uniquify}? The \key{uniquify} pass should come first because
  2688. \key{explicate\_control} changes all the \key{let}-bound variables to
  2689. become local variables whose scope is the entire program, which would
  2690. confuse variables with the same name.}
  2691. %
  2692. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2693. because the later removes the \key{let} form, but it is convenient to
  2694. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2695. %
  2696. \racket{The ordering of \key{uniquify} with respect to
  2697. \key{remove\_complex\_operands} does not matter, so we arbitrarily choose
  2698. \key{uniquify} to come first.}
  2699. The \key{select\_instructions} and \key{assign\_homes} passes are
  2700. intertwined.
  2701. %
  2702. In chapter~\ref{ch:Lfun} we learn that in x86, registers are used for
  2703. passing arguments to functions and that it is preferable to assign
  2704. parameters to their corresponding registers. This suggests that it
  2705. would be better to start with the \key{select\_instructions} pass,
  2706. which generates the instructions for argument passing, before
  2707. performing register allocation.
  2708. %
  2709. On the other hand, by selecting instructions first we may run into a
  2710. dead end in \key{assign\_homes}. Recall that only one argument of an
  2711. x86 instruction may be a memory access, but \key{assign\_homes} might
  2712. be forced to assign both arguments to memory locations.
  2713. %
  2714. A sophisticated approach is to repeat the two passes until a solution
  2715. is found. However, to reduce implementation complexity we recommend
  2716. placing \key{select\_instructions} first, followed by the
  2717. \key{assign\_homes}, and then a third pass named \key{patch\_instructions}
  2718. that uses a reserved register to fix outstanding problems.
  2719. \begin{figure}[tbp]
  2720. \begin{tcolorbox}[colback=white]
  2721. {\if\edition\racketEd
  2722. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  2723. \node (Lvar) at (0,2) {\large \LangVar{}};
  2724. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2725. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  2726. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2727. \node (Cvar-2) at (0,0) {\large \LangCVar{}};
  2728. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  2729. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  2730. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  2731. \node (x86-5) at (11,-2) {\large \LangXInt{}};
  2732. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2733. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  2734. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize\ \ explicate\_control} (Cvar-2);
  2735. \path[->,bend right=15] (Cvar-2) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  2736. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2737. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  2738. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  2739. \end{tikzpicture}
  2740. \fi}
  2741. {\if\edition\pythonEd\pythonColor
  2742. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  2743. \node (Lvar) at (0,2) {\large \LangVar{}};
  2744. \node (Lvar-2) at (4,2) {\large \LangVarANF{}};
  2745. \node (x86-1) at (0,0) {\large \LangXVar{}};
  2746. \node (x86-2) at (4,0) {\large \LangXVar{}};
  2747. \node (x86-3) at (8,0) {\large \LangXInt{}};
  2748. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2749. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-2);
  2750. \path[->,bend left=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instructions\ \ } (x86-1);
  2751. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2752. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  2753. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  2754. \end{tikzpicture}
  2755. \fi}
  2756. \end{tcolorbox}
  2757. \caption{Diagram of the passes for compiling \LangVar{}. }
  2758. \label{fig:Lvar-passes}
  2759. \end{figure}
  2760. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2761. passes and identifies the input and output language of each pass.
  2762. %
  2763. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2764. language, which extends \LangXInt{} with an unbounded number of
  2765. program-scope variables and removes the restrictions regarding
  2766. instruction arguments.
  2767. %
  2768. The last pass, \key{prelude\_and\_conclusion}, places the program
  2769. instructions inside a \code{main} function with instructions for the
  2770. prelude and conclusion.
  2771. %
  2772. \racket{In the next section we discuss the \LangCVar{} intermediate
  2773. language that serves as the output of \code{explicate\_control}.}
  2774. %
  2775. The remainder of this chapter provides guidance on the implementation
  2776. of each of the compiler passes represented in
  2777. figure~\ref{fig:Lvar-passes}.
  2778. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2779. %% are programs that are still in the \LangVar{} language, though the
  2780. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2781. %% (section~\ref{sec:remove-complex-opera-Lvar}).
  2782. %% %
  2783. %% The output of \code{explicate\_control} is in an intermediate language
  2784. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2785. %% syntax, which we introduce in the next section. The
  2786. %% \key{select-instruction} pass translates from \LangCVar{} to
  2787. %% \LangXVar{}. The \key{assign-homes} and
  2788. %% \key{patch-instructions}
  2789. %% passes input and output variants of x86 assembly.
  2790. \newcommand{\CvarGrammarRacket}{
  2791. \begin{array}{lcl}
  2792. \Atm &::=& \Int \MID \Var \\
  2793. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2794. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2795. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2796. \end{array}
  2797. }
  2798. \newcommand{\CvarASTRacket}{
  2799. \begin{array}{lcl}
  2800. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2801. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2802. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2803. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2804. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2805. \end{array}
  2806. }
  2807. {\if\edition\racketEd
  2808. \subsection{The \LangCVar{} Intermediate Language}
  2809. The output of \code{explicate\_control} is similar to the C
  2810. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2811. categories for expressions and statements, so we name it \LangCVar{}.
  2812. This style of intermediate language is also known as
  2813. \emph{three-address code}, to emphasize that the typical form of a
  2814. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2815. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2816. The concrete syntax for \LangCVar{} is shown in
  2817. figure~\ref{fig:c0-concrete-syntax}, and the abstract syntax for
  2818. \LangCVar{} is shown in figure~\ref{fig:c0-syntax}.
  2819. %
  2820. The \LangCVar{} language supports the same operators as \LangVar{} but
  2821. the arguments of operators are restricted to atomic
  2822. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2823. assignment statements that can be executed in sequence using the
  2824. \key{Seq} form. A sequence of statements always ends with
  2825. \key{Return}, a guarantee that is baked into the grammar rules for
  2826. \itm{tail}. The naming of this nonterminal comes from the term
  2827. \emph{tail position}\index{subject}{tail position}, which refers to an
  2828. expression that is the last one to execute within a function or
  2829. program.
  2830. A \LangCVar{} program consists of an alist mapping labels to
  2831. tails. This is more general than necessary for the present chapter, as
  2832. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2833. us from having to change the syntax in chapter~\ref{ch:Lif}. For now
  2834. there is just one label, \key{start}, and the whole program is
  2835. its tail.
  2836. %
  2837. The $\itm{info}$ field of the \key{CProgram} form, after the
  2838. \code{explicate\_control} pass, contains an alist that associates the
  2839. symbol \key{locals} with a list of all the variables used in the
  2840. program. At the start of the program, these variables are
  2841. uninitialized; they become initialized on their first assignment.
  2842. \begin{figure}[tbp]
  2843. \begin{tcolorbox}[colback=white]
  2844. \[
  2845. \begin{array}{l}
  2846. \CvarGrammarRacket \\
  2847. \begin{array}{lcl}
  2848. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2849. \end{array}
  2850. \end{array}
  2851. \]
  2852. \end{tcolorbox}
  2853. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2854. \label{fig:c0-concrete-syntax}
  2855. \end{figure}
  2856. \begin{figure}[tbp]
  2857. \begin{tcolorbox}[colback=white]
  2858. \[
  2859. \begin{array}{l}
  2860. \CvarASTRacket \\
  2861. \begin{array}{lcl}
  2862. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2863. \end{array}
  2864. \end{array}
  2865. \]
  2866. \end{tcolorbox}
  2867. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2868. \label{fig:c0-syntax}
  2869. \end{figure}
  2870. The definitional interpreter for \LangCVar{} is in the support code,
  2871. in the file \code{interp-Cvar.rkt}.
  2872. \fi}
  2873. {\if\edition\racketEd
  2874. \section{Uniquify Variables}
  2875. \label{sec:uniquify-Lvar}
  2876. The \code{uniquify} pass replaces the variable bound by each \key{let}
  2877. with a unique name. Both the input and output of the \code{uniquify}
  2878. pass is the \LangVar{} language. For example, the \code{uniquify} pass
  2879. should translate the program on the left into the program on the
  2880. right.
  2881. \begin{transformation}
  2882. \begin{lstlisting}
  2883. (let ([x 32])
  2884. (+ (let ([x 10]) x) x))
  2885. \end{lstlisting}
  2886. \compilesto
  2887. \begin{lstlisting}
  2888. (let ([x.1 32])
  2889. (+ (let ([x.2 10]) x.2) x.1))
  2890. \end{lstlisting}
  2891. \end{transformation}
  2892. The following is another example translation, this time of a program
  2893. with a \key{let} nested inside the initializing expression of another
  2894. \key{let}.
  2895. \begin{transformation}
  2896. \begin{lstlisting}
  2897. (let ([x (let ([x 4])
  2898. (+ x 1))])
  2899. (+ x 2))
  2900. \end{lstlisting}
  2901. \compilesto
  2902. \begin{lstlisting}
  2903. (let ([x.2 (let ([x.1 4])
  2904. (+ x.1 1))])
  2905. (+ x.2 2))
  2906. \end{lstlisting}
  2907. \end{transformation}
  2908. We recommend implementing \code{uniquify} by creating a structurally
  2909. recursive function named \code{uniquify\_exp} that does little other
  2910. than copy an expression. However, when encountering a \key{let}, it
  2911. should generate a unique name for the variable and associate the old
  2912. name with the new name in an alist.\footnote{The Racket function
  2913. \code{gensym} is handy for generating unique variable names.} The
  2914. \code{uniquify\_exp} function needs to access this alist when it gets
  2915. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2916. for the alist.
  2917. The skeleton of the \code{uniquify\_exp} function is shown in
  2918. figure~\ref{fig:uniquify-Lvar}.
  2919. %% The function is curried so that it is
  2920. %% convenient to partially apply it to an alist and then apply it to
  2921. %% different expressions, as in the last case for primitive operations in
  2922. %% figure~\ref{fig:uniquify-Lvar}.
  2923. The
  2924. %
  2925. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2926. %
  2927. form of Racket is useful for transforming the element of a list to
  2928. produce a new list.\index{subject}{for/list}
  2929. \begin{figure}[tbp]
  2930. \begin{tcolorbox}[colback=white]
  2931. \begin{lstlisting}
  2932. (define (uniquify_exp env)
  2933. (lambda (e)
  2934. (match e
  2935. [(Var x) ___]
  2936. [(Int n) (Int n)]
  2937. [(Let x e body) ___]
  2938. [(Prim op es)
  2939. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2940. (define (uniquify p)
  2941. (match p
  2942. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2943. \end{lstlisting}
  2944. \end{tcolorbox}
  2945. \caption{Skeleton for the \key{uniquify} pass.}
  2946. \label{fig:uniquify-Lvar}
  2947. \end{figure}
  2948. \begin{exercise}
  2949. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2950. Complete the \code{uniquify} pass by filling in the blanks in
  2951. figure~\ref{fig:uniquify-Lvar}; that is, implement the cases for
  2952. variables and for the \key{let} form in the file \code{compiler.rkt}
  2953. in the support code.
  2954. \end{exercise}
  2955. \begin{exercise}
  2956. \normalfont\normalsize
  2957. \label{ex:Lvar}
  2958. Create five \LangVar{} programs that exercise the most interesting
  2959. parts of the \key{uniquify} pass; that is, the programs should include
  2960. \key{let} forms, variables, and variables that shadow each other.
  2961. The five programs should be placed in the subdirectory named
  2962. \key{tests}, and the file names should start with \code{var\_test\_}
  2963. followed by a unique integer and end with the file extension
  2964. \key{.rkt}.
  2965. %
  2966. The \key{run-tests.rkt} script in the support code checks whether the
  2967. output programs produce the same result as the input programs. The
  2968. script uses the \key{interp-tests} function
  2969. (appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2970. your \key{uniquify} pass on the example programs. The \code{passes}
  2971. parameter of \key{interp-tests} is a list that should have one entry
  2972. for each pass in your compiler. For now, define \code{passes} to
  2973. contain just one entry for \code{uniquify} as follows:
  2974. \begin{lstlisting}
  2975. (define passes
  2976. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2977. \end{lstlisting}
  2978. Run the \key{run-tests.rkt} script in the support code to check
  2979. whether the output programs produce the same result as the input
  2980. programs.
  2981. \end{exercise}
  2982. \fi}
  2983. \section{Remove Complex Operands}
  2984. \label{sec:remove-complex-opera-Lvar}
  2985. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2986. into a restricted form in which the arguments of operations are atomic
  2987. expressions. Put another way, this pass removes complex
  2988. operands\index{subject}{complex operand}, such as the expression
  2989. \racket{\code{(- 10)}}\python{\code{-10}}
  2990. in the following program. This is accomplished by introducing a new
  2991. temporary variable, assigning the complex operand to the new
  2992. variable, and then using the new variable in place of the complex
  2993. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2994. right.
  2995. {\if\edition\racketEd
  2996. \begin{transformation}
  2997. % var_test_19.rkt
  2998. \begin{lstlisting}
  2999. (let ([x (+ 42 (- 10))])
  3000. (+ x 10))
  3001. \end{lstlisting}
  3002. \compilesto
  3003. \begin{lstlisting}
  3004. (let ([x (let ([tmp.1 (- 10)])
  3005. (+ 42 tmp.1))])
  3006. (+ x 10))
  3007. \end{lstlisting}
  3008. \end{transformation}
  3009. \fi}
  3010. {\if\edition\pythonEd\pythonColor
  3011. \begin{transformation}
  3012. \begin{lstlisting}
  3013. x = 42 + -10
  3014. print(x + 10)
  3015. \end{lstlisting}
  3016. \compilesto
  3017. \begin{lstlisting}
  3018. tmp_0 = -10
  3019. x = 42 + tmp_0
  3020. tmp_1 = x + 10
  3021. print(tmp_1)
  3022. \end{lstlisting}
  3023. \end{transformation}
  3024. \fi}
  3025. \newcommand{\LvarMonadASTRacket}{
  3026. \begin{array}{rcl}
  3027. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3028. \Exp &::=& \Atm \MID \READ{} \\
  3029. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  3030. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  3031. \end{array}
  3032. }
  3033. \newcommand{\LvarMonadASTPython}{
  3034. \begin{array}{rcl}
  3035. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  3036. \Exp{} &::=& \Atm \MID \READ{} \\
  3037. &\MID& \UNIOP{\key{USub()}}{\Atm} \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  3038. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm} \\
  3039. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  3040. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  3041. \end{array}
  3042. }
  3043. \begin{figure}[tp]
  3044. \centering
  3045. \begin{tcolorbox}[colback=white]
  3046. {\if\edition\racketEd
  3047. \[
  3048. \begin{array}{l}
  3049. \LvarMonadASTRacket \\
  3050. \begin{array}{rcl}
  3051. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  3052. \end{array}
  3053. \end{array}
  3054. \]
  3055. \fi}
  3056. {\if\edition\pythonEd\pythonColor
  3057. \[
  3058. \begin{array}{l}
  3059. \LvarMonadASTPython \\
  3060. \begin{array}{rcl}
  3061. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  3062. \end{array}
  3063. \end{array}
  3064. \]
  3065. \fi}
  3066. \end{tcolorbox}
  3067. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  3068. atomic expressions.}
  3069. \label{fig:Lvar-anf-syntax}
  3070. \end{figure}
  3071. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  3072. of this pass, the language \LangVarANF{}. The only difference is that
  3073. operator arguments are restricted to be atomic expressions that are
  3074. defined by the \Atm{} nonterminal. In particular, integer constants
  3075. and variables are atomic.
  3076. The atomic expressions are pure (they do not cause or depend on side
  3077. effects) whereas complex expressions may have side effects, such as
  3078. \READ{}. A language with this separation between pure expressions
  3079. versus expressions with side effects is said to be in monadic normal
  3080. form~\citep{Moggi:1991in,Danvy:2003fk}, which explains the \textit{mon}
  3081. in the name \LangVarANF{}. An important invariant of the
  3082. \code{remove\_complex\_operands} pass is that the relative ordering
  3083. among complex expressions is not changed, but the relative ordering
  3084. between atomic expressions and complex expressions can change and
  3085. often does. These changes are behavior preserving because
  3086. atomic expressions are pure.
  3087. {\if\edition\racketEd
  3088. Another well-known form for intermediate languages is the
  3089. \emph{administrative normal form}
  3090. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  3091. \index{subject}{administrative normal form} \index{subject}{ANF}
  3092. %
  3093. The \LangVarANF{} language is not quite in ANF because it allows the
  3094. right-hand side of a \code{let} to be a complex expression, such as
  3095. another \code{let}. The flattening of nested \code{let} expressions is
  3096. instead one of the responsibilities of the \code{explicate\_control}
  3097. pass.
  3098. \fi}
  3099. {\if\edition\racketEd
  3100. We recommend implementing this pass with two mutually recursive
  3101. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  3102. \code{rco\_atom} to subexpressions that need to become atomic and to
  3103. apply \code{rco\_exp} to subexpressions that do not. Both functions
  3104. take an \LangVar{} expression as input. The \code{rco\_exp} function
  3105. returns an expression. The \code{rco\_atom} function returns two
  3106. things: an atomic expression and an alist mapping temporary variables to
  3107. complex subexpressions. You can return multiple things from a function
  3108. using Racket's \key{values} form, and you can receive multiple things
  3109. from a function call using the \key{define-values} form.
  3110. \fi}
  3111. %
  3112. {\if\edition\pythonEd\pythonColor
  3113. %
  3114. We recommend implementing this pass with an auxiliary method named
  3115. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  3116. Boolean that specifies whether the expression needs to become atomic
  3117. or not. The \code{rco\_exp} method should return a pair consisting of
  3118. the new expression and a list of pairs, associating new temporary
  3119. variables with their initializing expressions.
  3120. %
  3121. \fi}
  3122. {\if\edition\racketEd
  3123. %
  3124. In the example program with the expression \code{(+ 42 (-
  3125. 10))}, the subexpression \code{(- 10)} should be processed using the
  3126. \code{rco\_atom} function because it is an argument of the \code{+}
  3127. operator and therefore needs to become atomic. The output of
  3128. \code{rco\_atom} applied to \code{(- 10)} is as follows:
  3129. \begin{transformation}
  3130. \begin{lstlisting}
  3131. (- 10)
  3132. \end{lstlisting}
  3133. \compilesto
  3134. \begin{lstlisting}
  3135. tmp.1
  3136. ((tmp.1 . (- 10)))
  3137. \end{lstlisting}
  3138. \end{transformation}
  3139. \fi}
  3140. %
  3141. {\if\edition\pythonEd\pythonColor
  3142. %
  3143. Returning to the example program with the expression \code{42 + -10},
  3144. the subexpression \code{-10} should be processed using the
  3145. \code{rco\_exp} function with \code{True} as the second argument,
  3146. because \code{-10} is an argument of the \code{+} operator and
  3147. therefore needs to become atomic. The output of \code{rco\_exp}
  3148. applied to \code{-10} is as follows.
  3149. \begin{transformation}
  3150. \begin{lstlisting}
  3151. -10
  3152. \end{lstlisting}
  3153. \compilesto
  3154. \begin{lstlisting}
  3155. tmp_1
  3156. [(tmp_1, -10)]
  3157. \end{lstlisting}
  3158. \end{transformation}
  3159. %
  3160. \fi}
  3161. Take special care of programs, such as the following, that
  3162. %
  3163. \racket{bind a variable to an atomic expression.}
  3164. %
  3165. \python{assign an atomic expression to a variable.}
  3166. %
  3167. You should leave such \racket{variable bindings}\python{assignments}
  3168. unchanged, as shown in the program on the right:\\
  3169. %
  3170. {\if\edition\racketEd
  3171. \begin{transformation}
  3172. % var_test_20.rkt
  3173. \begin{lstlisting}
  3174. (let ([a 42])
  3175. (let ([b a])
  3176. b))
  3177. \end{lstlisting}
  3178. \compilesto
  3179. \begin{lstlisting}
  3180. (let ([a 42])
  3181. (let ([b a])
  3182. b))
  3183. \end{lstlisting}
  3184. \end{transformation}
  3185. \fi}
  3186. {\if\edition\pythonEd\pythonColor
  3187. \begin{transformation}
  3188. \begin{lstlisting}
  3189. a = 42
  3190. b = a
  3191. print(b)
  3192. \end{lstlisting}
  3193. \compilesto
  3194. \begin{lstlisting}
  3195. a = 42
  3196. b = a
  3197. print(b)
  3198. \end{lstlisting}
  3199. \end{transformation}
  3200. \fi}
  3201. %
  3202. \noindent A careless implementation might produce the following output with
  3203. unnecessary temporary variables.
  3204. \begin{center}
  3205. \begin{minipage}{0.4\textwidth}
  3206. {\if\edition\racketEd
  3207. \begin{lstlisting}
  3208. (let ([tmp.1 42])
  3209. (let ([a tmp.1])
  3210. (let ([tmp.2 a])
  3211. (let ([b tmp.2])
  3212. b))))
  3213. \end{lstlisting}
  3214. \fi}
  3215. {\if\edition\pythonEd\pythonColor
  3216. \begin{lstlisting}
  3217. tmp_1 = 42
  3218. a = tmp_1
  3219. tmp_2 = a
  3220. b = tmp_2
  3221. print(b)
  3222. \end{lstlisting}
  3223. \fi}
  3224. \end{minipage}
  3225. \end{center}
  3226. \begin{exercise}
  3227. \normalfont\normalsize
  3228. {\if\edition\racketEd
  3229. Implement the \code{remove\_complex\_operands} function in
  3230. \code{compiler.rkt}.
  3231. %
  3232. Create three new \LangVar{} programs that exercise the interesting
  3233. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3234. regarding file names described in exercise~\ref{ex:Lvar}.
  3235. %
  3236. In the \code{run-tests.rkt} script, add the following entry to the
  3237. list of \code{passes}, and then run the script to test your compiler.
  3238. \begin{lstlisting}
  3239. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3240. \end{lstlisting}
  3241. In debugging your compiler, it is often useful to see the intermediate
  3242. programs that are output from each pass. To print the intermediate
  3243. programs, place \lstinline{(debug-level 1)} before the call to
  3244. \code{interp-tests} in \code{run-tests.rkt}. \fi}
  3245. %
  3246. {\if\edition\pythonEd\pythonColor
  3247. Implement the \code{remove\_complex\_operands} pass in
  3248. \code{compiler.py}, creating auxiliary functions for each
  3249. nonterminal in the grammar, that is, \code{rco\_exp}
  3250. and \code{rco\_stmt}. We recommend that you use the function
  3251. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3252. \fi}
  3253. \end{exercise}
  3254. {\if\edition\pythonEd\pythonColor
  3255. \begin{exercise}
  3256. \normalfont\normalsize
  3257. \label{ex:Lvar}
  3258. Create five \LangVar{} programs that exercise the most interesting
  3259. parts of the \code{remove\_complex\_operands} pass. The five programs
  3260. should be placed in the subdirectory \key{tests/var}, and the file
  3261. names should end with the file extension \key{.py}. Run the
  3262. \key{run-tests.py} script in the support code to check whether the
  3263. output programs produce the same result as the input programs.
  3264. \end{exercise}
  3265. \fi}
  3266. {\if\edition\racketEd
  3267. \section{Explicate Control}
  3268. \label{sec:explicate-control-Lvar}
  3269. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3270. programs that make the order of execution explicit in their
  3271. syntax. For now this amounts to flattening \key{let} constructs into a
  3272. sequence of assignment statements. For example, consider the following
  3273. \LangVar{} program:\\
  3274. % var_test_11.rkt
  3275. \begin{minipage}{0.96\textwidth}
  3276. \begin{lstlisting}
  3277. (let ([y (let ([x 20])
  3278. (+ x (let ([x 22]) x)))])
  3279. y)
  3280. \end{lstlisting}
  3281. \end{minipage}\\
  3282. %
  3283. The output of the previous pass is shown next, on the left, and the
  3284. output of \code{explicate\_control} is on the right. Recall that the
  3285. right-hand side of a \key{let} executes before its body, so that the order
  3286. of evaluation for this program is to assign \code{20} to \code{x.1},
  3287. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, and then to
  3288. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3289. this ordering explicit.
  3290. \begin{transformation}
  3291. \begin{lstlisting}
  3292. (let ([y (let ([x.1 20])
  3293. (let ([x.2 22])
  3294. (+ x.1 x.2)))])
  3295. y)
  3296. \end{lstlisting}
  3297. \compilesto
  3298. \begin{lstlisting}[language=C]
  3299. start:
  3300. x.1 = 20;
  3301. x.2 = 22;
  3302. y = (+ x.1 x.2);
  3303. return y;
  3304. \end{lstlisting}
  3305. \end{transformation}
  3306. \begin{figure}[tbp]
  3307. \begin{tcolorbox}[colback=white]
  3308. \begin{lstlisting}
  3309. (define (explicate_tail e)
  3310. (match e
  3311. [(Var x) ___]
  3312. [(Int n) (Return (Int n))]
  3313. [(Let x rhs body) ___]
  3314. [(Prim op es) ___]
  3315. [else (error "explicate_tail unhandled case" e)]))
  3316. (define (explicate_assign e x cont)
  3317. (match e
  3318. [(Var x) ___]
  3319. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3320. [(Let y rhs body) ___]
  3321. [(Prim op es) ___]
  3322. [else (error "explicate_assign unhandled case" e)]))
  3323. (define (explicate_control p)
  3324. (match p
  3325. [(Program info body) ___]))
  3326. \end{lstlisting}
  3327. \end{tcolorbox}
  3328. \caption{Skeleton for the \code{explicate\_control} pass.}
  3329. \label{fig:explicate-control-Lvar}
  3330. \end{figure}
  3331. The organization of this pass depends on the notion of tail position
  3332. to which we have alluded. Here is the definition.
  3333. \begin{definition}\normalfont
  3334. The following rules define when an expression is in \emph{tail
  3335. position}\index{subject}{tail position} for the language \LangVar{}.
  3336. \begin{enumerate}
  3337. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3338. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3339. \end{enumerate}
  3340. \end{definition}
  3341. We recommend implementing \code{explicate\_control} using two
  3342. recursive functions, \code{explicate\_tail} and
  3343. \code{explicate\_assign}, as suggested in the skeleton code shown in
  3344. figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3345. function should be applied to expressions in tail position, whereas the
  3346. \code{explicate\_assign} should be applied to expressions that occur on
  3347. the right-hand side of a \key{let}.
  3348. %
  3349. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3350. input and produces a \Tail{} in \LangCVar{} (see
  3351. figure~\ref{fig:c0-syntax}).
  3352. %
  3353. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3354. the variable to which it is to be assigned, and a \Tail{} in
  3355. \LangCVar{} for the code that comes after the assignment. The
  3356. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3357. The \code{explicate\_assign} function is in accumulator-passing style:
  3358. the \code{cont} parameter is used for accumulating the output. This
  3359. accumulator-passing style plays an important role in the way that we
  3360. generate high-quality code for conditional expressions in
  3361. chapter~\ref{ch:Lif}. The abbreviation \code{cont} is for
  3362. continuation because it contains the generated code that should come
  3363. after the current assignment. This code organization is also related
  3364. to continuation-passing style, except that \code{cont} is not what
  3365. happens next during compilation but is what happens next in the
  3366. generated code.
  3367. \begin{exercise}\normalfont\normalsize
  3368. %
  3369. Implement the \code{explicate\_control} function in
  3370. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3371. exercise the code in \code{explicate\_control}.
  3372. %
  3373. In the \code{run-tests.rkt} script, add the following entry to the
  3374. list of \code{passes} and then run the script to test your compiler.
  3375. \begin{lstlisting}
  3376. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3377. \end{lstlisting}
  3378. \end{exercise}
  3379. \fi}
  3380. \section{Select Instructions}
  3381. \label{sec:select-Lvar}
  3382. \index{subject}{select instructions}
  3383. In the \code{select\_instructions} pass we begin the work of
  3384. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3385. language of this pass is a variant of x86 that still uses variables,
  3386. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3387. nonterminal of the \LangXInt{} abstract syntax
  3388. (figure~\ref{fig:x86-int-ast}).
  3389. \racket{We recommend implementing the
  3390. \code{select\_instructions} with three auxiliary functions, one for
  3391. each of the nonterminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3392. $\Tail$.}
  3393. \python{We recommend implementing an auxiliary function
  3394. named \code{select\_stmt} for the $\Stmt$ nonterminal.}
  3395. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3396. same and integer constants change to immediates; that is, $\INT{n}$
  3397. changes to $\IMM{n}$.}
  3398. Next consider the cases for the $\Stmt$ nonterminal, starting with
  3399. arithmetic operations. For example, consider the following addition
  3400. operation, on the left side. (Let $\Arg_1$ and $\Arg_2$ be the
  3401. translations of $\Atm_1$ and $\Atm_2$, respectively.) There is an
  3402. \key{addq} instruction in x86, but it performs an in-place update.
  3403. %
  3404. So, we could move $\Arg_1$ into the \code{rax} register, then add
  3405. $\Arg_2$ to \code{rax}, and then finally move \code{rax} into \itm{var}.
  3406. \begin{transformation}
  3407. {\if\edition\racketEd
  3408. \begin{lstlisting}
  3409. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3410. \end{lstlisting}
  3411. \fi}
  3412. {\if\edition\pythonEd\pythonColor
  3413. \begin{lstlisting}
  3414. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3415. \end{lstlisting}
  3416. \fi}
  3417. \compilesto
  3418. \begin{lstlisting}
  3419. movq |$\Arg_1$|, %rax
  3420. addq |$\Arg_2$|, %rax
  3421. movq %rax, |$\itm{var}$|
  3422. \end{lstlisting}
  3423. \end{transformation}
  3424. %
  3425. However, with some care we can generate shorter sequences of
  3426. instructions. Suppose that one or more of the arguments of the
  3427. addition is the same variable as the left-hand side of the assignment.
  3428. Then the assignment statement can be translated into a single
  3429. \key{addq} instruction, as follows.
  3430. \begin{transformation}
  3431. {\if\edition\racketEd
  3432. \begin{lstlisting}
  3433. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3434. \end{lstlisting}
  3435. \fi}
  3436. {\if\edition\pythonEd\pythonColor
  3437. \begin{lstlisting}
  3438. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3439. \end{lstlisting}
  3440. \fi}
  3441. \compilesto
  3442. \begin{lstlisting}
  3443. addq |$\Arg_1$|, |$\itm{var}$|
  3444. \end{lstlisting}
  3445. \end{transformation}
  3446. %
  3447. On the other hand, if $\Atm_1$ is not the same variable as the
  3448. left-hand side, then we can move $\Arg_1$ into the left-hand \itm{var}
  3449. and then add $\Arg_2$ to \itm{var}.
  3450. %
  3451. \begin{transformation}
  3452. {\if\edition\racketEd
  3453. \begin{lstlisting}
  3454. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3455. \end{lstlisting}
  3456. \fi}
  3457. {\if\edition\pythonEd\pythonColor
  3458. \begin{lstlisting}
  3459. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3460. \end{lstlisting}
  3461. \fi}
  3462. \compilesto
  3463. \begin{lstlisting}
  3464. movq |$\Arg_1$|, |$\itm{var}$|
  3465. addq |$\Arg_2$|, |$\itm{var}$|
  3466. \end{lstlisting}
  3467. \end{transformation}
  3468. The \READOP{} operation does not have a direct counterpart in x86
  3469. assembly, so we provide this functionality with the function
  3470. \code{read\_int} in the file \code{runtime.c}, written in
  3471. C~\citep{Kernighan:1988nx}. In general, we refer to all the
  3472. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3473. system}, or simply the \emph{runtime} for short. When compiling your
  3474. generated x86 assembly code, you need to compile \code{runtime.c} to
  3475. \code{runtime.o} (an \emph{object file}, using \code{gcc} with option
  3476. \code{-c}) and link it into the executable. For our purposes of code
  3477. generation, all you need to do is translate an assignment of
  3478. \READOP{} into a call to the \code{read\_int} function followed by a
  3479. move from \code{rax} to the left-hand side variable. (The
  3480. return value of a function is placed in \code{rax}.)
  3481. \begin{transformation}
  3482. {\if\edition\racketEd
  3483. \begin{lstlisting}
  3484. |$\itm{var}$| = (read);
  3485. \end{lstlisting}
  3486. \fi}
  3487. {\if\edition\pythonEd\pythonColor
  3488. \begin{lstlisting}
  3489. |$\itm{var}$| = input_int();
  3490. \end{lstlisting}
  3491. \fi}
  3492. \compilesto
  3493. \begin{lstlisting}
  3494. callq read_int
  3495. movq %rax, |$\itm{var}$|
  3496. \end{lstlisting}
  3497. \end{transformation}
  3498. {\if\edition\pythonEd\pythonColor
  3499. %
  3500. Similarly, we translate the \code{print} operation, shown below, into
  3501. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3502. In x86, the first six arguments to functions are passed in registers,
  3503. with the first argument passed in register \code{rdi}. So we move the
  3504. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3505. \code{callq} instruction.
  3506. \begin{transformation}
  3507. \begin{lstlisting}
  3508. print(|$\Atm$|)
  3509. \end{lstlisting}
  3510. \compilesto
  3511. \begin{lstlisting}
  3512. movq |$\Arg$|, %rdi
  3513. callq print_int
  3514. \end{lstlisting}
  3515. \end{transformation}
  3516. %
  3517. \fi}
  3518. {\if\edition\racketEd
  3519. There are two cases for the $\Tail$ nonterminal: \key{Return} and
  3520. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3521. assignment to the \key{rax} register followed by a jump to the
  3522. conclusion of the program (so the conclusion needs to be labeled).
  3523. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3524. recursively and then append the resulting instructions.
  3525. \fi}
  3526. {\if\edition\pythonEd\pythonColor
  3527. We recommend that you use the function \code{utils.label\_name} to
  3528. transform strings into labels, for example, in
  3529. the target of the \code{callq} instruction. This practice makes your
  3530. compiler portable across Linux and Mac OS X, which requires an underscore
  3531. prefixed to all labels.
  3532. \fi}
  3533. \begin{exercise}
  3534. \normalfont\normalsize
  3535. {\if\edition\racketEd
  3536. Implement the \code{select\_instructions} pass in
  3537. \code{compiler.rkt}. Create three new example programs that are
  3538. designed to exercise all the interesting cases in this pass.
  3539. %
  3540. In the \code{run-tests.rkt} script, add the following entry to the
  3541. list of \code{passes} and then run the script to test your compiler.
  3542. \begin{lstlisting}
  3543. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3544. \end{lstlisting}
  3545. \fi}
  3546. {\if\edition\pythonEd\pythonColor
  3547. Implement the \key{select\_instructions} pass in
  3548. \code{compiler.py}. Create three new example programs that are
  3549. designed to exercise all the interesting cases in this pass.
  3550. Run the \code{run-tests.py} script to check
  3551. whether the output programs produce the same result as the input
  3552. programs.
  3553. \fi}
  3554. \end{exercise}
  3555. \section{Assign Homes}
  3556. \label{sec:assign-Lvar}
  3557. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3558. \LangXVar{} programs that no longer use program variables. Thus, the
  3559. \code{assign\_homes} pass is responsible for placing all the program
  3560. variables in registers or on the stack. For runtime efficiency, it is
  3561. better to place variables in registers, but because there are only
  3562. sixteen registers, some programs must necessarily resort to placing
  3563. some variables on the stack. In this chapter we focus on the mechanics
  3564. of placing variables on the stack. We study an algorithm for placing
  3565. variables in registers in chapter~\ref{ch:register-allocation-Lvar}.
  3566. Consider again the following \LangVar{} program from
  3567. section~\ref{sec:remove-complex-opera-Lvar}:\\
  3568. % var_test_20.rkt
  3569. \begin{minipage}{0.96\textwidth}
  3570. {\if\edition\racketEd
  3571. \begin{lstlisting}
  3572. (let ([a 42])
  3573. (let ([b a])
  3574. b))
  3575. \end{lstlisting}
  3576. \fi}
  3577. {\if\edition\pythonEd\pythonColor
  3578. \begin{lstlisting}
  3579. a = 42
  3580. b = a
  3581. print(b)
  3582. \end{lstlisting}
  3583. \fi}
  3584. \end{minipage}\\
  3585. %
  3586. The output of \code{select\_instructions} is shown next, on the left,
  3587. and the output of \code{assign\_homes} is on the right. In this
  3588. example, we assign variable \code{a} to stack location
  3589. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3590. \begin{transformation}
  3591. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3592. movq $42, a
  3593. movq a, b
  3594. movq b, %rax
  3595. \end{lstlisting}
  3596. \compilesto
  3597. %stack-space: 16
  3598. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3599. movq $42, -8(%rbp)
  3600. movq -8(%rbp), -16(%rbp)
  3601. movq -16(%rbp), %rax
  3602. \end{lstlisting}
  3603. \end{transformation}
  3604. \racket{
  3605. The \code{assign\_homes} pass should replace all variables
  3606. with stack locations.
  3607. The list of variables can be obtained from
  3608. the \code{locals-types} entry in the $\itm{info}$ of the
  3609. \code{X86Program} node. The \code{locals-types} entry is an alist
  3610. mapping all the variables in the program to their types
  3611. (for now, just \code{Integer}).
  3612. As an aside, the \code{locals-types} entry is
  3613. computed by \code{type-check-Cvar} in the support code, which
  3614. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3615. which you should propagate to the \code{X86Program} node.}
  3616. %
  3617. \python{The \code{assign\_homes} pass should replace all uses of
  3618. variables with stack locations.}
  3619. %
  3620. In the process of assigning variables to stack locations, it is
  3621. convenient for you to compute and store the size of the frame (in
  3622. bytes) in
  3623. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3624. %
  3625. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3626. %
  3627. which is needed later to generate the conclusion of the \code{main}
  3628. procedure. The x86-64 standard requires the frame size to be a
  3629. multiple of 16 bytes.\index{subject}{frame}
  3630. % TODO: store the number of variables instead? -Jeremy
  3631. \begin{exercise}\normalfont\normalsize
  3632. Implement the \code{assign\_homes} pass in
  3633. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3634. auxiliary functions for each of the nonterminals in the \LangXVar{}
  3635. grammar. We recommend that the auxiliary functions take an extra
  3636. parameter that maps variable names to homes (stack locations for now).
  3637. %
  3638. {\if\edition\racketEd
  3639. In the \code{run-tests.rkt} script, add the following entry to the
  3640. list of \code{passes} and then run the script to test your compiler.
  3641. \begin{lstlisting}
  3642. (list "assign homes" assign-homes interp_x86-0)
  3643. \end{lstlisting}
  3644. \fi}
  3645. {\if\edition\pythonEd\pythonColor
  3646. Run the \code{run-tests.py} script to check
  3647. whether the output programs produce the same result as the input
  3648. programs.
  3649. \fi}
  3650. \end{exercise}
  3651. \section{Patch Instructions}
  3652. \label{sec:patch-s0}
  3653. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3654. \LangXInt{} by making sure that each instruction adheres to the
  3655. restriction that at most one argument of an instruction may be a
  3656. memory reference.
  3657. We return to the following example.\\
  3658. \begin{minipage}{0.5\textwidth}
  3659. % var_test_20.rkt
  3660. {\if\edition\racketEd
  3661. \begin{lstlisting}
  3662. (let ([a 42])
  3663. (let ([b a])
  3664. b))
  3665. \end{lstlisting}
  3666. \fi}
  3667. {\if\edition\pythonEd\pythonColor
  3668. \begin{lstlisting}
  3669. a = 42
  3670. b = a
  3671. print(b)
  3672. \end{lstlisting}
  3673. \fi}
  3674. \end{minipage}\\
  3675. The \code{assign\_homes} pass produces the following translation. \\
  3676. \begin{minipage}{0.5\textwidth}
  3677. {\if\edition\racketEd
  3678. \begin{lstlisting}
  3679. movq $42, -8(%rbp)
  3680. movq -8(%rbp), -16(%rbp)
  3681. movq -16(%rbp), %rax
  3682. \end{lstlisting}
  3683. \fi}
  3684. {\if\edition\pythonEd\pythonColor
  3685. \begin{lstlisting}
  3686. movq $42, -8(%rbp)
  3687. movq -8(%rbp), -16(%rbp)
  3688. movq -16(%rbp), %rdi
  3689. callq print_int
  3690. \end{lstlisting}
  3691. \fi}
  3692. \end{minipage}\\
  3693. The second \key{movq} instruction is problematic because both
  3694. arguments are stack locations. We suggest fixing this problem by
  3695. moving from the source location to the register \key{rax} and then
  3696. from \key{rax} to the destination location, as follows.
  3697. \begin{lstlisting}
  3698. movq -8(%rbp), %rax
  3699. movq %rax, -16(%rbp)
  3700. \end{lstlisting}
  3701. There is a similar corner case that also needs to be dealt with. If
  3702. one argument is an immediate integer larger than $2^{16}$ and the
  3703. other is a memory reference, then the instruction is invalid. One can
  3704. fix this, for example, by first moving the immediate integer into
  3705. \key{rax} and then using \key{rax} in place of the integer.
  3706. \begin{exercise}
  3707. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3708. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3709. Create three new example programs that are
  3710. designed to exercise all the interesting cases in this pass.
  3711. %
  3712. {\if\edition\racketEd
  3713. In the \code{run-tests.rkt} script, add the following entry to the
  3714. list of \code{passes} and then run the script to test your compiler.
  3715. \begin{lstlisting}
  3716. (list "patch instructions" patch_instructions interp_x86-0)
  3717. \end{lstlisting}
  3718. \fi}
  3719. {\if\edition\pythonEd\pythonColor
  3720. Run the \code{run-tests.py} script to check
  3721. whether the output programs produce the same result as the input
  3722. programs.
  3723. \fi}
  3724. \end{exercise}
  3725. \section{Generate Prelude and Conclusion}
  3726. \label{sec:print-x86}
  3727. \index{subject}{prelude}\index{subject}{conclusion}
  3728. The last step of the compiler from \LangVar{} to x86 is to generate
  3729. the \code{main} function with a prelude and conclusion wrapped around
  3730. the rest of the program, as shown in figure~\ref{fig:p1-x86} and
  3731. discussed in section~\ref{sec:x86}.
  3732. When running on Mac OS X, your compiler should prefix an underscore to
  3733. all labels (for example, changing \key{main} to \key{\_main}).
  3734. %
  3735. \racket{The Racket call \code{(system-type 'os)} is useful for
  3736. determining which operating system the compiler is running on. It
  3737. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3738. %
  3739. \python{The Python \code{platform.system}
  3740. function returns \code{\textquotesingle Linux\textquotesingle},
  3741. \code{\textquotesingle Windows\textquotesingle}, or
  3742. \code{\textquotesingle Darwin\textquotesingle} (for Mac).}
  3743. \begin{exercise}\normalfont\normalsize
  3744. %
  3745. Implement the \key{prelude\_and\_conclusion} pass in
  3746. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3747. %
  3748. {\if\edition\racketEd
  3749. In the \code{run-tests.rkt} script, add the following entry to the
  3750. list of \code{passes} and then run the script to test your compiler.
  3751. \begin{lstlisting}
  3752. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3753. \end{lstlisting}
  3754. %
  3755. Uncomment the call to the \key{compiler-tests} function
  3756. (appendix~\ref{appendix:utilities}), which tests your complete
  3757. compiler by executing the generated x86 code. It translates the x86
  3758. AST that you produce into a string by invoking the \code{print-x86}
  3759. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3760. the provided \key{runtime.c} file to \key{runtime.o} using
  3761. \key{gcc}. Run the script to test your compiler.
  3762. %
  3763. \fi}
  3764. {\if\edition\pythonEd\pythonColor
  3765. %
  3766. Run the \code{run-tests.py} script to check whether the output
  3767. programs produce the same result as the input programs. That script
  3768. translates the x86 AST that you produce into a string by invoking the
  3769. \code{repr} method that is implemented by the x86 AST classes in
  3770. \code{x86\_ast.py}.
  3771. %
  3772. \fi}
  3773. \end{exercise}
  3774. \section{Challenge: Partial Evaluator for \LangVar{}}
  3775. \label{sec:pe-Lvar}
  3776. \index{subject}{partialevaluation@partial evaluation}
  3777. This section describes two optional challenge exercises that involve
  3778. adapting and improving the partial evaluator for \LangInt{} that was
  3779. introduced in section~\ref{sec:partial-evaluation}.
  3780. \begin{exercise}\label{ex:pe-Lvar}
  3781. \normalfont\normalsize
  3782. Adapt the partial evaluator from section~\ref{sec:partial-evaluation}
  3783. (figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3784. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3785. %
  3786. \racket{\key{let} binding}\python{assignment}
  3787. %
  3788. to the \LangInt{} language, so you will need to add cases for them in
  3789. the \code{pe\_exp}
  3790. %
  3791. \racket{function.}
  3792. %
  3793. \python{and \code{pe\_stmt} functions.}
  3794. %
  3795. Once complete, add the partial evaluation pass to the front of your
  3796. compiler, and check that your compiler still passes all the
  3797. tests.
  3798. \end{exercise}
  3799. \begin{exercise}
  3800. \normalfont\normalsize
  3801. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3802. \code{pe\_add} auxiliary functions with functions that know more about
  3803. arithmetic. For example, your partial evaluator should translate
  3804. {\if\edition\racketEd
  3805. \[
  3806. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3807. \code{(+ 2 (read))}
  3808. \]
  3809. \fi}
  3810. {\if\edition\pythonEd\pythonColor
  3811. \[
  3812. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3813. \code{2 + input\_int()}
  3814. \]
  3815. \fi}
  3816. %
  3817. To accomplish this, the \code{pe\_exp} function should produce output
  3818. in the form of the $\itm{residual}$ nonterminal of the following
  3819. grammar. The idea is that when processing an addition expression, we
  3820. can always produce one of the following: (1) an integer constant, (2)
  3821. an addition expression with an integer constant on the left-hand side
  3822. but not the right-hand side, or (3) an addition expression in which
  3823. neither subexpression is a constant.
  3824. %
  3825. {\if\edition\racketEd
  3826. \[
  3827. \begin{array}{lcl}
  3828. \itm{inert} &::=& \Var
  3829. \MID \LP\key{read}\RP
  3830. \MID \LP\key{-} ~\Var\RP
  3831. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3832. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3833. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3834. \itm{residual} &::=& \Int
  3835. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3836. \MID \itm{inert}
  3837. \end{array}
  3838. \]
  3839. \fi}
  3840. {\if\edition\pythonEd\pythonColor
  3841. \[
  3842. \begin{array}{lcl}
  3843. \itm{inert} &::=& \Var
  3844. \MID \key{input\_int}\LP\RP
  3845. \MID \key{-} \Var
  3846. \MID \key{-} \key{input\_int}\LP\RP
  3847. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3848. \itm{residual} &::=& \Int
  3849. \MID \Int ~ \key{+} ~ \itm{inert}
  3850. \MID \itm{inert}
  3851. \end{array}
  3852. \]
  3853. \fi}
  3854. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3855. inputs are $\itm{residual}$ expressions and they should return
  3856. $\itm{residual}$ expressions. Once the improvements are complete,
  3857. make sure that your compiler still passes all the tests. After
  3858. all, fast code is useless if it produces incorrect results!
  3859. \end{exercise}
  3860. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3861. {\if\edition\pythonEd\pythonColor
  3862. \chapter{Parsing}
  3863. \label{ch:parsing}
  3864. \setcounter{footnote}{0}
  3865. \index{subject}{parsing}
  3866. In this chapter we learn how to use the Lark parser
  3867. framework~\citep{shinan20:_lark_docs} to translate the concrete syntax
  3868. of \LangInt{} (a sequence of characters) into an abstract syntax tree.
  3869. You are then asked to create a parser for \LangVar{} using Lark.
  3870. We also describe the parsing algorithms used inside Lark, studying the
  3871. \citet{Earley:1970ly} and LALR(1) algorithms~\citep{DeRemer69,Anderson73}.
  3872. A parser framework such as Lark takes in a specification of the
  3873. concrete syntax and an input program and produces a parse tree. Even
  3874. though a parser framework does most of the work for us, using one
  3875. properly requires some knowledge. In particular, we must learn about
  3876. its specification languages and we must learn how to deal with
  3877. ambiguity in our language specifications. Also, some algorithms, such
  3878. as LALR(1), place restrictions on the grammars they can handle, in
  3879. which case knowing the algorithm helps with trying to decipher the
  3880. error messages.
  3881. The process of parsing is traditionally subdivided into two phases:
  3882. \emph{lexical analysis} (also called scanning) and \emph{syntax
  3883. analysis} (also called parsing). The lexical analysis phase
  3884. translates the sequence of characters into a sequence of
  3885. \emph{tokens}, that is, words consisting of several characters. The
  3886. parsing phase organizes the tokens into a \emph{parse tree} that
  3887. captures how the tokens were matched by rules in the grammar of the
  3888. language. The reason for the subdivision into two phases is to enable
  3889. the use of a faster but less powerful algorithm for lexical analysis
  3890. and the use of a slower but more powerful algorithm for parsing.
  3891. %
  3892. %% Likewise, parser generators typical come in pairs, with separate
  3893. %% generators for the lexical analyzer (or lexer for short) and for the
  3894. %% parser. A particularly influential pair of generators were
  3895. %% \texttt{lex} and \texttt{yacc}. The \texttt{lex} generator was written
  3896. %% by \citet{Lesk:1975uq} at Bell Labs. The \texttt{yacc} generator was
  3897. %% written by \citet{Johnson:1979qy} at AT\&T and stands for Yet Another
  3898. %% Compiler Compiler.
  3899. %
  3900. The Lark parser framework that we use in this chapter includes both
  3901. lexical analyzers and parsers. The next section discusses lexical
  3902. analysis, and the remainder of the chapter discusses parsing.
  3903. \section{Lexical Analysis and Regular Expressions}
  3904. \label{sec:lex}
  3905. The lexical analyzers produced by Lark turn a sequence of characters
  3906. (a string) into a sequence of token objects. For example, a Lark
  3907. generated lexer for \LangInt{} converts the string
  3908. \begin{lstlisting}
  3909. 'print(1 + 3)'
  3910. \end{lstlisting}
  3911. \noindent into the following sequence of token objects:
  3912. \begin{center}
  3913. \begin{minipage}{0.95\textwidth}
  3914. \begin{lstlisting}
  3915. Token('PRINT', 'print')
  3916. Token('LPAR', '(')
  3917. Token('INT', '1')
  3918. Token('PLUS', '+')
  3919. Token('INT', '3')
  3920. Token('RPAR', ')')
  3921. Token('NEWLINE', '\n')
  3922. \end{lstlisting}
  3923. \end{minipage}
  3924. \end{center}
  3925. Each token includes a field for its \code{type}, such as \skey{INT},
  3926. and a field for its \code{value}, such as \skey{1}.
  3927. Following in the tradition of \code{lex}~\citep{Lesk:1975uq}, the
  3928. specification language for Lark's lexer is one regular expression for
  3929. each type of token. The term \emph{regular} comes from the term
  3930. \emph{regular languages}, which are the languages that can be
  3931. recognized by a finite state machine. A \emph{regular expression} is a
  3932. pattern formed of the following core elements:\index{subject}{regular
  3933. expression}\footnote{Regular expressions traditionally include the
  3934. empty regular expression that matches any zero-length part of a
  3935. string, but Lark does not support the empty regular expression.}
  3936. \begin{itemize}
  3937. \item A single character $c$ is a regular expression, and it matches
  3938. only itself. For example, the regular expression \code{a} matches
  3939. only the string \skey{a}.
  3940. \item Two regular expressions separated by a vertical bar $R_1 \ttm{|}
  3941. R_2$ form a regular expression that matches any string that matches
  3942. $R_1$ or $R_2$. For example, the regular expression \code{a|c}
  3943. matches the string \skey{a} and the string \skey{c}.
  3944. \item Two regular expressions in sequence $R_1 R_2$ form a regular
  3945. expression that matches any string that can be formed by
  3946. concatenating two strings, where the first string matches $R_1$ and
  3947. the second string matches $R_2$. For example, the regular expression
  3948. \code{(a|c)b} matches the strings \skey{ab} and \skey{cb}.
  3949. (Parentheses can be used to control the grouping of operators within
  3950. a regular expression.)
  3951. \item A regular expression followed by an asterisks $R\ttm{*}$ (called
  3952. Kleene closure) is a regular expression that matches any string that
  3953. can be formed by concatenating zero or more strings that each match
  3954. the regular expression $R$. For example, the regular expression
  3955. \code{((a|c)b)*} matches the string \skey{abcbab} but not
  3956. \skey{abc}.
  3957. \end{itemize}
  3958. For our convenience, Lark also accepts the following extended set of
  3959. regular expressions that are automatically translated into the core
  3960. regular expressions.
  3961. \begin{itemize}
  3962. \item A set of characters enclosed in square brackets $[c_1 c_2 \ldots
  3963. c_n]$ is a regular expression that matches any one of the
  3964. characters. So, $[c_1 c_2 \ldots c_n]$ is equivalent to
  3965. the regular expression $c_1\mid c_2\mid \ldots \mid c_n$.
  3966. \item A range of characters enclosed in square brackets $[c_1\ttm{-}c_2]$ is
  3967. a regular expression that matches any character between $c_1$ and
  3968. $c_2$, inclusive. For example, \code{[a-z]} matches any lowercase
  3969. letter in the alphabet.
  3970. \item A regular expression followed by the plus symbol $R\ttm{+}$
  3971. is a regular expression that matches any string that can
  3972. be formed by concatenating one or more strings that each match $R$.
  3973. So $R+$ is equivalent to $R(R*)$. For example, \code{[a-z]+}
  3974. matches \skey{b} and \skey{bzca}.
  3975. \item A regular expression followed by a question mark $R\ttm{?}$
  3976. is a regular expression that matches any string that either
  3977. matches $R$ or is the empty string.
  3978. For example, \code{a?b} matches both \skey{ab} and \skey{b}.
  3979. \end{itemize}
  3980. In a Lark grammar file, each kind of token is specified by a
  3981. \emph{terminal}\index{subject}{terminal}, which is defined by a rule
  3982. that consists of the name of the terminal followed by a colon followed
  3983. by a sequence of literals. The literals include strings such as
  3984. \code{"abc"}, regular expressions surrounded by \code{/} characters,
  3985. terminal names, and literals composed using the regular expression
  3986. operators ($+$, $*$, etc.). For example, the \code{DIGIT},
  3987. \code{INT}, and \code{NEWLINE} terminals are specified as follows:
  3988. \begin{center}
  3989. \begin{minipage}{0.95\textwidth}
  3990. \begin{lstlisting}
  3991. DIGIT: /[0-9]/
  3992. INT: "-"? DIGIT+
  3993. NEWLINE: (/\r/? /\n/)+
  3994. \end{lstlisting}
  3995. \end{minipage}
  3996. \end{center}
  3997. \section{Grammars and Parse Trees}
  3998. \label{sec:CFG}
  3999. In section~\ref{sec:grammar} we learned how to use grammar rules to
  4000. specify the abstract syntax of a language. We now take a closer look
  4001. at using grammar rules to specify the concrete syntax. Recall that
  4002. each rule has a left-hand side and a right-hand side, where the
  4003. left-hand side is a nonterminal and the right-hand side is a pattern
  4004. that defines what can be parsed as that nonterminal. For concrete
  4005. syntax, each right-hand side expresses a pattern for a string instead
  4006. of a pattern for an abstract syntax tree. In particular, each
  4007. right-hand side is a sequence of
  4008. \emph{symbols}\index{subject}{symbol}, where a symbol is either a
  4009. terminal or a nonterminal. The nonterminals play the same role as in
  4010. the abstract syntax, defining categories of syntax. The nonterminals
  4011. of a grammar include the tokens defined in the lexer and all the
  4012. nonterminals defined by the grammar rules.
  4013. As an example, let us take a closer look at the concrete syntax of the
  4014. \LangInt{} language, repeated here.
  4015. \[
  4016. \begin{array}{l}
  4017. \LintGrammarPython \\
  4018. \begin{array}{rcl}
  4019. \LangInt{} &::=& \Stmt^{*}
  4020. \end{array}
  4021. \end{array}
  4022. \]
  4023. The Lark syntax for grammar rules differs slightly from the variant of
  4024. BNF that we use in this book. In particular, the notation $::=$ is
  4025. replaced by a single colon, and the use of typewriter font for string
  4026. literals is replaced by quotation marks. The following grammar serves
  4027. as a first draft of a Lark grammar for \LangInt{}.
  4028. \begin{center}
  4029. \begin{minipage}{0.95\textwidth}
  4030. \begin{lstlisting}[escapechar=$]
  4031. exp: INT
  4032. | "input_int" "(" ")"
  4033. | "-" exp
  4034. | exp "+" exp
  4035. | exp "-" exp
  4036. | "(" exp ")"
  4037. stmt_list:
  4038. | stmt NEWLINE stmt_list
  4039. lang_int: stmt_list
  4040. \end{lstlisting}
  4041. \end{minipage}
  4042. \end{center}
  4043. Let us begin by discussing the rule \code{exp: INT}, which says that
  4044. if the lexer matches a string to \code{INT}, then the parser also
  4045. categorizes the string as an \code{exp}. Recall that in
  4046. section~\ref{sec:grammar} we defined the corresponding \Int{}
  4047. nonterminal with a sentence in English. Here we specify \code{INT}
  4048. more formally using a type of token \code{INT} and its regular
  4049. expression \code{"-"? DIGIT+}.
  4050. The rule \code{exp: exp "+" exp} says that any string that matches
  4051. \code{exp}, followed by the \code{+} character, followed by another
  4052. string that matches \code{exp}, is itself an \code{exp}. For example,
  4053. the string \lstinline{'1+3'} is an \code{exp} because \lstinline{'1'} and
  4054. \lstinline{'3'} are both \code{exp} by the rule \code{exp: INT}, and then
  4055. the rule for addition applies to categorize \lstinline{'1+3'} as an
  4056. \code{exp}. We can visualize the application of grammar rules to parse
  4057. a string using a \emph{parse tree}\index{subject}{parse tree}. Each
  4058. internal node in the tree is an application of a grammar rule and is
  4059. labeled with its left-hand side nonterminal. Each leaf node is a
  4060. substring of the input program. The parse tree for \lstinline{'1+3'} is
  4061. shown in figure~\ref{fig:simple-parse-tree}.
  4062. \begin{figure}[tbp]
  4063. \begin{tcolorbox}[colback=white]
  4064. \centering
  4065. \includegraphics[width=1.9in]{figs/simple-parse-tree}
  4066. \end{tcolorbox}
  4067. \caption{The parse tree for \lstinline{'1+3'}.}
  4068. \label{fig:simple-parse-tree}
  4069. \end{figure}
  4070. The result of parsing \lstinline{'1+3'} with this Lark grammar is the
  4071. following parse tree as represented by \code{Tree} and \code{Token}
  4072. objects.
  4073. \begin{lstlisting}
  4074. Tree('lang_int',
  4075. [Tree('stmt', [Tree('exp', [Tree('exp', [Token('INT', '1')]),
  4076. Tree('exp', [Token('INT', '3')])])]),
  4077. Token('NEWLINE', '\n')])
  4078. \end{lstlisting}
  4079. The nodes that come from the lexer are \code{Token} objects, whereas
  4080. the nodes from the parser are \code{Tree} objects. Each \code{Tree}
  4081. object has a \code{data} field containing the name of the nonterminal
  4082. for the grammar rule that was applied. Each \code{Tree} object also
  4083. has a \code{children} field that is a list containing trees and/or
  4084. tokens. Note that Lark does not produce nodes for string literals in
  4085. the grammar. For example, the \code{Tree} node for the addition
  4086. expression has only two children for the two integers but is missing
  4087. its middle child for the \code{"+"} terminal. This would be
  4088. problematic except that Lark provides a mechanism for customizing the
  4089. \code{data} field of each \code{Tree} node on the basis of which rule was
  4090. applied. Next to each alternative in a grammar rule, write \code{->}
  4091. followed by a string that you want to appear in the \code{data}
  4092. field. The following is a second draft of a Lark grammar for
  4093. \LangInt{}, this time with more specific labels on the \code{Tree}
  4094. nodes.
  4095. \begin{center}
  4096. \begin{minipage}{0.95\textwidth}
  4097. \begin{lstlisting}[escapechar=$]
  4098. exp: INT -> int
  4099. | "input_int" "(" ")" -> input_int
  4100. | "-" exp -> usub
  4101. | exp "+" exp -> add
  4102. | exp "-" exp -> sub
  4103. | "(" exp ")" -> paren
  4104. stmt: "print" "(" exp ")" -> print
  4105. | exp -> expr
  4106. stmt_list: -> empty_stmt
  4107. | stmt NEWLINE stmt_list -> add_stmt
  4108. lang_int: stmt_list -> module
  4109. \end{lstlisting}
  4110. \end{minipage}
  4111. \end{center}
  4112. Here is the resulting parse tree.
  4113. \begin{lstlisting}
  4114. Tree('module',
  4115. [Tree('expr', [Tree('add', [Tree('int', [Token('INT', '1')]),
  4116. Tree('int', [Token('INT', '3')])])]),
  4117. Token('NEWLINE', '\n')])
  4118. \end{lstlisting}
  4119. \section{Ambiguous Grammars}
  4120. A grammar is \emph{ambiguous}\index{subject}{ambiguous} when a string
  4121. can be parsed in more than one way. For example, consider the string
  4122. \lstinline{'1-2+3'}. This string can be parsed in two different ways using
  4123. our draft grammar, resulting in the two parse trees shown in
  4124. figure~\ref{fig:ambig-parse-tree}. This example is problematic because
  4125. interpreting the second parse tree would yield \code{-4} even through
  4126. the correct answer is \code{2}.
  4127. \begin{figure}[tbp]
  4128. \begin{tcolorbox}[colback=white]
  4129. \centering
  4130. \includegraphics[width=0.95\textwidth]{figs/ambig-parse-tree}
  4131. \end{tcolorbox}
  4132. \caption{The two parse trees for \lstinline{'1-2+3'}.}
  4133. \label{fig:ambig-parse-tree}
  4134. \end{figure}
  4135. To deal with this problem we can change the grammar by categorizing
  4136. the syntax in a more fine-grained fashion. In this case we want to
  4137. disallow the application of the rule \code{exp: exp "-" exp} when the
  4138. child on the right is an addition. To do this we can replace the
  4139. \code{exp} after \code{"-"} with a nonterminal that categorizes all
  4140. the expressions except for addition, as in the following.
  4141. \begin{center}
  4142. \begin{minipage}{0.95\textwidth}
  4143. \begin{lstlisting}[escapechar=$]
  4144. exp: exp "-" exp_no_add -> sub
  4145. | exp "+" exp -> add
  4146. | exp_no_add
  4147. exp_no_add: INT -> int
  4148. | "input_int" "(" ")" -> input_int
  4149. | "-" exp -> usub
  4150. | exp "-" exp_no_add -> sub
  4151. | "(" exp ")" -> paren
  4152. \end{lstlisting}
  4153. \end{minipage}
  4154. \end{center}
  4155. However, there remains some ambiguity in the grammar. For example, the
  4156. string \lstinline{'1-2-3'} can still be parsed in two different ways,
  4157. as \lstinline{'(1-2)-3'} (correct) or \lstinline{'1-(2-3)'}
  4158. (incorrect). That is, subtraction is left associative. Likewise,
  4159. addition in Python is left associative. We also need to consider the
  4160. interaction of unary subtraction with both addition and
  4161. subtraction. How should we parse \lstinline{'-1+2'}? Unary subtraction
  4162. has higher \emph{precedence}\index{subject}{precedence} than addition
  4163. and subtraction, so \lstinline{'-1+2'} should parse the same as
  4164. \lstinline{'(-1)+2'} and not \lstinline{'-(1+2)'}. The grammar in
  4165. figure~\ref{fig:Lint-lark-grammar} handles the associativity of
  4166. addition and subtraction by using the nonterminal \code{exp\_hi} for
  4167. all the other expressions, and it uses \code{exp\_hi} for the second
  4168. child in the rules for addition and subtraction. Furthermore, unary
  4169. subtraction uses \code{exp\_hi} for its child.
  4170. For languages with more operators and more precedence levels, one must
  4171. refine the \code{exp} nonterminal into several nonterminals, one for
  4172. each precedence level.
  4173. \begin{figure}[tbp]
  4174. \begin{tcolorbox}[colback=white]
  4175. \centering
  4176. \begin{lstlisting}[escapechar=$]
  4177. exp: exp "+" exp_hi -> add
  4178. | exp "-" exp_hi -> sub
  4179. | exp_hi
  4180. exp_hi: INT -> int
  4181. | "input_int" "(" ")" -> input_int
  4182. | "-" exp_hi -> usub
  4183. | "(" exp ")" -> paren
  4184. stmt: "print" "(" exp ")" -> print
  4185. | exp -> expr
  4186. stmt_list: -> empty_stmt
  4187. | stmt NEWLINE stmt_list -> add_stmt
  4188. lang_int: stmt_list -> module
  4189. \end{lstlisting}
  4190. \end{tcolorbox}
  4191. \caption{An unambiguous Lark grammar for \LangInt{}.}
  4192. \label{fig:Lint-lark-grammar}
  4193. \end{figure}
  4194. \section{From Parse Trees to Abstract Syntax Trees}
  4195. As we have seen, the output of a Lark parser is a parse tree, that is,
  4196. a tree consisting of \code{Tree} and \code{Token} nodes. So, the next
  4197. step is to convert the parse tree to an abstract syntax tree. This can
  4198. be accomplished with a recursive function that inspects the
  4199. \code{data} field of each node and then constructs the corresponding
  4200. AST node, using recursion to handle its children. The following is an
  4201. excerpt from the \code{parse\_tree\_to\_ast} function for \LangInt{}.
  4202. \begin{center}
  4203. \begin{minipage}{0.95\textwidth}
  4204. \begin{lstlisting}
  4205. def parse_tree_to_ast(e):
  4206. if e.data == 'int':
  4207. return Constant(int(e.children[0].value))
  4208. elif e.data == 'input_int':
  4209. return Call(Name('input_int'), [])
  4210. elif e.data == 'add':
  4211. e1, e2 = e.children
  4212. return BinOp(parse_tree_to_ast(e1), Add(), parse_tree_to_ast(e2))
  4213. ...
  4214. else:
  4215. raise Exception('unhandled parse tree', e)
  4216. \end{lstlisting}
  4217. \end{minipage}
  4218. \end{center}
  4219. \begin{exercise}
  4220. \normalfont\normalsize
  4221. %
  4222. Use Lark to create a lexer and parser for \LangVar{}. Use Lark's
  4223. default parsing algorithm (Earley) with the \code{ambiguity} option
  4224. set to \lstinline{'explicit'} so that if your grammar is ambiguous, the
  4225. output will include multiple parse trees that will indicate to you
  4226. that there is a problem with your grammar. Your parser should ignore
  4227. white space, so we recommend using Lark's \code{\%ignore} directive
  4228. as follows.
  4229. \begin{lstlisting}
  4230. WS: /[ \t\f\r\n]/+
  4231. %ignore WS
  4232. \end{lstlisting}
  4233. Change your compiler from chapter~\ref{ch:Lvar} to use your
  4234. Lark parser instead of using the \code{parse} function from
  4235. the \code{ast} module. Test your compiler on all the \LangVar{}
  4236. programs that you have created, and create four additional programs
  4237. that test for ambiguities in your grammar.
  4238. \end{exercise}
  4239. \section{Earley's Algorithm}
  4240. \label{sec:earley}
  4241. In this section we discuss the parsing algorithm of
  4242. \citet{Earley:1970ly}, the default algorithm used by Lark. The
  4243. algorithm is powerful in that it can handle any context-free grammar,
  4244. which makes it easy to use, but it is not a particularly
  4245. efficient parsing algorithm. Earley's algorithm is $O(n^3)$ for
  4246. ambiguous grammars and $O(n^2)$ for unambiguous grammars, where $n$ is
  4247. the number of tokens in the input
  4248. string~\citep{Hopcroft06:_automata}. In section~\ref{sec:lalr} we
  4249. learn about the LALR(1) algorithm, which is more efficient but cannot
  4250. handle all context-free grammars.
  4251. Earley's algorithm can be viewed as an interpreter; it treats the
  4252. grammar as the program being interpreted, and it treats the concrete
  4253. syntax of the program-to-be-parsed as its input. Earley's algorithm
  4254. uses a data structure called a \emph{chart}\index{subject}{chart} to
  4255. keep track of its progress and to store its results. The chart is an
  4256. array with one slot for each position in the input string, where
  4257. position $0$ is before the first character and position $n$ is
  4258. immediately after the last character. So, the array has length $n+1$
  4259. for an input string of length $n$. Each slot in the chart contains a
  4260. set of \emph{dotted rules}. A dotted rule is simply a grammar rule
  4261. with a period indicating how much of its right-hand side has already
  4262. been parsed. For example, the dotted rule
  4263. \begin{lstlisting}
  4264. exp: exp "+" . exp_hi
  4265. \end{lstlisting}
  4266. represents a partial parse that has matched an \code{exp} followed by
  4267. \code{+} but has not yet parsed an \code{exp} to the right of
  4268. \code{+}.
  4269. %
  4270. Earley's algorithm starts with an initialization phase and then
  4271. repeats three actions---prediction, scanning, and completion---for as
  4272. long as opportunities arise. We demonstrate Earley's algorithm on a
  4273. running example, parsing the following program:
  4274. \begin{lstlisting}
  4275. print(1 + 3)
  4276. \end{lstlisting}
  4277. The algorithm's initialization phase creates dotted rules for all the
  4278. grammar rules whose left-hand side is the start symbol and places them
  4279. in slot $0$ of the chart. We also record the starting position of the
  4280. dotted rule in parentheses on the right. For example, given the
  4281. grammar in figure~\ref{fig:Lint-lark-grammar}, we place
  4282. \begin{lstlisting}
  4283. lang_int: . stmt_list (0)
  4284. \end{lstlisting}
  4285. in slot $0$ of the chart. The algorithm then proceeds with
  4286. \emph{prediction} actions in which it adds more dotted rules to the
  4287. chart based on the nonterminals that come immediately after a period. In
  4288. the dotted rule above, the nonterminal \code{stmt\_list} appears after a period,
  4289. so we add all the rules for \code{stmt\_list} to slot $0$, with a
  4290. period at the beginning of their right-hand sides, as follows:
  4291. \begin{lstlisting}
  4292. stmt_list: . (0)
  4293. stmt_list: . stmt NEWLINE stmt_list (0)
  4294. \end{lstlisting}
  4295. We continue to perform prediction actions as more opportunities
  4296. arise. For example, the \code{stmt} nonterminal now appears after a
  4297. period, so we add all the rules for \code{stmt}.
  4298. \begin{lstlisting}
  4299. stmt: . "print" "(" exp ")" (0)
  4300. stmt: . exp (0)
  4301. \end{lstlisting}
  4302. This reveals yet more opportunities for prediction, so we add the grammar
  4303. rules for \code{exp} and \code{exp\_hi} to slot $0$.
  4304. \begin{lstlisting}[escapechar=$]
  4305. exp: . exp "+" exp_hi (0)
  4306. exp: . exp "-" exp_hi (0)
  4307. exp: . exp_hi (0)
  4308. exp_hi: . INT (0)
  4309. exp_hi: . "input_int" "(" ")" (0)
  4310. exp_hi: . "-" exp_hi (0)
  4311. exp_hi: . "(" exp ")" (0)
  4312. \end{lstlisting}
  4313. We have exhausted the opportunities for prediction, so the algorithm
  4314. proceeds to \emph{scanning}, in which we inspect the next input token
  4315. and look for a dotted rule at the current position that has a matching
  4316. terminal immediately following the period. In our running example, the
  4317. first input token is \code{"print"}, so we identify the rule in slot
  4318. $0$ of the chart where \code{"print"} follows the period:
  4319. \begin{lstlisting}
  4320. stmt: . "print" "(" exp ")" (0)
  4321. \end{lstlisting}
  4322. We advance the period past \code{"print"} and add the resulting rule
  4323. to slot $1$:
  4324. \begin{lstlisting}
  4325. stmt: "print" . "(" exp ")" (0)
  4326. \end{lstlisting}
  4327. If the new dotted rule had a nonterminal after the period, we would
  4328. need to carry out a prediction action, adding more dotted rules to
  4329. slot $1$. That is not the case, so we continue scanning. The next
  4330. input token is \code{"("}, so we add the following to slot $2$ of the
  4331. chart.
  4332. \begin{lstlisting}
  4333. stmt: "print" "(" . exp ")" (0)
  4334. \end{lstlisting}
  4335. Now we have a nonterminal after the period, so we carry out several
  4336. prediction actions, adding dotted rules for \code{exp} and
  4337. \code{exp\_hi} to slot $2$ with a period at the beginning and with
  4338. starting position $2$.
  4339. \begin{lstlisting}[escapechar=$]
  4340. exp: . exp "+" exp_hi (2)
  4341. exp: . exp "-" exp_hi (2)
  4342. exp: . exp_hi (2)
  4343. exp_hi: . INT (2)
  4344. exp_hi: . "input_int" "(" ")" (2)
  4345. exp_hi: . "-" exp_hi (2)
  4346. exp_hi: . "(" exp ")" (2)
  4347. \end{lstlisting}
  4348. With this prediction complete, we return to scanning, noting that the
  4349. next input token is \code{"1"}, which the lexer parses as an
  4350. \code{INT}. There is a matching rule in slot $2$:
  4351. \begin{lstlisting}
  4352. exp_hi: . INT (2)
  4353. \end{lstlisting}
  4354. so we advance the period and put the following rule into slot $3$.
  4355. \begin{lstlisting}
  4356. exp_hi: INT . (2)
  4357. \end{lstlisting}
  4358. This brings us to \emph{completion} actions. When the period reaches
  4359. the end of a dotted rule, we recognize that the substring
  4360. has matched the nonterminal on the left-hand side of the rule, in this case
  4361. \code{exp\_hi}. We therefore need to advance the periods in any dotted
  4362. rules into slot $2$ (the starting position for the finished rule) if
  4363. the period is immediately followed by \code{exp\_hi}. So we identify
  4364. \begin{lstlisting}
  4365. exp: . exp_hi (2)
  4366. \end{lstlisting}
  4367. and add the following dotted rule to slot $3$
  4368. \begin{lstlisting}
  4369. exp: exp_hi . (2)
  4370. \end{lstlisting}
  4371. This triggers another completion step for the nonterminal \code{exp},
  4372. adding two more dotted rules to slot $3$.
  4373. \begin{lstlisting}[escapechar=$]
  4374. exp: exp . "+" exp_hi (2)
  4375. exp: exp . "-" exp_hi (2)
  4376. \end{lstlisting}
  4377. Returning to scanning, the next input token is \code{"+"}, so
  4378. we add the following to slot $4$.
  4379. \begin{lstlisting}[escapechar=$]
  4380. exp: exp "+" . exp_hi (2)
  4381. \end{lstlisting}
  4382. The period precedes the nonterminal \code{exp\_hi}, so prediction adds
  4383. the following dotted rules to slot $4$ of the chart.
  4384. \begin{lstlisting}[escapechar=$]
  4385. exp_hi: . INT (4)
  4386. exp_hi: . "input_int" "(" ")" (4)
  4387. exp_hi: . "-" exp_hi (4)
  4388. exp_hi: . "(" exp ")" (4)
  4389. \end{lstlisting}
  4390. The next input token is \code{"3"} which the lexer categorized as an
  4391. \code{INT}, so we advance the period past \code{INT} for the rules in
  4392. slot $4$, of which there is just one, and put the following into slot $5$.
  4393. \begin{lstlisting}[escapechar=$]
  4394. exp_hi: INT . (4)
  4395. \end{lstlisting}
  4396. The period at the end of the rule triggers a completion action for the
  4397. rules in slot $4$, one of which has a period before \code{exp\_hi}.
  4398. So we advance the period and put the following into slot $5$.
  4399. \begin{lstlisting}[escapechar=$]
  4400. exp: exp "+" exp_hi . (2)
  4401. \end{lstlisting}
  4402. This triggers another completion action for the rules in slot $2$ that
  4403. have a period before \code{exp}.
  4404. \begin{lstlisting}[escapechar=$]
  4405. stmt: "print" "(" exp . ")" (0)
  4406. exp: exp . "+" exp_hi (2)
  4407. exp: exp . "-" exp_hi (2)
  4408. \end{lstlisting}
  4409. We scan the next input token \code{")"}, placing the following dotted
  4410. rule into slot $6$.
  4411. \begin{lstlisting}[escapechar=$]
  4412. stmt: "print" "(" exp ")" . (0)
  4413. \end{lstlisting}
  4414. This triggers the completion of \code{stmt} in slot $0$
  4415. \begin{lstlisting}
  4416. stmt_list: stmt . NEWLINE stmt_list (0)
  4417. \end{lstlisting}
  4418. The last input token is a \code{NEWLINE}, so we advance the period
  4419. and place the new dotted rule into slot $7$.
  4420. \begin{lstlisting}
  4421. stmt_list: stmt NEWLINE . stmt_list (0)
  4422. \end{lstlisting}
  4423. We are close to the end of parsing the input!
  4424. The period is before the \code{stmt\_list} nonterminal, so we
  4425. apply prediction for \code{stmt\_list} and then \code{stmt}.
  4426. \begin{lstlisting}
  4427. stmt_list: . (7)
  4428. stmt_list: . stmt NEWLINE stmt_list (7)
  4429. stmt: . "print" "(" exp ")" (7)
  4430. stmt: . exp (7)
  4431. \end{lstlisting}
  4432. There is immediately an opportunity for completion of \code{stmt\_list},
  4433. so we add the following to slot $7$.
  4434. \begin{lstlisting}
  4435. stmt_list: stmt NEWLINE stmt_list . (0)
  4436. \end{lstlisting}
  4437. This triggers another completion action for \code{stmt\_list} in slot $0$
  4438. \begin{lstlisting}
  4439. lang_int: stmt_list . (0)
  4440. \end{lstlisting}
  4441. which in turn completes \code{lang\_int}, the start symbol of the
  4442. grammar, so the parsing of the input is complete.
  4443. For reference, we give a general description of Earley's
  4444. algorithm.
  4445. \begin{enumerate}
  4446. \item The algorithm begins by initializing slot $0$ of the chart with the
  4447. grammar rule for the start symbol, placing a period at the beginning
  4448. of the right-hand side, and recording its starting position as $0$.
  4449. \item The algorithm repeatedly applies the following three kinds of
  4450. actions for as long as there are opportunities to do so.
  4451. \begin{itemize}
  4452. \item Prediction: If there is a rule in slot $k$ whose period comes
  4453. before a nonterminal, add the rules for that nonterminal into slot
  4454. $k$, placing a period at the beginning of their right-hand sides
  4455. and recording their starting position as $k$.
  4456. \item Scanning: If the token at position $k$ of the input string
  4457. matches the symbol after the period in a dotted rule in slot $k$
  4458. of the chart, advance the period in the dotted rule, adding
  4459. the result to slot $k+1$.
  4460. \item Completion: If a dotted rule in slot $k$ has a period at the
  4461. end, inspect the rules in the slot corresponding to the starting
  4462. position of the completed rule. If any of those rules have a
  4463. nonterminal following their period that matches the left-hand side
  4464. of the completed rule, then advance their period, placing the new
  4465. dotted rule in slot $k$.
  4466. \end{itemize}
  4467. While repeating these three actions, take care never to add
  4468. duplicate dotted rules to the chart.
  4469. \end{enumerate}
  4470. We have described how Earley's algorithm recognizes that an input
  4471. string matches a grammar, but we have not described how it builds a
  4472. parse tree. The basic idea is simple, but building parse trees in an
  4473. efficient way is more complex, requiring a data structure called a
  4474. shared packed parse forest~\citep{Tomita:1985qr}. The simple idea is
  4475. to attach a partial parse tree to every dotted rule in the chart.
  4476. Initially, the node associated with a dotted rule has no
  4477. children. As the period moves to the right, the nodes from the
  4478. subparses are added as children to the node.
  4479. As mentioned at the beginning of this section, Earley's algorithm is
  4480. $O(n^2)$ for unambiguous grammars, which means that it can parse input
  4481. files that contain thousands of tokens in a reasonable amount of time,
  4482. but not millions.
  4483. %
  4484. In the next section we discuss the LALR(1) parsing algorithm, which is
  4485. efficient enough to use with even the largest of input files.
  4486. \section{The LALR(1) Algorithm}
  4487. \label{sec:lalr}
  4488. The LALR(1) algorithm~\citep{DeRemer69,Anderson73} can be viewed as a
  4489. two-phase approach in which it first compiles the grammar into a state
  4490. machine and then runs the state machine to parse an input string. The
  4491. second phase has time complexity $O(n)$ where $n$ is the number of
  4492. tokens in the input, so LALR(1) is the best one could hope for with
  4493. respect to efficiency.
  4494. %
  4495. A particularly influential implementation of LALR(1) is the
  4496. \texttt{yacc} parser generator by \citet{Johnson:1979qy};
  4497. \texttt{yacc} stands for ``yet another compiler compiler.''
  4498. %
  4499. The LALR(1) state machine uses a stack to record its progress in
  4500. parsing the input string. Each element of the stack is a pair: a
  4501. state number and a grammar symbol (a terminal or a nonterminal). The
  4502. symbol characterizes the input that has been parsed so far, and the
  4503. state number is used to remember how to proceed once the next
  4504. symbol's worth of input has been parsed. Each state in the machine
  4505. represents where the parser stands in the parsing process with respect
  4506. to certain grammar rules. In particular, each state is associated with
  4507. a set of dotted rules.
  4508. Figure~\ref{fig:shift-reduce} shows an example LALR(1) state machine
  4509. (also called parse table) for the following simple but ambiguous
  4510. grammar:
  4511. \begin{lstlisting}[escapechar=$]
  4512. exp: INT
  4513. | exp "+" exp
  4514. stmt: "print" exp
  4515. start: stmt
  4516. \end{lstlisting}
  4517. Consider state 1 in figure~\ref{fig:shift-reduce}. The parser has just
  4518. read in a \lstinline{"print"} token, so the top of the stack is
  4519. \lstinline{(1,"print")}. The parser is part of the way through parsing
  4520. the input according to grammar rule 1, which is signified by showing
  4521. rule 1 with a period after the \code{"print"} token and before the
  4522. \code{exp} nonterminal. There are two rules that could apply next,
  4523. rules 2 and 3, so state 1 also shows those rules with a period at
  4524. the beginning of their right-hand sides. The edges between states
  4525. indicate which transitions the machine should make depending on the
  4526. next input token. So, for example, if the next input token is
  4527. \code{INT} then the parser will push \code{INT} and the target state 4
  4528. on the stack and transition to state 4. Suppose that we are now at the end
  4529. of the input. State 4 says that we should reduce by rule 3, so we pop
  4530. from the stack the same number of items as the number of symbols in
  4531. the right-hand side of the rule, in this case just one. We then
  4532. momentarily jump to the state at the top of the stack (state 1) and
  4533. then follow the goto edge that corresponds to the left-hand side of
  4534. the rule we just reduced by, in this case \code{exp}, so we arrive at
  4535. state 3. (A slightly longer example parse is shown in
  4536. figure~\ref{fig:shift-reduce}.)
  4537. \begin{figure}[tbp]
  4538. \centering
  4539. \includegraphics[width=5.0in]{figs/shift-reduce-conflict}
  4540. \caption{An LALR(1) parse table and a trace of an example run.}
  4541. \label{fig:shift-reduce}
  4542. \end{figure}
  4543. In general, the algorithm works as follows. First, set the current state to
  4544. state $0$. Then repeat the following, looking at the next input token.
  4545. \begin{itemize}
  4546. \item If there there is a shift edge for the input token in the
  4547. current state, push the edge's target state and the input token onto
  4548. the stack and proceed to the edge's target state.
  4549. \item If there is a reduce action for the input token in the current
  4550. state, pop $k$ elements from the stack, where $k$ is the number of
  4551. symbols in the right-hand side of the rule being reduced. Jump to
  4552. the state at the top of the stack and then follow the goto edge for
  4553. the nonterminal that matches the left-hand side of the rule that we
  4554. are reducing by. Push the edge's target state and the nonterminal on the
  4555. stack.
  4556. \end{itemize}
  4557. Notice that in state 6 of figure~\ref{fig:shift-reduce} there is both
  4558. a shift and a reduce action for the token \lstinline{PLUS}, so the
  4559. algorithm does not know which action to take in this case. When a
  4560. state has both a shift and a reduce action for the same token, we say
  4561. there is a \emph{shift/reduce conflict}. In this case, the conflict
  4562. will arise, for example, in trying to parse the input
  4563. \lstinline{print 1 + 2 + 3}. After having consumed \lstinline{print 1 + 2},
  4564. the parser will be in state 6 and will not know whether to
  4565. reduce to form an \code{exp} of \lstinline{1 + 2} or
  4566. to proceed by shifting the next \lstinline{+} from the input.
  4567. A similar kind of problem, known as a \emph{reduce/reduce} conflict,
  4568. arises when there are two reduce actions in a state for the same
  4569. token. To understand which grammars give rise to shift/reduce and
  4570. reduce/reduce conflicts, it helps to know how the parse table is
  4571. generated from the grammar, which we discuss next.
  4572. The parse table is generated one state at a time. State 0 represents
  4573. the start of the parser. We add the grammar rule for the start symbol
  4574. to this state with a period at the beginning of the right-hand side,
  4575. similarly to the initialization phase of the Earley parser. If the
  4576. period appears immediately before another nonterminal, we add all the
  4577. rules with that nonterminal on the left-hand side. Again, we place a
  4578. period at the beginning of the right-hand side of each new
  4579. rule. This process, called \emph{state closure}, is continued
  4580. until there are no more rules to add (similarly to the prediction
  4581. actions of an Earley parser). We then examine each dotted rule in the
  4582. current state $I$. Suppose that a dotted rule has the form $A ::=
  4583. s_1.\,X \,s_2$, where $A$ and $X$ are symbols and $s_1$ and $s_2$
  4584. are sequences of symbols. We create a new state and call it $J$. If $X$
  4585. is a terminal, we create a shift edge from $I$ to $J$ (analogously to
  4586. scanning in Earley), whereas if $X$ is a nonterminal, we create a
  4587. goto edge from $I$ to $J$. We then need to add some dotted rules to
  4588. state $J$. We start by adding all dotted rules from state $I$ that
  4589. have the form $B ::= s_1.\,X\,s_2$ (where $B$ is any nonterminal and
  4590. $s_1$ and $s_2$ are arbitrary sequences of symbols), with
  4591. the period moved past the $X$. (This is analogous to completion in
  4592. Earley's algorithm.) We then perform state closure on $J$. This
  4593. process repeats until there are no more states or edges to add.
  4594. We then mark states as accepting states if they have a dotted rule
  4595. that is the start rule with a period at the end. Also, to add
  4596. the reduce actions, we look for any state containing a dotted rule
  4597. with a period at the end. Let $n$ be the rule number for this dotted
  4598. rule. We then put a reduce $n$ action into that state for every token
  4599. $Y$. For example, in figure~\ref{fig:shift-reduce} state 4 has a
  4600. dotted rule with a period at the end. We therefore put a reduce by
  4601. rule 3 action into state 4 for every
  4602. token.
  4603. When inserting reduce actions, take care to spot any shift/reduce or
  4604. reduce/reduce conflicts. If there are any, abort the construction of
  4605. the parse table.
  4606. \begin{exercise}
  4607. \normalfont\normalsize
  4608. %
  4609. Working on paper, walk through the parse table generation process for
  4610. the grammar at the top of figure~\ref{fig:shift-reduce}, and check
  4611. your results against the parse table shown in
  4612. figure~\ref{fig:shift-reduce}.
  4613. \end{exercise}
  4614. \begin{exercise}
  4615. \normalfont\normalsize
  4616. %
  4617. Change the parser in your compiler for \LangVar{} to set the
  4618. \code{parser} option of Lark to \lstinline{'lalr'}. Test your compiler on
  4619. all the \LangVar{} programs that you have created. In doing so, Lark
  4620. may signal an error due to shift/reduce or reduce/reduce conflicts
  4621. in your grammar. If so, change your Lark grammar for \LangVar{} to
  4622. remove those conflicts.
  4623. \end{exercise}
  4624. \section{Further Reading}
  4625. In this chapter we have just scratched the surface of the field of
  4626. parsing, with the study of a very general but less efficient algorithm
  4627. (Earley) and with a more limited but highly efficient algorithm
  4628. (LALR). There are many more algorithms and classes of grammars that
  4629. fall between these two ends of the spectrum. We recommend to the reader
  4630. \citet{Aho:2006wb} for a thorough treatment of parsing.
  4631. Regarding lexical analysis, we have described the specification
  4632. language, which are the regular expressions, but not the algorithms
  4633. for recognizing them. In short, regular expressions can be translated
  4634. to nondeterministic finite automata, which in turn are translated to
  4635. finite automata. We refer the reader again to \citet{Aho:2006wb} for
  4636. all the details on lexical analysis.
  4637. \fi}
  4638. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4639. \chapter{Register Allocation}
  4640. \label{ch:register-allocation-Lvar}
  4641. \setcounter{footnote}{0}
  4642. \index{subject}{register allocation}
  4643. In chapter~\ref{ch:Lvar} we learned how to compile \LangVar{} to x86,
  4644. storing variables on the procedure call stack. The CPU may require tens
  4645. to hundreds of cycles to access a location on the stack, whereas
  4646. accessing a register takes only a single cycle. In this chapter we
  4647. improve the efficiency of our generated code by storing some variables
  4648. in registers. The goal of register allocation is to fit as many
  4649. variables into registers as possible. Some programs have more
  4650. variables than registers, so we cannot always map each variable to a
  4651. different register. Fortunately, it is common for different variables
  4652. to be in use during different periods of time during program
  4653. execution, and in those cases we can map multiple variables to the
  4654. same register.
  4655. The program shown in figure~\ref{fig:reg-eg} serves as a running
  4656. example. The source program is on the left and the output of
  4657. instruction selection\index{subject}{instruction selection}
  4658. is on the right. The program is almost
  4659. completely in the x86 assembly language, but it still uses variables.
  4660. Consider variables \code{x} and \code{z}. After the variable \code{x}
  4661. has been moved to \code{z}, it is no longer in use. Variable \code{z}, on
  4662. the other hand, is used only after this point, so \code{x} and
  4663. \code{z} could share the same register.
  4664. \begin{figure}
  4665. \begin{tcolorbox}[colback=white]
  4666. \begin{minipage}{0.45\textwidth}
  4667. Example \LangVar{} program:
  4668. % var_test_28.rkt
  4669. {\if\edition\racketEd
  4670. \begin{lstlisting}
  4671. (let ([v 1])
  4672. (let ([w 42])
  4673. (let ([x (+ v 7)])
  4674. (let ([y x])
  4675. (let ([z (+ x w)])
  4676. (+ z (- y)))))))
  4677. \end{lstlisting}
  4678. \fi}
  4679. {\if\edition\pythonEd\pythonColor
  4680. \begin{lstlisting}
  4681. v = 1
  4682. w = 42
  4683. x = v + 7
  4684. y = x
  4685. z = x + w
  4686. print(z + (- y))
  4687. \end{lstlisting}
  4688. \fi}
  4689. \end{minipage}
  4690. \begin{minipage}{0.45\textwidth}
  4691. After instruction selection:
  4692. {\if\edition\racketEd
  4693. \begin{lstlisting}
  4694. locals-types:
  4695. x : Integer, y : Integer,
  4696. z : Integer, t : Integer,
  4697. v : Integer, w : Integer
  4698. start:
  4699. movq $1, v
  4700. movq $42, w
  4701. movq v, x
  4702. addq $7, x
  4703. movq x, y
  4704. movq x, z
  4705. addq w, z
  4706. movq y, t
  4707. negq t
  4708. movq z, %rax
  4709. addq t, %rax
  4710. jmp conclusion
  4711. \end{lstlisting}
  4712. \fi}
  4713. {\if\edition\pythonEd\pythonColor
  4714. \begin{lstlisting}
  4715. movq $1, v
  4716. movq $42, w
  4717. movq v, x
  4718. addq $7, x
  4719. movq x, y
  4720. movq x, z
  4721. addq w, z
  4722. movq y, tmp_0
  4723. negq tmp_0
  4724. movq z, tmp_1
  4725. addq tmp_0, tmp_1
  4726. movq tmp_1, %rdi
  4727. callq print_int
  4728. \end{lstlisting}
  4729. \fi}
  4730. \end{minipage}
  4731. \end{tcolorbox}
  4732. \caption{A running example for register allocation.}
  4733. \label{fig:reg-eg}
  4734. \end{figure}
  4735. The topic of section~\ref{sec:liveness-analysis-Lvar} is how to
  4736. compute where a variable is in use. Once we have that information, we
  4737. compute which variables are in use at the same time, that is, which ones
  4738. \emph{interfere}\index{subject}{interfere} with each other, and
  4739. represent this relation as an undirected graph whose vertices are
  4740. variables and edges indicate when two variables interfere
  4741. (section~\ref{sec:build-interference}). We then model register
  4742. allocation as a graph coloring problem
  4743. (section~\ref{sec:graph-coloring}).
  4744. If we run out of registers despite these efforts, we place the
  4745. remaining variables on the stack, similarly to how we handled
  4746. variables in chapter~\ref{ch:Lvar}. It is common to use the verb
  4747. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  4748. location. The decision to spill a variable is handled as part of the
  4749. graph coloring process.
  4750. We make the simplifying assumption that each variable is assigned to
  4751. one location (a register or stack address). A more sophisticated
  4752. approach is to assign a variable to one or more locations in different
  4753. regions of the program. For example, if a variable is used many times
  4754. in short sequence and then used again only after many other
  4755. instructions, it could be more efficient to assign the variable to a
  4756. register during the initial sequence and then move it to the stack for
  4757. the rest of its lifetime. We refer the interested reader to
  4758. \citet{Cooper:2011aa} (chapter 13) for more information about that
  4759. approach.
  4760. % discuss prioritizing variables based on how much they are used.
  4761. \section{Registers and Calling Conventions}
  4762. \label{sec:calling-conventions}
  4763. \index{subject}{calling conventions}
  4764. As we perform register allocation, we must be aware of the
  4765. \emph{calling conventions} \index{subject}{calling conventions} that
  4766. govern how function calls are performed in x86.
  4767. %
  4768. Even though \LangVar{} does not include programmer-defined functions,
  4769. our generated code includes a \code{main} function that is called by
  4770. the operating system and our generated code contains calls to the
  4771. \code{read\_int} function.
  4772. Function calls require coordination between two pieces of code that
  4773. may be written by different programmers or generated by different
  4774. compilers. Here we follow the System V calling conventions that are
  4775. used by the GNU C compiler on Linux and
  4776. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  4777. %
  4778. The calling conventions include rules about how functions share the
  4779. use of registers. In particular, the caller is responsible for freeing
  4780. some registers prior to the function call for use by the callee.
  4781. These are called the \emph{caller-saved registers}
  4782. \index{subject}{caller-saved registers}
  4783. and they are
  4784. \begin{lstlisting}
  4785. rax rcx rdx rsi rdi r8 r9 r10 r11
  4786. \end{lstlisting}
  4787. On the other hand, the callee is responsible for preserving the values
  4788. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  4789. which are
  4790. \begin{lstlisting}
  4791. rsp rbp rbx r12 r13 r14 r15
  4792. \end{lstlisting}
  4793. We can think about this caller/callee convention from two points of
  4794. view, the caller view and the callee view, as follows:
  4795. \begin{itemize}
  4796. \item The caller should assume that all the caller-saved registers get
  4797. overwritten with arbitrary values by the callee. On the other hand,
  4798. the caller can safely assume that all the callee-saved registers
  4799. retain their original values.
  4800. \item The callee can freely use any of the caller-saved registers.
  4801. However, if the callee wants to use a callee-saved register, the
  4802. callee must arrange to put the original value back in the register
  4803. prior to returning to the caller. This can be accomplished by saving
  4804. the value to the stack in the prelude of the function and restoring
  4805. the value in the conclusion of the function.
  4806. \end{itemize}
  4807. In x86, registers are also used for passing arguments to a function
  4808. and for the return value. In particular, the first six arguments of a
  4809. function are passed in the following six registers, in this order.
  4810. \begin{lstlisting}
  4811. rdi rsi rdx rcx r8 r9
  4812. \end{lstlisting}
  4813. We refer to these six registers are the argument-passing registers
  4814. \index{subject}{argument-passing registers}.
  4815. If there are more than six arguments, the convention is to use space
  4816. on the frame of the caller for the rest of the arguments. In
  4817. chapter~\ref{ch:Lfun}, we instead pass a tuple containing the sixth
  4818. argument and the rest of the arguments, which simplifies the treatment
  4819. of efficient tail calls.
  4820. %
  4821. \racket{For now, the only function we care about is \code{read\_int},
  4822. which takes zero arguments.}
  4823. %
  4824. \python{For now, the only functions we care about are \code{read\_int}
  4825. and \code{print\_int}, which take zero and one argument, respectively.}
  4826. %
  4827. The register \code{rax} is used for the return value of a function.
  4828. The next question is how these calling conventions impact register
  4829. allocation. Consider the \LangVar{} program presented in
  4830. figure~\ref{fig:example-calling-conventions}. We first analyze this
  4831. example from the caller point of view and then from the callee point
  4832. of view. We refer to a variable that is in use during a function call
  4833. as a \emph{call-live variable}\index{subject}{call-live variable}.
  4834. The program makes two calls to \READOP{}. The variable \code{x} is
  4835. call-live because it is in use during the second call to \READOP{}; we
  4836. must ensure that the value in \code{x} does not get overwritten during
  4837. the call to \READOP{}. One obvious approach is to save all the values
  4838. that reside in caller-saved registers to the stack prior to each
  4839. function call and to restore them after each call. That way, if the
  4840. register allocator chooses to assign \code{x} to a caller-saved
  4841. register, its value will be preserved across the call to \READOP{}.
  4842. However, saving and restoring to the stack is relatively slow. If
  4843. \code{x} is not used many times, it may be better to assign \code{x}
  4844. to a stack location in the first place. Or better yet, if we can
  4845. arrange for \code{x} to be placed in a callee-saved register, then it
  4846. won't need to be saved and restored during function calls.
  4847. We recommend an approach that captures these issues in the
  4848. interference graph, without complicating the graph coloring algorithm.
  4849. During liveness analysis we know which variables are call-live because
  4850. we compute which variables are in use at every instruction
  4851. (section~\ref{sec:liveness-analysis-Lvar}). When we build the
  4852. interference graph (section~\ref{sec:build-interference}), we can
  4853. place an edge in the interference graph between each call-live
  4854. variable and the caller-saved registers. This will prevent the graph
  4855. coloring algorithm from assigning call-live variables to caller-saved
  4856. registers.
  4857. On the other hand, for variables that are not call-live, we prefer
  4858. placing them in caller-saved registers to leave more room for
  4859. call-live variables in the callee-saved registers. This can also be
  4860. implemented without complicating the graph coloring algorithm. We
  4861. recommend that the graph coloring algorithm assign variables to
  4862. natural numbers, choosing the lowest number for which there is no
  4863. interference. After the coloring is complete, we map the numbers to
  4864. registers and stack locations: mapping the lowest numbers to
  4865. caller-saved registers, the next lowest to callee-saved registers, and
  4866. the largest numbers to stack locations. This ordering gives preference
  4867. to registers over stack locations and to caller-saved registers over
  4868. callee-saved registers.
  4869. Returning to the example in
  4870. figure~\ref{fig:example-calling-conventions}, let us analyze the
  4871. generated x86 code on the right-hand side. Variable \code{x} is
  4872. assigned to \code{rbx}, a callee-saved register. Thus, it is already
  4873. in a safe place during the second call to \code{read\_int}. Next,
  4874. variable \code{y} is assigned to \code{rcx}, a caller-saved register,
  4875. because \code{y} is not a call-live variable.
  4876. We have completed the analysis from the caller point of view, so now
  4877. we switch to the callee point of view, focusing on the prelude and
  4878. conclusion of the \code{main} function. As usual, the prelude begins
  4879. with saving the \code{rbp} register to the stack and setting the
  4880. \code{rbp} to the current stack pointer. We now know why it is
  4881. necessary to save the \code{rbp}: it is a callee-saved register. The
  4882. prelude then pushes \code{rbx} to the stack because (1) \code{rbx} is
  4883. a callee-saved register and (2) \code{rbx} is assigned to a variable
  4884. (\code{x}). The other callee-saved registers are not saved in the
  4885. prelude because they are not used. The prelude subtracts 8 bytes from
  4886. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  4887. conclusion, we see that \code{rbx} is restored from the stack with a
  4888. \code{popq} instruction.
  4889. \index{subject}{prelude}\index{subject}{conclusion}
  4890. \begin{figure}[tp]
  4891. \begin{tcolorbox}[colback=white]
  4892. \begin{minipage}{0.45\textwidth}
  4893. Example \LangVar{} program:
  4894. %var_test_14.rkt
  4895. {\if\edition\racketEd
  4896. \begin{lstlisting}
  4897. (let ([x (read)])
  4898. (let ([y (read)])
  4899. (+ (+ x y) 42)))
  4900. \end{lstlisting}
  4901. \fi}
  4902. {\if\edition\pythonEd\pythonColor
  4903. \begin{lstlisting}
  4904. x = input_int()
  4905. y = input_int()
  4906. print((x + y) + 42)
  4907. \end{lstlisting}
  4908. \fi}
  4909. \end{minipage}
  4910. \begin{minipage}{0.45\textwidth}
  4911. Generated x86 assembly:
  4912. {\if\edition\racketEd
  4913. \begin{lstlisting}
  4914. start:
  4915. callq read_int
  4916. movq %rax, %rbx
  4917. callq read_int
  4918. movq %rax, %rcx
  4919. addq %rcx, %rbx
  4920. movq %rbx, %rax
  4921. addq $42, %rax
  4922. jmp _conclusion
  4923. .globl main
  4924. main:
  4925. pushq %rbp
  4926. movq %rsp, %rbp
  4927. pushq %rbx
  4928. subq $8, %rsp
  4929. jmp start
  4930. conclusion:
  4931. addq $8, %rsp
  4932. popq %rbx
  4933. popq %rbp
  4934. retq
  4935. \end{lstlisting}
  4936. \fi}
  4937. {\if\edition\pythonEd\pythonColor
  4938. \begin{lstlisting}
  4939. .globl main
  4940. main:
  4941. pushq %rbp
  4942. movq %rsp, %rbp
  4943. pushq %rbx
  4944. subq $8, %rsp
  4945. callq read_int
  4946. movq %rax, %rbx
  4947. callq read_int
  4948. movq %rax, %rcx
  4949. movq %rbx, %rdx
  4950. addq %rcx, %rdx
  4951. movq %rdx, %rcx
  4952. addq $42, %rcx
  4953. movq %rcx, %rdi
  4954. callq print_int
  4955. addq $8, %rsp
  4956. popq %rbx
  4957. popq %rbp
  4958. retq
  4959. \end{lstlisting}
  4960. \fi}
  4961. \end{minipage}
  4962. \end{tcolorbox}
  4963. \caption{An example with function calls.}
  4964. \label{fig:example-calling-conventions}
  4965. \end{figure}
  4966. %\clearpage
  4967. \section{Liveness Analysis}
  4968. \label{sec:liveness-analysis-Lvar}
  4969. \index{subject}{liveness analysis}
  4970. The \code{uncover\_live} \racket{pass}\python{function} performs
  4971. \emph{liveness analysis}; that is, it discovers which variables are
  4972. in use in different regions of a program.
  4973. %
  4974. A variable or register is \emph{live} at a program point if its
  4975. current value is used at some later point in the program. We refer to
  4976. variables, stack locations, and registers collectively as
  4977. \emph{locations}.
  4978. %
  4979. Consider the following code fragment in which there are two writes to
  4980. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4981. time?
  4982. \begin{center}
  4983. \begin{minipage}{0.85\textwidth}
  4984. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4985. movq $5, a
  4986. movq $30, b
  4987. movq a, c
  4988. movq $10, b
  4989. addq b, c
  4990. \end{lstlisting}
  4991. \end{minipage}
  4992. \end{center}
  4993. The answer is no, because \code{a} is live from line 1 to 3 and
  4994. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4995. line 2 is never used because it is overwritten (line 4) before the
  4996. next read (line 5).
  4997. The live locations for each instruction can be computed by traversing
  4998. the instruction sequence back to front (i.e., backward in execution
  4999. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  5000. $L_{\mathsf{after}}(k)$ for the set of live locations after
  5001. instruction $I_k$ and write $L_{\mathsf{before}}(k)$ for the set of live
  5002. locations before instruction $I_k$. \racket{We recommend representing
  5003. these sets with the Racket \code{set} data structure described in
  5004. figure~\ref{fig:set}.} \python{We recommend representing these sets
  5005. with the Python
  5006. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  5007. data structure.}
  5008. {\if\edition\racketEd
  5009. \begin{figure}[tp]
  5010. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  5011. \small
  5012. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  5013. A \emph{set} is an unordered collection of elements without duplicates.
  5014. Here are some of the operations defined on sets.
  5015. \index{subject}{set}
  5016. \begin{description}
  5017. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  5018. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  5019. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  5020. difference of the two sets.
  5021. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  5022. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  5023. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  5024. \end{description}
  5025. \end{tcolorbox}
  5026. %\end{wrapfigure}
  5027. \caption{The \code{set} data structure.}
  5028. \label{fig:set}
  5029. \end{figure}
  5030. \fi}
  5031. % TODO: add a python version of the reference box for sets. -Jeremy
  5032. The locations that are live after an instruction are its
  5033. \emph{live-after}\index{subject}{live-after} set, and the locations
  5034. that are live before an instruction are its
  5035. \emph{live-before}\index{subject}{live-before} set. The live-after
  5036. set of an instruction is always the same as the live-before set of the
  5037. next instruction.
  5038. \begin{equation} \label{eq:live-after-before-next}
  5039. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  5040. \end{equation}
  5041. To start things off, there are no live locations after the last
  5042. instruction, so
  5043. \begin{equation}\label{eq:live-last-empty}
  5044. L_{\mathsf{after}}(n) = \emptyset
  5045. \end{equation}
  5046. We then apply the following rule repeatedly, traversing the
  5047. instruction sequence back to front.
  5048. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  5049. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  5050. \end{equation}
  5051. where $W(k)$ are the locations written to by instruction $I_k$, and
  5052. $R(k)$ are the locations read by instruction $I_k$.
  5053. {\if\edition\racketEd
  5054. %
  5055. There is a special case for \code{jmp} instructions. The locations
  5056. that are live before a \code{jmp} should be the locations in
  5057. $L_{\mathsf{before}}$ at the target of the jump. So, we recommend
  5058. maintaining an alist named \code{label->live} that maps each label to
  5059. the $L_{\mathsf{before}}$ for the first instruction in its block. For
  5060. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  5061. conclusion. (For example, see figure~\ref{fig:reg-eg}.) The
  5062. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  5063. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  5064. %
  5065. \fi}
  5066. Let us walk through the previous example, applying these formulas
  5067. starting with the instruction on line 5 of the code fragment. We
  5068. collect the answers in figure~\ref{fig:liveness-example-0}. The
  5069. $L_{\mathsf{after}}$ for the \code{addq b, c} instruction is
  5070. $\emptyset$ because it is the last instruction
  5071. (formula~\eqref{eq:live-last-empty}). The $L_{\mathsf{before}}$ for
  5072. this instruction is $\{\ttm{b},\ttm{c}\}$ because it reads from
  5073. variables \code{b} and \code{c}
  5074. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}):
  5075. \[
  5076. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  5077. \]
  5078. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  5079. the live-before set from line 5 to be the live-after set for this
  5080. instruction (formula~\eqref{eq:live-after-before-next}).
  5081. \[
  5082. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  5083. \]
  5084. This move instruction writes to \code{b} and does not read from any
  5085. variables, so we have the following live-before set
  5086. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}).
  5087. \[
  5088. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  5089. \]
  5090. The live-before for instruction \code{movq a, c}
  5091. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  5092. (formula~\eqref{eq:live-before-after-minus-writes-plus-reads}). The
  5093. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  5094. variable that is not live and does not read from a variable.
  5095. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  5096. because it writes to variable \code{a}.
  5097. \begin{figure}[tbp]
  5098. \centering
  5099. \begin{tcolorbox}[colback=white]
  5100. \hspace{10pt}
  5101. \begin{minipage}{0.4\textwidth}
  5102. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  5103. movq $5, a
  5104. movq $30, b
  5105. movq a, c
  5106. movq $10, b
  5107. addq b, c
  5108. \end{lstlisting}
  5109. \end{minipage}
  5110. \vrule\hspace{10pt}
  5111. \begin{minipage}{0.45\textwidth}
  5112. \begin{align*}
  5113. L_{\mathsf{before}}(1)= \emptyset,
  5114. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  5115. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  5116. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  5117. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  5118. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  5119. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  5120. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  5121. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  5122. L_{\mathsf{after}}(5)= \emptyset
  5123. \end{align*}
  5124. \end{minipage}
  5125. \end{tcolorbox}
  5126. \caption{Example output of liveness analysis on a short example.}
  5127. \label{fig:liveness-example-0}
  5128. \end{figure}
  5129. \begin{exercise}\normalfont\normalsize
  5130. Perform liveness analysis by hand on the running example in
  5131. figure~\ref{fig:reg-eg}, computing the live-before and live-after
  5132. sets for each instruction. Compare your answers to the solution
  5133. shown in figure~\ref{fig:live-eg}.
  5134. \end{exercise}
  5135. \begin{figure}[tp]
  5136. \hspace{20pt}
  5137. \begin{minipage}{0.55\textwidth}
  5138. \begin{tcolorbox}[colback=white]
  5139. {\if\edition\racketEd
  5140. \begin{lstlisting}
  5141. |$\{\ttm{rsp}\}$|
  5142. movq $1, v
  5143. |$\{\ttm{v},\ttm{rsp}\}$|
  5144. movq $42, w
  5145. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  5146. movq v, x
  5147. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5148. addq $7, x
  5149. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  5150. movq x, y
  5151. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  5152. movq x, z
  5153. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5154. addq w, z
  5155. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  5156. movq y, t
  5157. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5158. negq t
  5159. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  5160. movq z, %rax
  5161. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  5162. addq t, %rax
  5163. |$\{\ttm{rax},\ttm{rsp}\}$|
  5164. jmp conclusion
  5165. \end{lstlisting}
  5166. \fi}
  5167. {\if\edition\pythonEd\pythonColor
  5168. \begin{lstlisting}
  5169. movq $1, v
  5170. |$\{\ttm{v}\}$|
  5171. movq $42, w
  5172. |$\{\ttm{w}, \ttm{v}\}$|
  5173. movq v, x
  5174. |$\{\ttm{w}, \ttm{x}\}$|
  5175. addq $7, x
  5176. |$\{\ttm{w}, \ttm{x}\}$|
  5177. movq x, y
  5178. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  5179. movq x, z
  5180. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  5181. addq w, z
  5182. |$\{\ttm{y}, \ttm{z}\}$|
  5183. movq y, tmp_0
  5184. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5185. negq tmp_0
  5186. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  5187. movq z, tmp_1
  5188. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  5189. addq tmp_0, tmp_1
  5190. |$\{\ttm{tmp\_1}\}$|
  5191. movq tmp_1, %rdi
  5192. |$\{\ttm{rdi}\}$|
  5193. callq print_int
  5194. |$\{\}$|
  5195. \end{lstlisting}
  5196. \fi}
  5197. \end{tcolorbox}
  5198. \end{minipage}
  5199. \caption{The running example annotated with live-after sets.}
  5200. \label{fig:live-eg}
  5201. \end{figure}
  5202. \begin{exercise}\normalfont\normalsize
  5203. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  5204. %
  5205. \racket{Store the sequence of live-after sets in the $\itm{info}$
  5206. field of the \code{Block} structure.}
  5207. %
  5208. \python{Return a dictionary that maps each instruction to its
  5209. live-after set.}
  5210. %
  5211. \racket{We recommend creating an auxiliary function that takes a list
  5212. of instructions and an initial live-after set (typically empty) and
  5213. returns the list of live-after sets.}
  5214. %
  5215. We recommend creating auxiliary functions to (1) compute the set
  5216. of locations that appear in an \Arg{}, (2) compute the locations read
  5217. by an instruction (the $R$ function), and (3) the locations written by
  5218. an instruction (the $W$ function). The \code{callq} instruction should
  5219. include all the caller-saved registers in its write set $W$ because
  5220. the calling convention says that those registers may be written to
  5221. during the function call. Likewise, the \code{callq} instruction
  5222. should include the appropriate argument-passing registers in its
  5223. read set $R$, depending on the arity of the function being
  5224. called. (This is why the abstract syntax for \code{callq} includes the
  5225. arity.)
  5226. \end{exercise}
  5227. %\clearpage
  5228. \section{Build the Interference Graph}
  5229. \label{sec:build-interference}
  5230. {\if\edition\racketEd
  5231. \begin{figure}[tp]
  5232. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  5233. \small
  5234. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  5235. A \emph{graph} is a collection of vertices and edges where each
  5236. edge connects two vertices. A graph is \emph{directed} if each
  5237. edge points from a source to a target. Otherwise the graph is
  5238. \emph{undirected}.
  5239. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  5240. \begin{description}
  5241. %% We currently don't use directed graphs. We instead use
  5242. %% directed multi-graphs. -Jeremy
  5243. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  5244. directed graph from a list of edges. Each edge is a list
  5245. containing the source and target vertex.
  5246. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  5247. undirected graph from a list of edges. Each edge is represented by
  5248. a list containing two vertices.
  5249. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  5250. inserts a vertex into the graph.
  5251. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  5252. inserts an edge between the two vertices.
  5253. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  5254. returns a sequence of vertices adjacent to the vertex.
  5255. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  5256. returns a sequence of all vertices in the graph.
  5257. \end{description}
  5258. \end{tcolorbox}
  5259. %\end{wrapfigure}
  5260. \caption{The Racket \code{graph} package.}
  5261. \label{fig:graph}
  5262. \end{figure}
  5263. \fi}
  5264. On the basis of the liveness analysis, we know where each location is
  5265. live. However, during register allocation, we need to answer
  5266. questions of the specific form: are locations $u$ and $v$ live at the
  5267. same time? (If so, they cannot be assigned to the same register.) To
  5268. make this question more efficient to answer, we create an explicit
  5269. data structure, an \emph{interference
  5270. graph}\index{subject}{interference graph}. An interference graph is
  5271. an undirected graph that has a node for every variable and register
  5272. and has an edge between two nodes if they are
  5273. live at the same time, that is, if they interfere with each other.
  5274. %
  5275. \racket{We recommend using the Racket \code{graph} package
  5276. (figure~\ref{fig:graph}) to represent the interference graph.}
  5277. %
  5278. \python{We provide implementations of directed and undirected graph
  5279. data structures in the file \code{graph.py} of the support code.}
  5280. A straightforward way to compute the interference graph is to look at
  5281. the set of live locations between each instruction and add an edge to
  5282. the graph for every pair of variables in the same set. This approach
  5283. is less than ideal for two reasons. First, it can be expensive because
  5284. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  5285. locations. Second, in the special case in which two locations hold the
  5286. same value (because one was assigned to the other), they can be live
  5287. at the same time without interfering with each other.
  5288. A better way to compute the interference graph is to focus on
  5289. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  5290. must not overwrite something in a live location. So for each
  5291. instruction, we create an edge between the locations being written to
  5292. and the live locations. (However, a location never interferes with
  5293. itself.) For the \key{callq} instruction, we consider all the
  5294. caller-saved registers to have been written to, so an edge is added
  5295. between every live variable and every caller-saved register. Also, for
  5296. \key{movq} there is the special case of two variables holding the same
  5297. value. If a live variable $v$ is the same as the source of the
  5298. \key{movq}, then there is no need to add an edge between $v$ and the
  5299. destination, because they both hold the same value.
  5300. %
  5301. Hence we have the following two rules:
  5302. \begin{enumerate}
  5303. \item If instruction $I_k$ is a move instruction of the form
  5304. \key{movq} $s$\key{,} $d$, then for every $v \in
  5305. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  5306. $(d,v)$.
  5307. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  5308. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  5309. $(d,v)$.
  5310. \end{enumerate}
  5311. Working from the top to bottom of figure~\ref{fig:live-eg}, we apply
  5312. these rules to each instruction. We highlight a few of the
  5313. instructions. \racket{The first instruction is \lstinline{movq $1, v},
  5314. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  5315. so \code{v} interferes with \code{rsp}.}
  5316. %
  5317. \python{The first instruction is \lstinline{movq $1, v}, and the
  5318. live-after set is $\{\ttm{v}\}$. Rule 1 applies, but there is
  5319. no interference because $\ttm{v}$ is the destination of the move.}
  5320. %
  5321. \racket{The fourth instruction is \lstinline{addq $7, x}, and the
  5322. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies, so
  5323. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  5324. %
  5325. \python{The fourth instruction is \lstinline{addq $7, x}, and the
  5326. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies, so
  5327. $\ttm{x}$ interferes with \ttm{w}.}
  5328. %
  5329. \racket{The next instruction is \lstinline{movq x, y}, and the
  5330. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  5331. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  5332. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5333. \ttm{x} and \ttm{y} hold the same value.}
  5334. %
  5335. \python{The next instruction is \lstinline{movq x, y}, and the
  5336. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  5337. applies, so \ttm{y} interferes with \ttm{w} but not
  5338. \ttm{x}, because \ttm{x} is the source of the move and therefore
  5339. \ttm{x} and \ttm{y} hold the same value.}
  5340. %
  5341. Figure~\ref{fig:interference-results} lists the interference results
  5342. for all the instructions, and the resulting interference graph is
  5343. shown in figure~\ref{fig:interfere}. We elide the register nodes from
  5344. the interference graph in figure~\ref{fig:interfere} because there
  5345. were no interference edges involving registers and we did not wish to
  5346. clutter the graph, but in general one needs to include all the
  5347. registers in the interference graph.
  5348. \begin{figure}[tbp]
  5349. \begin{tcolorbox}[colback=white]
  5350. \begin{quote}
  5351. {\if\edition\racketEd
  5352. \begin{tabular}{ll}
  5353. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  5354. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  5355. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5356. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  5357. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  5358. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  5359. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  5360. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5361. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  5362. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  5363. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  5364. \lstinline!jmp conclusion!& no interference.
  5365. \end{tabular}
  5366. \fi}
  5367. {\if\edition\pythonEd\pythonColor
  5368. \begin{tabular}{ll}
  5369. \lstinline!movq $1, v!& no interference\\
  5370. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  5371. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  5372. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  5373. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  5374. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  5375. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  5376. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5377. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  5378. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  5379. \lstinline!addq tmp_0, tmp_1! & no interference\\
  5380. \lstinline!movq tmp_1, %rdi! & no interference \\
  5381. \lstinline!callq print_int!& no interference.
  5382. \end{tabular}
  5383. \fi}
  5384. \end{quote}
  5385. \end{tcolorbox}
  5386. \caption{Interference results for the running example.}
  5387. \label{fig:interference-results}
  5388. \end{figure}
  5389. \begin{figure}[tbp]
  5390. \begin{tcolorbox}[colback=white]
  5391. \large
  5392. {\if\edition\racketEd
  5393. \[
  5394. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5395. \node (rax) at (0,0) {$\ttm{rax}$};
  5396. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5397. \node (t1) at (0,2) {$\ttm{t}$};
  5398. \node (z) at (3,2) {$\ttm{z}$};
  5399. \node (x) at (6,2) {$\ttm{x}$};
  5400. \node (y) at (3,0) {$\ttm{y}$};
  5401. \node (w) at (6,0) {$\ttm{w}$};
  5402. \node (v) at (9,0) {$\ttm{v}$};
  5403. \draw (t1) to (rax);
  5404. \draw (t1) to (z);
  5405. \draw (z) to (y);
  5406. \draw (z) to (w);
  5407. \draw (x) to (w);
  5408. \draw (y) to (w);
  5409. \draw (v) to (w);
  5410. \draw (v) to (rsp);
  5411. \draw (w) to (rsp);
  5412. \draw (x) to (rsp);
  5413. \draw (y) to (rsp);
  5414. \path[-.,bend left=15] (z) edge node {} (rsp);
  5415. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5416. \draw (rax) to (rsp);
  5417. \end{tikzpicture}
  5418. \]
  5419. \fi}
  5420. {\if\edition\pythonEd\pythonColor
  5421. \[
  5422. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5423. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5424. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5425. \node (z) at (3,2) {$\ttm{z}$};
  5426. \node (x) at (6,2) {$\ttm{x}$};
  5427. \node (y) at (3,0) {$\ttm{y}$};
  5428. \node (w) at (6,0) {$\ttm{w}$};
  5429. \node (v) at (9,0) {$\ttm{v}$};
  5430. \draw (t0) to (t1);
  5431. \draw (t0) to (z);
  5432. \draw (z) to (y);
  5433. \draw (z) to (w);
  5434. \draw (x) to (w);
  5435. \draw (y) to (w);
  5436. \draw (v) to (w);
  5437. \end{tikzpicture}
  5438. \]
  5439. \fi}
  5440. \end{tcolorbox}
  5441. \caption{The interference graph of the example program.}
  5442. \label{fig:interfere}
  5443. \end{figure}
  5444. \begin{exercise}\normalfont\normalsize
  5445. \racket{Implement the compiler pass named \code{build\_interference} according
  5446. to the algorithm suggested here. We recommend using the Racket
  5447. \code{graph} package to create and inspect the interference graph.
  5448. The output graph of this pass should be stored in the $\itm{info}$ field of
  5449. the program, under the key \code{conflicts}.}
  5450. %
  5451. \python{Implement a function named \code{build\_interference}
  5452. according to the algorithm suggested above that
  5453. returns the interference graph.}
  5454. \end{exercise}
  5455. \section{Graph Coloring via Sudoku}
  5456. \label{sec:graph-coloring}
  5457. \index{subject}{graph coloring}
  5458. \index{subject}{sudoku}
  5459. \index{subject}{color}
  5460. We come to the main event discussed in this chapter, mapping variables
  5461. to registers and stack locations. Variables that interfere with each
  5462. other must be mapped to different locations. In terms of the
  5463. interference graph, this means that adjacent vertices must be mapped
  5464. to different locations. If we think of locations as colors, the
  5465. register allocation problem becomes the graph coloring
  5466. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  5467. The reader may be more familiar with the graph coloring problem than he
  5468. or she realizes; the popular game of sudoku is an instance of the
  5469. graph coloring problem. The following describes how to build a graph
  5470. out of an initial sudoku board.
  5471. \begin{itemize}
  5472. \item There is one vertex in the graph for each sudoku square.
  5473. \item There is an edge between two vertices if the corresponding squares
  5474. are in the same row, in the same column, or in the same $3\times 3$ region.
  5475. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  5476. \item On the basis of the initial assignment of numbers to squares on the
  5477. sudoku board, assign the corresponding colors to the corresponding
  5478. vertices in the graph.
  5479. \end{itemize}
  5480. If you can color the remaining vertices in the graph with the nine
  5481. colors, then you have also solved the corresponding game of sudoku.
  5482. Figure~\ref{fig:sudoku-graph} shows an initial sudoku game board and
  5483. the corresponding graph with colored vertices. Here we use a
  5484. monochrome representation of colors, mapping the sudoku number 1 to
  5485. black, 2 to white, and 3 to gray. We show edges for only a sampling
  5486. of the vertices (the colored ones) because showing edges for all the
  5487. vertices would make the graph unreadable.
  5488. \begin{figure}[tbp]
  5489. \begin{tcolorbox}[colback=white]
  5490. \includegraphics[width=0.5\textwidth]{figs/sudoku}
  5491. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  5492. \end{tcolorbox}
  5493. \caption{A sudoku game board and the corresponding colored graph.}
  5494. \label{fig:sudoku-graph}
  5495. \end{figure}
  5496. Some techniques for playing sudoku correspond to heuristics used in
  5497. graph coloring algorithms. For example, one of the basic techniques
  5498. for sudoku is called Pencil Marks. The idea is to use a process of
  5499. elimination to determine what numbers are no longer available for a
  5500. square and to write those numbers in the square (writing very
  5501. small). For example, if the number $1$ is assigned to a square, then
  5502. write the pencil mark $1$ in all the squares in the same row, column,
  5503. and region to indicate that $1$ is no longer an option for those other
  5504. squares.
  5505. %
  5506. The Pencil Marks technique corresponds to the notion of
  5507. \emph{saturation}\index{subject}{saturation} due to \citet{Brelaz:1979eu}. The
  5508. saturation of a vertex, in sudoku terms, is the set of numbers that
  5509. are no longer available. In graph terminology, we have the following
  5510. definition:
  5511. \begin{equation*}
  5512. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  5513. \text{ and } \mathrm{color}(v) = c \}
  5514. \end{equation*}
  5515. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  5516. edge with $u$.
  5517. The Pencil Marks technique leads to a simple strategy for filling in
  5518. numbers: if there is a square with only one possible number left, then
  5519. choose that number! But what if there are no squares with only one
  5520. possibility left? One brute-force approach is to try them all: choose
  5521. the first one, and if that ultimately leads to a solution, great. If
  5522. not, backtrack and choose the next possibility. One good thing about
  5523. Pencil Marks is that it reduces the degree of branching in the search
  5524. tree. Nevertheless, backtracking can be terribly time consuming. One
  5525. way to reduce the amount of backtracking is to use the
  5526. most-constrained-first heuristic (aka minimum remaining
  5527. values)~\citep{Russell2003}. That is, in choosing a square, always
  5528. choose one with the fewest possibilities left (the vertex with the
  5529. highest saturation). The idea is that choosing highly constrained
  5530. squares earlier rather than later is better, because later on there may
  5531. not be any possibilities left in the highly saturated squares.
  5532. However, register allocation is easier than sudoku, because the
  5533. register allocator can fall back to assigning variables to stack
  5534. locations when the registers run out. Thus, it makes sense to replace
  5535. backtracking with greedy search: make the best choice at the time and
  5536. keep going. We still wish to minimize the number of colors needed, so
  5537. we use the most-constrained-first heuristic in the greedy search.
  5538. Figure~\ref{fig:satur-algo} gives the pseudocode for a simple greedy
  5539. algorithm for register allocation based on saturation and the
  5540. most-constrained-first heuristic. It is roughly equivalent to the
  5541. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}. Just as in
  5542. sudoku, the algorithm represents colors with integers. The integers
  5543. $0$ through $k-1$ correspond to the $k$ registers that we use for
  5544. register allocation. In particular, we recommend the following
  5545. correspondence, with $k=11$.
  5546. \begin{lstlisting}
  5547. 0: rcx, 1: rdx, 2: rsi, 3: rdi, 4: r8, 5: r9,
  5548. 6: r10, 7: rbx, 8: r12, 9: r13, 10: r14
  5549. \end{lstlisting}
  5550. The integers $k$ and larger correspond to stack locations. The
  5551. registers that are not used for register allocation, such as
  5552. \code{rax}, are assigned to negative integers. In particular, we
  5553. recommend the following correspondence.
  5554. \begin{lstlisting}
  5555. -1: rax, -2: rsp, -3: rbp, -4: r11, -5: r15
  5556. \end{lstlisting}
  5557. \begin{figure}[btp]
  5558. \begin{tcolorbox}[colback=white]
  5559. \centering
  5560. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  5561. Algorithm: DSATUR
  5562. Input: A graph |$G$|
  5563. Output: An assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  5564. |$W \gets \mathrm{vertices}(G)$|
  5565. while |$W \neq \emptyset$| do
  5566. pick a vertex |$u$| from |$W$| with the highest saturation,
  5567. breaking ties randomly
  5568. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  5569. |$\mathrm{color}[u] \gets c$|
  5570. |$W \gets W - \{u\}$|
  5571. \end{lstlisting}
  5572. \end{tcolorbox}
  5573. \caption{The saturation-based greedy graph coloring algorithm.}
  5574. \label{fig:satur-algo}
  5575. \end{figure}
  5576. {\if\edition\racketEd
  5577. With the DSATUR algorithm in hand, let us return to the running
  5578. example and consider how to color the interference graph shown in
  5579. figure~\ref{fig:interfere}.
  5580. %
  5581. We start by assigning each register node to its own color. For
  5582. example, \code{rax} is assigned the color $-1$, \code{rsp} is assign
  5583. $-2$, \code{rcx} is assigned $0$, and \code{rdx} is assigned $1$.
  5584. (To reduce clutter in the interference graph, we elide nodes
  5585. that do not have interference edges, such as \code{rcx}.)
  5586. The variables are not yet colored, so they are annotated with a dash. We
  5587. then update the saturation for vertices that are adjacent to a
  5588. register, obtaining the following annotated graph. For example, the
  5589. saturation for \code{t} is $\{-1,-2\}$ because it interferes with both
  5590. \code{rax} and \code{rsp}.
  5591. \[
  5592. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5593. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  5594. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  5595. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  5596. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  5597. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5598. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5599. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5600. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5601. \draw (t1) to (rax);
  5602. \draw (t1) to (z);
  5603. \draw (z) to (y);
  5604. \draw (z) to (w);
  5605. \draw (x) to (w);
  5606. \draw (y) to (w);
  5607. \draw (v) to (w);
  5608. \draw (v) to (rsp);
  5609. \draw (w) to (rsp);
  5610. \draw (x) to (rsp);
  5611. \draw (y) to (rsp);
  5612. \path[-.,bend left=15] (z) edge node {} (rsp);
  5613. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5614. \draw (rax) to (rsp);
  5615. \end{tikzpicture}
  5616. \]
  5617. The algorithm says to select a maximally saturated vertex. So, we pick
  5618. $\ttm{t}$ and color it with the first available integer, which is
  5619. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  5620. and \ttm{rsp} because they interfere with $\ttm{t}$.
  5621. \[
  5622. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5623. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5624. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  5625. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  5626. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  5627. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5628. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  5629. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  5630. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5631. \draw (t1) to (rax);
  5632. \draw (t1) to (z);
  5633. \draw (z) to (y);
  5634. \draw (z) to (w);
  5635. \draw (x) to (w);
  5636. \draw (y) to (w);
  5637. \draw (v) to (w);
  5638. \draw (v) to (rsp);
  5639. \draw (w) to (rsp);
  5640. \draw (x) to (rsp);
  5641. \draw (y) to (rsp);
  5642. \path[-.,bend left=15] (z) edge node {} (rsp);
  5643. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5644. \draw (rax) to (rsp);
  5645. \end{tikzpicture}
  5646. \]
  5647. We repeat the process, selecting a maximally saturated vertex,
  5648. choosing \code{z}, and coloring it with the first available number, which
  5649. is $1$. We add $1$ to the saturation for the neighboring vertices
  5650. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  5651. \[
  5652. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5653. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5654. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5655. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5656. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5657. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5658. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5659. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5660. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  5661. \draw (t1) to (rax);
  5662. \draw (t1) to (z);
  5663. \draw (z) to (y);
  5664. \draw (z) to (w);
  5665. \draw (x) to (w);
  5666. \draw (y) to (w);
  5667. \draw (v) to (w);
  5668. \draw (v) to (rsp);
  5669. \draw (w) to (rsp);
  5670. \draw (x) to (rsp);
  5671. \draw (y) to (rsp);
  5672. \path[-.,bend left=15] (z) edge node {} (rsp);
  5673. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5674. \draw (rax) to (rsp);
  5675. \end{tikzpicture}
  5676. \]
  5677. The most saturated vertices are now \code{w} and \code{y}. We color
  5678. \code{w} with the first available color, which is $0$.
  5679. \[
  5680. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5681. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5682. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  5683. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5684. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5685. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5686. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  5687. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  5688. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5689. \draw (t1) to (rax);
  5690. \draw (t1) to (z);
  5691. \draw (z) to (y);
  5692. \draw (z) to (w);
  5693. \draw (x) to (w);
  5694. \draw (y) to (w);
  5695. \draw (v) to (w);
  5696. \draw (v) to (rsp);
  5697. \draw (w) to (rsp);
  5698. \draw (x) to (rsp);
  5699. \draw (y) to (rsp);
  5700. \path[-.,bend left=15] (z) edge node {} (rsp);
  5701. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5702. \draw (rax) to (rsp);
  5703. \end{tikzpicture}
  5704. \]
  5705. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  5706. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  5707. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  5708. and \code{z}, whose colors are $0$ and $1$ respectively.
  5709. \[
  5710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5711. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5712. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5713. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5714. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5715. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5716. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5717. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5718. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  5719. \draw (t1) to (rax);
  5720. \draw (t1) to (z);
  5721. \draw (z) to (y);
  5722. \draw (z) to (w);
  5723. \draw (x) to (w);
  5724. \draw (y) to (w);
  5725. \draw (v) to (w);
  5726. \draw (v) to (rsp);
  5727. \draw (w) to (rsp);
  5728. \draw (x) to (rsp);
  5729. \draw (y) to (rsp);
  5730. \path[-.,bend left=15] (z) edge node {} (rsp);
  5731. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5732. \draw (rax) to (rsp);
  5733. \end{tikzpicture}
  5734. \]
  5735. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  5736. \[
  5737. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5738. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5739. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5740. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5741. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5742. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  5743. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5744. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5745. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5746. \draw (t1) to (rax);
  5747. \draw (t1) to (z);
  5748. \draw (z) to (y);
  5749. \draw (z) to (w);
  5750. \draw (x) to (w);
  5751. \draw (y) to (w);
  5752. \draw (v) to (w);
  5753. \draw (v) to (rsp);
  5754. \draw (w) to (rsp);
  5755. \draw (x) to (rsp);
  5756. \draw (y) to (rsp);
  5757. \path[-.,bend left=15] (z) edge node {} (rsp);
  5758. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5759. \draw (rax) to (rsp);
  5760. \end{tikzpicture}
  5761. \]
  5762. In the last step of the algorithm, we color \code{x} with $1$.
  5763. \[
  5764. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5765. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5766. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5767. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  5768. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5769. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  5770. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  5771. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  5772. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  5773. \draw (t1) to (rax);
  5774. \draw (t1) to (z);
  5775. \draw (z) to (y);
  5776. \draw (z) to (w);
  5777. \draw (x) to (w);
  5778. \draw (y) to (w);
  5779. \draw (v) to (w);
  5780. \draw (v) to (rsp);
  5781. \draw (w) to (rsp);
  5782. \draw (x) to (rsp);
  5783. \draw (y) to (rsp);
  5784. \path[-.,bend left=15] (z) edge node {} (rsp);
  5785. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5786. \draw (rax) to (rsp);
  5787. \end{tikzpicture}
  5788. \]
  5789. So, we obtain the following coloring:
  5790. \[
  5791. \{
  5792. \ttm{rax} \mapsto -1,
  5793. \ttm{rsp} \mapsto -2,
  5794. \ttm{t} \mapsto 0,
  5795. \ttm{z} \mapsto 1,
  5796. \ttm{x} \mapsto 1,
  5797. \ttm{y} \mapsto 2,
  5798. \ttm{w} \mapsto 0,
  5799. \ttm{v} \mapsto 1
  5800. \}
  5801. \]
  5802. \fi}
  5803. %
  5804. {\if\edition\pythonEd\pythonColor
  5805. %
  5806. With the DSATUR algorithm in hand, let us return to the running
  5807. example and consider how to color the interference graph shown in
  5808. figure~\ref{fig:interfere}. We annotate each variable node with a dash
  5809. to indicate that it has not yet been assigned a color. Each register
  5810. node (not shown) should be assigned the number that the register
  5811. corresponds to, for example, color \code{rcx} with the number \code{0}
  5812. and \code{rdx} with \code{1}. The saturation sets are also shown for
  5813. each node; all of them start as the empty set.
  5814. %
  5815. \[
  5816. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5817. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  5818. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  5819. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  5820. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5821. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5822. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5823. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5824. \draw (t0) to (t1);
  5825. \draw (t0) to (z);
  5826. \draw (z) to (y);
  5827. \draw (z) to (w);
  5828. \draw (x) to (w);
  5829. \draw (y) to (w);
  5830. \draw (v) to (w);
  5831. \end{tikzpicture}
  5832. \]
  5833. The algorithm says to select a maximally saturated vertex, but they
  5834. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  5835. and then we color it with the first available integer, which is $0$. We mark
  5836. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  5837. they interfere with $\ttm{tmp\_0}$.
  5838. \[
  5839. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5840. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  5841. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5842. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  5843. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5844. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  5845. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  5846. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5847. \draw (t0) to (t1);
  5848. \draw (t0) to (z);
  5849. \draw (z) to (y);
  5850. \draw (z) to (w);
  5851. \draw (x) to (w);
  5852. \draw (y) to (w);
  5853. \draw (v) to (w);
  5854. \end{tikzpicture}
  5855. \]
  5856. We repeat the process. The most saturated vertices are \code{z} and
  5857. \code{tmp\_1}, so we choose \code{z} and color it with the first
  5858. available number, which is $1$. We add $1$ to the saturation for the
  5859. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  5860. \[
  5861. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5862. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5863. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5864. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5865. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5866. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5867. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5868. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5869. \draw (t0) to (t1);
  5870. \draw (t0) to (z);
  5871. \draw (z) to (y);
  5872. \draw (z) to (w);
  5873. \draw (x) to (w);
  5874. \draw (y) to (w);
  5875. \draw (v) to (w);
  5876. \end{tikzpicture}
  5877. \]
  5878. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  5879. \code{y}. We color \code{w} with the first available color, which
  5880. is $0$.
  5881. \[
  5882. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5883. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5884. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5885. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5886. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5887. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  5888. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  5889. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  5890. \draw (t0) to (t1);
  5891. \draw (t0) to (z);
  5892. \draw (z) to (y);
  5893. \draw (z) to (w);
  5894. \draw (x) to (w);
  5895. \draw (y) to (w);
  5896. \draw (v) to (w);
  5897. \end{tikzpicture}
  5898. \]
  5899. Now \code{y} is the most saturated, so we color it with $2$.
  5900. \[
  5901. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  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,2\}$};
  5905. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5906. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5907. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5908. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  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. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  5919. We choose to color \code{v} with $1$.
  5920. \[
  5921. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5922. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5923. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5924. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5925. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  5926. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5927. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5928. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5929. \draw (t0) to (t1);
  5930. \draw (t0) to (z);
  5931. \draw (z) to (y);
  5932. \draw (z) to (w);
  5933. \draw (x) to (w);
  5934. \draw (y) to (w);
  5935. \draw (v) to (w);
  5936. \end{tikzpicture}
  5937. \]
  5938. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  5939. \[
  5940. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  5941. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5942. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5943. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  5944. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  5945. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  5946. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  5947. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  5948. \draw (t0) to (t1);
  5949. \draw (t0) to (z);
  5950. \draw (z) to (y);
  5951. \draw (z) to (w);
  5952. \draw (x) to (w);
  5953. \draw (y) to (w);
  5954. \draw (v) to (w);
  5955. \end{tikzpicture}
  5956. \]
  5957. So, we obtain the following coloring:
  5958. \[
  5959. \{ \ttm{tmp\_0} \mapsto 0,
  5960. \ttm{tmp\_1} \mapsto 1,
  5961. \ttm{z} \mapsto 1,
  5962. \ttm{x} \mapsto 1,
  5963. \ttm{y} \mapsto 2,
  5964. \ttm{w} \mapsto 0,
  5965. \ttm{v} \mapsto 1 \}
  5966. \]
  5967. \fi}
  5968. We recommend creating an auxiliary function named \code{color\_graph}
  5969. that takes an interference graph and a list of all the variables in
  5970. the program. This function should return a mapping of variables to
  5971. their colors (represented as natural numbers). By creating this helper
  5972. function, you will be able to reuse it in chapter~\ref{ch:Lfun}
  5973. when we add support for functions.
  5974. To prioritize the processing of highly saturated nodes inside the
  5975. \code{color\_graph} function, we recommend using the priority queue
  5976. data structure \racket{described in figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5977. addition, you will need to maintain a mapping from variables to their
  5978. handles in the priority queue so that you can notify the priority
  5979. queue when their saturation changes.}
  5980. {\if\edition\racketEd
  5981. \begin{figure}[tp]
  5982. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5983. \small
  5984. \begin{tcolorbox}[title=Priority Queue]
  5985. A \emph{priority queue}\index{subject}{priority queue}
  5986. is a collection of items in which the
  5987. removal of items is governed by priority. In a \emph{min} queue,
  5988. lower priority items are removed first. An implementation is in
  5989. \code{priority\_queue.rkt} of the support code.\index{subject}{min queue}
  5990. \begin{description}
  5991. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5992. priority queue that uses the $\itm{cmp}$ predicate to determine
  5993. whether its first argument has lower or equal priority to its
  5994. second argument.
  5995. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5996. items in the queue.
  5997. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5998. the item into the queue and returns a handle for the item in the
  5999. queue.
  6000. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  6001. the lowest priority.
  6002. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  6003. notifies the queue that the priority has decreased for the item
  6004. associated with the given handle.
  6005. \end{description}
  6006. \end{tcolorbox}
  6007. %\end{wrapfigure}
  6008. \caption{The priority queue data structure.}
  6009. \label{fig:priority-queue}
  6010. \end{figure}
  6011. \fi}
  6012. With the coloring complete, we finalize the assignment of variables to
  6013. registers and stack locations. We map the first $k$ colors to the $k$
  6014. registers and the rest of the colors to stack locations. Suppose for
  6015. the moment that we have just one register to use for register
  6016. allocation, \key{rcx}. Then we have the following assignment.
  6017. \[
  6018. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  6019. \]
  6020. Composing this mapping with the coloring, we arrive at the following
  6021. assignment of variables to locations.
  6022. {\if\edition\racketEd
  6023. \begin{gather*}
  6024. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6025. \ttm{w} \mapsto \key{\%rcx}, \,
  6026. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6027. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6028. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6029. \ttm{t} \mapsto \key{\%rcx} \}
  6030. \end{gather*}
  6031. \fi}
  6032. {\if\edition\pythonEd\pythonColor
  6033. \begin{gather*}
  6034. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  6035. \ttm{w} \mapsto \key{\%rcx}, \,
  6036. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  6037. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  6038. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6039. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6040. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6041. \end{gather*}
  6042. \fi}
  6043. Adapt the code from the \code{assign\_homes} pass
  6044. (section~\ref{sec:assign-Lvar}) to replace the variables with their
  6045. assigned location. Applying this assignment to our running
  6046. example shown next, on the left, yields the program on the right.
  6047. \begin{center}
  6048. {\if\edition\racketEd
  6049. \begin{minipage}{0.35\textwidth}
  6050. \begin{lstlisting}
  6051. movq $1, v
  6052. movq $42, w
  6053. movq v, x
  6054. addq $7, x
  6055. movq x, y
  6056. movq x, z
  6057. addq w, z
  6058. movq y, t
  6059. negq t
  6060. movq z, %rax
  6061. addq t, %rax
  6062. jmp conclusion
  6063. \end{lstlisting}
  6064. \end{minipage}
  6065. $\Rightarrow\qquad$
  6066. \begin{minipage}{0.45\textwidth}
  6067. \begin{lstlisting}
  6068. movq $1, -8(%rbp)
  6069. movq $42, %rcx
  6070. movq -8(%rbp), -8(%rbp)
  6071. addq $7, -8(%rbp)
  6072. movq -8(%rbp), -16(%rbp)
  6073. movq -8(%rbp), -8(%rbp)
  6074. addq %rcx, -8(%rbp)
  6075. movq -16(%rbp), %rcx
  6076. negq %rcx
  6077. movq -8(%rbp), %rax
  6078. addq %rcx, %rax
  6079. jmp conclusion
  6080. \end{lstlisting}
  6081. \end{minipage}
  6082. \fi}
  6083. {\if\edition\pythonEd\pythonColor
  6084. \begin{minipage}{0.35\textwidth}
  6085. \begin{lstlisting}
  6086. movq $1, v
  6087. movq $42, w
  6088. movq v, x
  6089. addq $7, x
  6090. movq x, y
  6091. movq x, z
  6092. addq w, z
  6093. movq y, tmp_0
  6094. negq tmp_0
  6095. movq z, tmp_1
  6096. addq tmp_0, tmp_1
  6097. movq tmp_1, %rdi
  6098. callq print_int
  6099. \end{lstlisting}
  6100. \end{minipage}
  6101. $\Rightarrow\qquad$
  6102. \begin{minipage}{0.45\textwidth}
  6103. \begin{lstlisting}
  6104. movq $1, -8(%rbp)
  6105. movq $42, %rcx
  6106. movq -8(%rbp), -8(%rbp)
  6107. addq $7, -8(%rbp)
  6108. movq -8(%rbp), -16(%rbp)
  6109. movq -8(%rbp), -8(%rbp)
  6110. addq %rcx, -8(%rbp)
  6111. movq -16(%rbp), %rcx
  6112. negq %rcx
  6113. movq -8(%rbp), -8(%rbp)
  6114. addq %rcx, -8(%rbp)
  6115. movq -8(%rbp), %rdi
  6116. callq print_int
  6117. \end{lstlisting}
  6118. \end{minipage}
  6119. \fi}
  6120. \end{center}
  6121. \begin{exercise}\normalfont\normalsize
  6122. Implement the \code{allocate\_registers} pass.
  6123. Create five programs that exercise all aspects of the register
  6124. allocation algorithm, including spilling variables to the stack.
  6125. %
  6126. {\if\edition\racketEd
  6127. Replace \code{assign\_homes} in the list of \code{passes} in the
  6128. \code{run-tests.rkt} script with the three new passes:
  6129. \code{uncover\_live}, \code{build\_interference}, and
  6130. \code{allocate\_registers}.
  6131. Temporarily remove the call to \code{compiler-tests}.
  6132. Run the script to test the register allocator.
  6133. \fi}
  6134. %
  6135. {\if\edition\pythonEd\pythonColor
  6136. Run the \code{run-tests.py} script to check whether the
  6137. output programs produce the same result as the input programs.
  6138. \fi}
  6139. \end{exercise}
  6140. \section{Patch Instructions}
  6141. \label{sec:patch-instructions}
  6142. The remaining step in the compilation to x86 is to ensure that the
  6143. instructions have at most one argument that is a memory access.
  6144. %
  6145. In the running example, the instruction \code{movq -8(\%rbp),
  6146. -16(\%rbp)} is problematic. Recall from section~\ref{sec:patch-s0}
  6147. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  6148. then move \code{rax} into \code{-16(\%rbp)}.
  6149. %
  6150. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  6151. problematic, but they can simply be deleted. In general, we recommend
  6152. deleting all the trivial moves whose source and destination are the
  6153. same location.
  6154. %
  6155. The following is the output of \code{patch\_instructions} on the
  6156. running example.
  6157. \begin{center}
  6158. {\if\edition\racketEd
  6159. \begin{minipage}{0.35\textwidth}
  6160. \begin{lstlisting}
  6161. movq $1, -8(%rbp)
  6162. movq $42, %rcx
  6163. movq -8(%rbp), -8(%rbp)
  6164. addq $7, -8(%rbp)
  6165. movq -8(%rbp), -16(%rbp)
  6166. movq -8(%rbp), -8(%rbp)
  6167. addq %rcx, -8(%rbp)
  6168. movq -16(%rbp), %rcx
  6169. negq %rcx
  6170. movq -8(%rbp), %rax
  6171. addq %rcx, %rax
  6172. jmp conclusion
  6173. \end{lstlisting}
  6174. \end{minipage}
  6175. $\Rightarrow\qquad$
  6176. \begin{minipage}{0.45\textwidth}
  6177. \begin{lstlisting}
  6178. movq $1, -8(%rbp)
  6179. movq $42, %rcx
  6180. addq $7, -8(%rbp)
  6181. movq -8(%rbp), %rax
  6182. movq %rax, -16(%rbp)
  6183. addq %rcx, -8(%rbp)
  6184. movq -16(%rbp), %rcx
  6185. negq %rcx
  6186. movq -8(%rbp), %rax
  6187. addq %rcx, %rax
  6188. jmp conclusion
  6189. \end{lstlisting}
  6190. \end{minipage}
  6191. \fi}
  6192. {\if\edition\pythonEd\pythonColor
  6193. \begin{minipage}{0.35\textwidth}
  6194. \begin{lstlisting}
  6195. movq $1, -8(%rbp)
  6196. movq $42, %rcx
  6197. movq -8(%rbp), -8(%rbp)
  6198. addq $7, -8(%rbp)
  6199. movq -8(%rbp), -16(%rbp)
  6200. movq -8(%rbp), -8(%rbp)
  6201. addq %rcx, -8(%rbp)
  6202. movq -16(%rbp), %rcx
  6203. negq %rcx
  6204. movq -8(%rbp), -8(%rbp)
  6205. addq %rcx, -8(%rbp)
  6206. movq -8(%rbp), %rdi
  6207. callq print_int
  6208. \end{lstlisting}
  6209. \end{minipage}
  6210. $\Rightarrow\qquad$
  6211. \begin{minipage}{0.45\textwidth}
  6212. \begin{lstlisting}
  6213. movq $1, -8(%rbp)
  6214. movq $42, %rcx
  6215. addq $7, -8(%rbp)
  6216. movq -8(%rbp), %rax
  6217. movq %rax, -16(%rbp)
  6218. addq %rcx, -8(%rbp)
  6219. movq -16(%rbp), %rcx
  6220. negq %rcx
  6221. addq %rcx, -8(%rbp)
  6222. movq -8(%rbp), %rdi
  6223. callq print_int
  6224. \end{lstlisting}
  6225. \end{minipage}
  6226. \fi}
  6227. \end{center}
  6228. \begin{exercise}\normalfont\normalsize
  6229. %
  6230. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  6231. %
  6232. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  6233. %in the \code{run-tests.rkt} script.
  6234. %
  6235. Run the script to test the \code{patch\_instructions} pass.
  6236. \end{exercise}
  6237. \section{Generate Prelude and Conclusion}
  6238. \label{sec:print-x86-reg-alloc}
  6239. \index{subject}{calling conventions}
  6240. \index{subject}{prelude}\index{subject}{conclusion}
  6241. Recall that this pass generates the prelude and conclusion
  6242. instructions to satisfy the x86 calling conventions
  6243. (section~\ref{sec:calling-conventions}). With the addition of the
  6244. register allocator, the callee-saved registers used by the register
  6245. allocator must be saved in the prelude and restored in the conclusion.
  6246. In the \code{allocate\_registers} pass,
  6247. %
  6248. \racket{add an entry to the \itm{info}
  6249. of \code{X86Program} named \code{used\_callee}}
  6250. %
  6251. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  6252. %
  6253. that stores the set of callee-saved registers that were assigned to
  6254. variables. The \code{prelude\_and\_conclusion} pass can then access
  6255. this information to decide which callee-saved registers need to be
  6256. saved and restored.
  6257. %
  6258. When calculating the amount to adjust the \code{rsp} in the prelude,
  6259. make sure to take into account the space used for saving the
  6260. callee-saved registers. Also, remember that the frame needs to be a
  6261. multiple of 16 bytes! We recommend using the following equation for
  6262. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  6263. of stack locations used by spilled variables\footnote{Sometimes two or
  6264. more spilled variables are assigned to the same stack location, so
  6265. $S$ can be less than the number of spilled variables.} and $C$ be
  6266. the number of callee-saved registers that were
  6267. allocated\index{subject}{allocate} to
  6268. variables. The $\itm{align}$ function rounds a number up to the
  6269. nearest 16 bytes.
  6270. \[
  6271. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  6272. \]
  6273. The reason we subtract $8\itm{C}$ in this equation is that the
  6274. prelude uses \code{pushq} to save each of the callee-saved registers,
  6275. and \code{pushq} subtracts $8$ from the \code{rsp}.
  6276. \racket{An overview of all the passes involved in register
  6277. allocation is shown in figure~\ref{fig:reg-alloc-passes}.}
  6278. {\if\edition\racketEd
  6279. \begin{figure}[tbp]
  6280. \begin{tcolorbox}[colback=white]
  6281. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6282. \node (Lvar) at (0,2) {\large \LangVar{}};
  6283. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  6284. \node (Lvar-3) at (7,2) {\large \LangVarANF{}};
  6285. \node (Cvar-1) at (0,0) {\large \LangCVar{}};
  6286. \node (x86-2) at (0,-2) {\large \LangXVar{}};
  6287. \node (x86-3) at (3,-2) {\large \LangXVar{}};
  6288. \node (x86-4) at (7,-2) {\large \LangXInt{}};
  6289. \node (x86-5) at (7,-4) {\large \LangXInt{}};
  6290. \node (x86-2-1) at (0,-4) {\large \LangXVar{}};
  6291. \node (x86-2-2) at (3,-4) {\large \LangXVar{}};
  6292. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  6293. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvar-3);
  6294. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (Cvar-1);
  6295. \path[->,bend right=15] (Cvar-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  6296. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  6297. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  6298. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  6299. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  6300. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  6301. \end{tikzpicture}
  6302. \end{tcolorbox}
  6303. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  6304. \label{fig:reg-alloc-passes}
  6305. \end{figure}
  6306. \fi}
  6307. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  6308. the running example (figure~\ref{fig:reg-eg}). To demonstrate both the
  6309. use of registers and the stack, we limit the register allocator for
  6310. this example to use just two registers: \code{rcx} (color $0$) and
  6311. \code{rbx} (color $1$). In the prelude\index{subject}{prelude} of the
  6312. \code{main} function, we push \code{rbx} onto the stack because it is
  6313. a callee-saved register and it was assigned to a variable by the
  6314. register allocator. We subtract \code{8} from the \code{rsp} at the
  6315. end of the prelude to reserve space for the one spilled variable.
  6316. After that subtraction, the \code{rsp} is aligned to 16 bytes.
  6317. Moving on to the program proper, we see how the registers were
  6318. allocated.
  6319. %
  6320. \racket{Variables \code{v}, \code{x}, and \code{z} were assigned to
  6321. \code{rbx}, and variables \code{w} and \code{t} was assigned to \code{rcx}.}
  6322. %
  6323. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  6324. were assigned to \code{rcx}, and variables \code{w} and \code{tmp\_1}
  6325. were assigned to \code{rbx}.}
  6326. %
  6327. Variable \racket{\code{y}}\python{\code{z}} was spilled to the stack
  6328. location \code{-16(\%rbp)}. Recall that the prelude saved the
  6329. callee-save register \code{rbx} onto the stack. The spilled variables
  6330. must be placed lower on the stack than the saved callee-save
  6331. registers, so in this case \racket{\code{y}}\python{z} is placed at
  6332. \code{-16(\%rbp)}.
  6333. In the conclusion\index{subject}{conclusion}, we undo the work that was
  6334. done in the prelude. We move the stack pointer up by \code{8} bytes
  6335. (the room for spilled variables), then pop the old values of
  6336. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  6337. \code{retq} to return control to the operating system.
  6338. \begin{figure}[tbp]
  6339. \begin{minipage}{0.55\textwidth}
  6340. \begin{tcolorbox}[colback=white]
  6341. % var_test_28.rkt
  6342. % (use-minimal-set-of-registers! #t)
  6343. % 0 -> rcx
  6344. % 1 -> rbx
  6345. %
  6346. % t 0 rcx
  6347. % z 1 rbx
  6348. % w 0 rcx
  6349. % y 2 rbp -16
  6350. % v 1 rbx
  6351. % x 1 rbx
  6352. {\if\edition\racketEd
  6353. \begin{lstlisting}
  6354. start:
  6355. movq $1, %rbx
  6356. movq $42, %rcx
  6357. addq $7, %rbx
  6358. movq %rbx, -16(%rbp)
  6359. addq %rcx, %rbx
  6360. movq -16(%rbp), %rcx
  6361. negq %rcx
  6362. movq %rbx, %rax
  6363. addq %rcx, %rax
  6364. jmp conclusion
  6365. .globl main
  6366. main:
  6367. pushq %rbp
  6368. movq %rsp, %rbp
  6369. pushq %rbx
  6370. subq $8, %rsp
  6371. jmp start
  6372. conclusion:
  6373. addq $8, %rsp
  6374. popq %rbx
  6375. popq %rbp
  6376. retq
  6377. \end{lstlisting}
  6378. \fi}
  6379. {\if\edition\pythonEd\pythonColor
  6380. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  6381. \begin{lstlisting}
  6382. .globl main
  6383. main:
  6384. pushq %rbp
  6385. movq %rsp, %rbp
  6386. pushq %rbx
  6387. subq $8, %rsp
  6388. movq $1, %rcx
  6389. movq $42, %rbx
  6390. addq $7, %rcx
  6391. movq %rcx, -16(%rbp)
  6392. addq %rbx, -16(%rbp)
  6393. negq %rcx
  6394. movq -16(%rbp), %rbx
  6395. addq %rcx, %rbx
  6396. movq %rbx, %rdi
  6397. callq print_int
  6398. addq $8, %rsp
  6399. popq %rbx
  6400. popq %rbp
  6401. retq
  6402. \end{lstlisting}
  6403. \fi}
  6404. \end{tcolorbox}
  6405. \end{minipage}
  6406. \caption{The x86 output from the running example
  6407. (figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  6408. and \code{rcx}.}
  6409. \label{fig:running-example-x86}
  6410. \end{figure}
  6411. \begin{exercise}\normalfont\normalsize
  6412. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  6413. %
  6414. \racket{
  6415. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  6416. list of passes and the call to \code{compiler-tests}.}
  6417. %
  6418. Run the script to test the complete compiler for \LangVar{} that
  6419. performs register allocation.
  6420. \end{exercise}
  6421. \section{Challenge: Move Biasing}
  6422. \label{sec:move-biasing}
  6423. \index{subject}{move biasing}
  6424. This section describes an enhancement to the register allocator,
  6425. called move biasing, for students who are looking for an extra
  6426. challenge.
  6427. {\if\edition\racketEd
  6428. To motivate the need for move biasing we return to the running example,
  6429. but this time we use all the general purpose registers. So, we have
  6430. the following mapping of color numbers to registers.
  6431. \[
  6432. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  6433. \]
  6434. Using the same assignment of variables to color numbers that was
  6435. produced by the register allocator described in the last section, we
  6436. get the following program.
  6437. \begin{center}
  6438. \begin{minipage}{0.35\textwidth}
  6439. \begin{lstlisting}
  6440. movq $1, v
  6441. movq $42, w
  6442. movq v, x
  6443. addq $7, x
  6444. movq x, y
  6445. movq x, z
  6446. addq w, z
  6447. movq y, t
  6448. negq t
  6449. movq z, %rax
  6450. addq t, %rax
  6451. jmp conclusion
  6452. \end{lstlisting}
  6453. \end{minipage}
  6454. $\Rightarrow\qquad$
  6455. \begin{minipage}{0.45\textwidth}
  6456. \begin{lstlisting}
  6457. movq $1, %rdx
  6458. movq $42, %rcx
  6459. movq %rdx, %rdx
  6460. addq $7, %rdx
  6461. movq %rdx, %rsi
  6462. movq %rdx, %rdx
  6463. addq %rcx, %rdx
  6464. movq %rsi, %rcx
  6465. negq %rcx
  6466. movq %rdx, %rax
  6467. addq %rcx, %rax
  6468. jmp conclusion
  6469. \end{lstlisting}
  6470. \end{minipage}
  6471. \end{center}
  6472. In this output code there are two \key{movq} instructions that
  6473. can be removed because their source and target are the same. However,
  6474. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  6475. register, we could instead remove three \key{movq} instructions. We
  6476. can accomplish this by taking into account which variables appear in
  6477. \key{movq} instructions with which other variables.
  6478. \fi}
  6479. {\if\edition\pythonEd\pythonColor
  6480. %
  6481. To motivate the need for move biasing we return to the running example
  6482. and recall that in section~\ref{sec:patch-instructions} we were able to
  6483. remove three trivial move instructions from the running
  6484. example. However, we could remove another trivial move if we were able
  6485. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  6486. We say that two variables $p$ and $q$ are \emph{move
  6487. related}\index{subject}{move related} if they participate together in
  6488. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  6489. \key{movq} $q$\key{,} $p$.
  6490. %
  6491. Recall that we color variables that are more saturated before coloring
  6492. variables that are less saturated, and in the case of equally
  6493. saturated variables, we choose randomly. Now we break such ties by
  6494. giving preference to variables that have an available color that is
  6495. the same as the color of a move-related variable.
  6496. %
  6497. Furthermore, when the register allocator chooses a color for a
  6498. variable, it should prefer a color that has already been used for a
  6499. move-related variable if one exists (and assuming that they do not
  6500. interfere). This preference should not override the preference for
  6501. registers over stack locations. So, this preference should be used as
  6502. a tie breaker in choosing between two registers or in choosing between
  6503. two stack locations.
  6504. We recommend representing the move relationships in a graph, similarly
  6505. to how we represented interference. The following is the \emph{move
  6506. graph} for our example.
  6507. {\if\edition\racketEd
  6508. \[
  6509. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6510. \node (rax) at (0,0) {$\ttm{rax}$};
  6511. \node (rsp) at (9,2) {$\ttm{rsp}$};
  6512. \node (t) at (0,2) {$\ttm{t}$};
  6513. \node (z) at (3,2) {$\ttm{z}$};
  6514. \node (x) at (6,2) {$\ttm{x}$};
  6515. \node (y) at (3,0) {$\ttm{y}$};
  6516. \node (w) at (6,0) {$\ttm{w}$};
  6517. \node (v) at (9,0) {$\ttm{v}$};
  6518. \draw (v) to (x);
  6519. \draw (x) to (y);
  6520. \draw (x) to (z);
  6521. \draw (y) to (t);
  6522. \end{tikzpicture}
  6523. \]
  6524. \fi}
  6525. %
  6526. {\if\edition\pythonEd\pythonColor
  6527. \[
  6528. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6529. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  6530. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  6531. \node (z) at (3,2) {$\ttm{z}$};
  6532. \node (x) at (6,2) {$\ttm{x}$};
  6533. \node (y) at (3,0) {$\ttm{y}$};
  6534. \node (w) at (6,0) {$\ttm{w}$};
  6535. \node (v) at (9,0) {$\ttm{v}$};
  6536. \draw (y) to (t0);
  6537. \draw (z) to (x);
  6538. \draw (z) to (t1);
  6539. \draw (x) to (y);
  6540. \draw (x) to (v);
  6541. \end{tikzpicture}
  6542. \]
  6543. \fi}
  6544. {\if\edition\racketEd
  6545. Now we replay the graph coloring, pausing to see the coloring of
  6546. \code{y}. Recall the following configuration. The most saturated vertices
  6547. were \code{w} and \code{y}.
  6548. \[
  6549. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6550. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6551. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6552. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6553. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6554. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6555. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  6556. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  6557. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6558. \draw (t1) to (rax);
  6559. \draw (t1) to (z);
  6560. \draw (z) to (y);
  6561. \draw (z) to (w);
  6562. \draw (x) to (w);
  6563. \draw (y) to (w);
  6564. \draw (v) to (w);
  6565. \draw (v) to (rsp);
  6566. \draw (w) to (rsp);
  6567. \draw (x) to (rsp);
  6568. \draw (y) to (rsp);
  6569. \path[-.,bend left=15] (z) edge node {} (rsp);
  6570. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6571. \draw (rax) to (rsp);
  6572. \end{tikzpicture}
  6573. \]
  6574. %
  6575. The last time, we chose to color \code{w} with $0$. This time, we see
  6576. that \code{w} is not move-related to any vertex, but \code{y} is
  6577. move-related to \code{t}. So we choose to color \code{y} with $0$,
  6578. the same color as \code{t}.
  6579. \[
  6580. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6581. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6582. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6583. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6584. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  6585. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  6586. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  6587. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  6588. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  6589. \draw (t1) to (rax);
  6590. \draw (t1) to (z);
  6591. \draw (z) to (y);
  6592. \draw (z) to (w);
  6593. \draw (x) to (w);
  6594. \draw (y) to (w);
  6595. \draw (v) to (w);
  6596. \draw (v) to (rsp);
  6597. \draw (w) to (rsp);
  6598. \draw (x) to (rsp);
  6599. \draw (y) to (rsp);
  6600. \path[-.,bend left=15] (z) edge node {} (rsp);
  6601. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6602. \draw (rax) to (rsp);
  6603. \end{tikzpicture}
  6604. \]
  6605. Now \code{w} is the most saturated, so we color it $2$.
  6606. \[
  6607. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6608. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6609. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6610. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6611. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6612. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  6613. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6614. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6615. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  6616. \draw (t1) to (rax);
  6617. \draw (t1) to (z);
  6618. \draw (z) to (y);
  6619. \draw (z) to (w);
  6620. \draw (x) to (w);
  6621. \draw (y) to (w);
  6622. \draw (v) to (w);
  6623. \draw (v) to (rsp);
  6624. \draw (w) to (rsp);
  6625. \draw (x) to (rsp);
  6626. \draw (y) to (rsp);
  6627. \path[-.,bend left=15] (z) edge node {} (rsp);
  6628. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6629. \draw (rax) to (rsp);
  6630. \end{tikzpicture}
  6631. \]
  6632. At this point, vertices \code{x} and \code{v} are most saturated, but
  6633. \code{x} is move related to \code{y} and \code{z}, so we color
  6634. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  6635. \[
  6636. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6637. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  6638. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  6639. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  6640. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  6641. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  6642. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  6643. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  6644. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  6645. \draw (t1) to (rax);
  6646. \draw (t) to (z);
  6647. \draw (z) to (y);
  6648. \draw (z) to (w);
  6649. \draw (x) to (w);
  6650. \draw (y) to (w);
  6651. \draw (v) to (w);
  6652. \draw (v) to (rsp);
  6653. \draw (w) to (rsp);
  6654. \draw (x) to (rsp);
  6655. \draw (y) to (rsp);
  6656. \path[-.,bend left=15] (z) edge node {} (rsp);
  6657. \path[-.,bend left=10] (t1) edge node {} (rsp);
  6658. \draw (rax) to (rsp);
  6659. \end{tikzpicture}
  6660. \]
  6661. \fi}
  6662. %
  6663. {\if\edition\pythonEd\pythonColor
  6664. Now we replay the graph coloring, pausing before the coloring of
  6665. \code{w}. Recall the following configuration. The most saturated vertices
  6666. were \code{tmp\_1}, \code{w}, and \code{y}.
  6667. \[
  6668. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6669. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6670. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6671. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6672. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6673. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  6674. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  6675. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6676. \draw (t0) to (t1);
  6677. \draw (t0) to (z);
  6678. \draw (z) to (y);
  6679. \draw (z) to (w);
  6680. \draw (x) to (w);
  6681. \draw (y) to (w);
  6682. \draw (v) to (w);
  6683. \end{tikzpicture}
  6684. \]
  6685. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  6686. or \code{y}. Note, however, that \code{w} is not move related to any
  6687. variables, whereas \code{y} and \code{tmp\_1} are move related to
  6688. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  6689. \code{y} and color it $0$, we can delete another move instruction.
  6690. \[
  6691. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6692. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6693. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6694. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6695. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  6696. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  6697. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  6698. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  6699. \draw (t0) to (t1);
  6700. \draw (t0) to (z);
  6701. \draw (z) to (y);
  6702. \draw (z) to (w);
  6703. \draw (x) to (w);
  6704. \draw (y) to (w);
  6705. \draw (v) to (w);
  6706. \end{tikzpicture}
  6707. \]
  6708. Now \code{w} is the most saturated, so we color it $2$.
  6709. \[
  6710. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6711. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6712. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  6713. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6714. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  6715. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6716. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6717. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  6718. \draw (t0) to (t1);
  6719. \draw (t0) to (z);
  6720. \draw (z) to (y);
  6721. \draw (z) to (w);
  6722. \draw (x) to (w);
  6723. \draw (y) to (w);
  6724. \draw (v) to (w);
  6725. \end{tikzpicture}
  6726. \]
  6727. To finish the coloring, \code{x} and \code{v} get $0$ and
  6728. \code{tmp\_1} gets $1$.
  6729. \[
  6730. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.9]
  6731. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  6732. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  6733. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  6734. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  6735. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  6736. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  6737. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  6738. \draw (t0) to (t1);
  6739. \draw (t0) to (z);
  6740. \draw (z) to (y);
  6741. \draw (z) to (w);
  6742. \draw (x) to (w);
  6743. \draw (y) to (w);
  6744. \draw (v) to (w);
  6745. \end{tikzpicture}
  6746. \]
  6747. \fi}
  6748. So, we have the following assignment of variables to registers.
  6749. {\if\edition\racketEd
  6750. \begin{gather*}
  6751. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6752. \ttm{w} \mapsto \key{\%rsi}, \,
  6753. \ttm{x} \mapsto \key{\%rcx}, \,
  6754. \ttm{y} \mapsto \key{\%rcx}, \,
  6755. \ttm{z} \mapsto \key{\%rdx}, \,
  6756. \ttm{t} \mapsto \key{\%rcx} \}
  6757. \end{gather*}
  6758. \fi}
  6759. {\if\edition\pythonEd\pythonColor
  6760. \begin{gather*}
  6761. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  6762. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  6763. \ttm{x} \mapsto \key{\%rcx}, \,
  6764. \ttm{y} \mapsto \key{\%rcx}, \\
  6765. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  6766. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  6767. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  6768. \end{gather*}
  6769. \fi}
  6770. %
  6771. We apply this register assignment to the running example shown next,
  6772. on the left, to obtain the code in the middle. The
  6773. \code{patch\_instructions} then deletes the trivial moves to obtain
  6774. the code on the right.
  6775. {\if\edition\racketEd
  6776. \begin{center}
  6777. \begin{minipage}{0.2\textwidth}
  6778. \begin{lstlisting}
  6779. movq $1, v
  6780. movq $42, w
  6781. movq v, x
  6782. addq $7, x
  6783. movq x, y
  6784. movq x, z
  6785. addq w, z
  6786. movq y, t
  6787. negq t
  6788. movq z, %rax
  6789. addq t, %rax
  6790. jmp conclusion
  6791. \end{lstlisting}
  6792. \end{minipage}
  6793. $\Rightarrow\qquad$
  6794. \begin{minipage}{0.25\textwidth}
  6795. \begin{lstlisting}
  6796. movq $1, %rcx
  6797. movq $42, %rsi
  6798. movq %rcx, %rcx
  6799. addq $7, %rcx
  6800. movq %rcx, %rcx
  6801. movq %rcx, %rdx
  6802. addq %rsi, %rdx
  6803. movq %rcx, %rcx
  6804. negq %rcx
  6805. movq %rdx, %rax
  6806. addq %rcx, %rax
  6807. jmp conclusion
  6808. \end{lstlisting}
  6809. \end{minipage}
  6810. $\Rightarrow\qquad$
  6811. \begin{minipage}{0.23\textwidth}
  6812. \begin{lstlisting}
  6813. movq $1, %rcx
  6814. movq $42, %rsi
  6815. addq $7, %rcx
  6816. movq %rcx, %rdx
  6817. addq %rsi, %rdx
  6818. negq %rcx
  6819. movq %rdx, %rax
  6820. addq %rcx, %rax
  6821. jmp conclusion
  6822. \end{lstlisting}
  6823. \end{minipage}
  6824. \end{center}
  6825. \fi}
  6826. {\if\edition\pythonEd\pythonColor
  6827. \begin{center}
  6828. \begin{minipage}{0.20\textwidth}
  6829. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6830. movq $1, v
  6831. movq $42, w
  6832. movq v, x
  6833. addq $7, x
  6834. movq x, y
  6835. movq x, z
  6836. addq w, z
  6837. movq y, tmp_0
  6838. negq tmp_0
  6839. movq z, tmp_1
  6840. addq tmp_0, tmp_1
  6841. movq tmp_1, %rdi
  6842. callq _print_int
  6843. \end{lstlisting}
  6844. \end{minipage}
  6845. ${\Rightarrow\qquad}$
  6846. \begin{minipage}{0.35\textwidth}
  6847. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6848. movq $1, %rcx
  6849. movq $42, -16(%rbp)
  6850. movq %rcx, %rcx
  6851. addq $7, %rcx
  6852. movq %rcx, %rcx
  6853. movq %rcx, -8(%rbp)
  6854. addq -16(%rbp), -8(%rbp)
  6855. movq %rcx, %rcx
  6856. negq %rcx
  6857. movq -8(%rbp), -8(%rbp)
  6858. addq %rcx, -8(%rbp)
  6859. movq -8(%rbp), %rdi
  6860. callq _print_int
  6861. \end{lstlisting}
  6862. \end{minipage}
  6863. ${\Rightarrow\qquad}$
  6864. \begin{minipage}{0.20\textwidth}
  6865. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6866. movq $1, %rcx
  6867. movq $42, -16(%rbp)
  6868. addq $7, %rcx
  6869. movq %rcx, -8(%rbp)
  6870. movq -16(%rbp), %rax
  6871. addq %rax, -8(%rbp)
  6872. negq %rcx
  6873. addq %rcx, -8(%rbp)
  6874. movq -8(%rbp), %rdi
  6875. callq print_int
  6876. \end{lstlisting}
  6877. \end{minipage}
  6878. \end{center}
  6879. \fi}
  6880. \begin{exercise}\normalfont\normalsize
  6881. Change your implementation of \code{allocate\_registers} to take move
  6882. biasing into account. Create two new tests that include at least one
  6883. opportunity for move biasing, and visually inspect the output x86
  6884. programs to make sure that your move biasing is working properly. Make
  6885. sure that your compiler still passes all the tests.
  6886. \end{exercise}
  6887. %To do: another neat challenge would be to do
  6888. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  6889. %% \subsection{Output of the Running Example}
  6890. %% \label{sec:reg-alloc-output}
  6891. % challenge: prioritize variables based on execution frequencies
  6892. % and the number of uses of a variable
  6893. % challenge: enhance the coloring algorithm using Chaitin's
  6894. % approach of prioritizing high-degree variables
  6895. % by removing low-degree variables (coloring them later)
  6896. % from the interference graph
  6897. \section{Further Reading}
  6898. \label{sec:register-allocation-further-reading}
  6899. Early register allocation algorithms were developed for Fortran
  6900. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  6901. of graph coloring began in the late 1970s and early 1980s with the
  6902. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  6903. algorithm is based on the following observation of
  6904. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  6905. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  6906. $v$ removed is also $k$ colorable. To see why, suppose that the
  6907. subgraph is $k$ colorable. At worst, the neighbors of $v$ are assigned
  6908. different colors, but because there are fewer than $k$ neighbors, there
  6909. will be one or more colors left over to use for coloring $v$ in $G$.
  6910. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  6911. less than $k$ from the graph and recursively colors the rest of the
  6912. graph. Upon returning from the recursion, it colors $v$ with one of
  6913. the available colors and returns. \citet{Chaitin:1982vn} augments
  6914. this algorithm to handle spilling as follows. If there are no vertices
  6915. of degree lower than $k$ then pick a vertex at random, spill it,
  6916. remove it from the graph, and proceed recursively to color the rest of
  6917. the graph.
  6918. Prior to coloring, \citet{Chaitin:1981vl} merged variables that are
  6919. move-related and that don't interfere with each other, in a process
  6920. called \emph{coalescing}. Although coalescing decreases the number of
  6921. moves, it can make the graph more difficult to
  6922. color. \citet{Briggs:1994kx} proposed \emph{conservative coalescing} in
  6923. which two variables are merged only if they have fewer than $k$
  6924. neighbors of high degree. \citet{George:1996aa} observes that
  6925. conservative coalescing is sometimes too conservative and made it more
  6926. aggressive by iterating the coalescing with the removal of low-degree
  6927. vertices.
  6928. %
  6929. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  6930. also proposed \emph{biased coloring}, in which a variable is assigned to
  6931. the same color as another move-related variable if possible, as
  6932. discussed in section~\ref{sec:move-biasing}.
  6933. %
  6934. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  6935. performs coalescing, graph coloring, and spill code insertion until
  6936. all variables have been assigned a location.
  6937. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  6938. spilled variables that don't have to be: a high-degree variable can be
  6939. colorable if many of its neighbors are assigned the same color.
  6940. \citet{Briggs:1994kx} proposed \emph{optimistic coloring}, in which a
  6941. high-degree vertex is not immediately spilled. Instead the decision is
  6942. deferred until after the recursive call, when it is apparent whether
  6943. there is an available color or not. We observe that this algorithm is
  6944. equivalent to the smallest-last ordering
  6945. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  6946. be registers and the rest to be stack locations.
  6947. %% biased coloring
  6948. Earlier editions of the compiler course at Indiana University
  6949. \citep{Dybvig:2010aa} were based on the algorithm of
  6950. \citet{Briggs:1994kx}.
  6951. The smallest-last ordering algorithm is one of many \emph{greedy}
  6952. coloring algorithms. A greedy coloring algorithm visits all the
  6953. vertices in a particular order and assigns each one the first
  6954. available color. An \emph{offline} greedy algorithm chooses the
  6955. ordering up front, prior to assigning colors. The algorithm of
  6956. \citet{Chaitin:1981vl} should be considered offline because the vertex
  6957. ordering does not depend on the colors assigned. Other orderings are
  6958. possible. For example, \citet{Chow:1984ys} ordered variables according
  6959. to an estimate of runtime cost.
  6960. An \emph{online} greedy coloring algorithm uses information about the
  6961. current assignment of colors to influence the order in which the
  6962. remaining vertices are colored. The saturation-based algorithm
  6963. described in this chapter is one such algorithm. We choose to use
  6964. saturation-based coloring because it is fun to introduce graph
  6965. coloring via sudoku!
  6966. A register allocator may choose to map each variable to just one
  6967. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  6968. variable to one or more locations. The latter can be achieved by
  6969. \emph{live range splitting}, where a variable is replaced by several
  6970. variables that each handle part of its live
  6971. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  6972. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  6973. %% replacement algorithm, bottom-up local
  6974. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  6975. %% Cooper: top-down (priority bassed), bottom-up
  6976. %% top-down
  6977. %% order variables by priority (estimated cost)
  6978. %% caveat: split variables into two groups:
  6979. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  6980. %% color the constrained ones first
  6981. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  6982. %% cite J. Cocke for an algorithm that colors variables
  6983. %% in a high-degree first ordering
  6984. %Register Allocation via Usage Counts, Freiburghouse CACM
  6985. \citet{Palsberg:2007si} observes that many of the interference graphs
  6986. that arise from Java programs in the JoeQ compiler are \emph{chordal};
  6987. that is, every cycle with four or more edges has an edge that is not
  6988. part of the cycle but that connects two vertices on the cycle. Such
  6989. graphs can be optimally colored by the greedy algorithm with a vertex
  6990. ordering determined by maximum cardinality search.
  6991. In situations in which compile time is of utmost importance, such as
  6992. in just-in-time compilers, graph coloring algorithms can be too
  6993. expensive, and the linear scan algorithm of \citet{Poletto:1999uq} may
  6994. be more appropriate.
  6995. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6996. {\if\edition\racketEd
  6997. \addtocontents{toc}{\newpage}
  6998. \fi}
  6999. \chapter{Booleans and Conditionals}
  7000. \label{ch:Lif}
  7001. \setcounter{footnote}{0}
  7002. The \LangVar{} language has only a single kind of value, the
  7003. integers. In this chapter we add a second kind of value, the Booleans,
  7004. to create the \LangIf{} language. In \racket{Racket}\python{Python},
  7005. the Boolean\index{subject}{Boolean} values \emph{true} and \emph{false}
  7006. are written
  7007. \TRUE{}\index{subject}{True@\TRUE{}} and
  7008. \FALSE{}\index{subject}{False@\FALSE{}}, respectively. The \LangIf{}
  7009. language includes several operations that involve Booleans
  7010. (\key{and}\index{subject}{and@\ANDNAME{}},
  7011. \key{or}\index{subject}{or@\ORNAME{}},
  7012. \key{not}\index{subject}{not@\NOTNAME{}},
  7013. \racket{\key{eq?}\index{subject}{equal@\EQNAME{}}}\python{==},
  7014. \key{<}\index{subject}{lessthan@\texttt{<}}, etc.) and the
  7015. \key{if}\index{subject}{IfExp@\IFNAME{}}
  7016. conditional expression\index{subject}{conditional expression}%
  7017. \python{ and statement\index{subject}{IfStmt@\IFSTMTNAME{}}}.
  7018. With the addition of \key{if}, programs can have
  7019. nontrivial control flow\index{subject}{control flow}, which
  7020. %
  7021. \racket{impacts \code{explicate\_control} and liveness analysis.}%
  7022. %
  7023. \python{impacts liveness analysis and motivates a new pass named
  7024. \code{explicate\_control}.}
  7025. %
  7026. Also, because we now have two kinds of values, we need to handle
  7027. programs that apply an operation to the wrong kind of value, such as
  7028. \racket{\code{(not 1)}}\python{\code{not 1}}.
  7029. There are two language design options for such situations. One option
  7030. is to signal an error and the other is to provide a wider
  7031. interpretation of the operation. \racket{The Racket
  7032. language}\python{Python} uses a mixture of these two options,
  7033. depending on the operation and the kind of value. For example, the
  7034. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  7035. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  7036. treats nonzero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  7037. %
  7038. \racket{On the other hand, \code{(car 1)} results in a runtime error
  7039. in Racket because \code{car} expects a pair.}
  7040. %
  7041. \python{On the other hand, \code{1[0]} results in a runtime error
  7042. in Python because an ``\code{int} object is not subscriptable.''}
  7043. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  7044. design choices as \racket{Racket}\python{Python}, except that much of the
  7045. error detection happens at compile time instead of runtime\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  7046. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  7047. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed Racket}
  7048. \python{MyPy} reports a compile-time error
  7049. %
  7050. \racket{because Racket expects the type of the argument to be of the form
  7051. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  7052. %
  7053. \python{stating that a ``value of type \code{int} is not indexable.''}
  7054. The \LangIf{} language performs type checking during compilation just as
  7055. \racket{Typed Racket}\python{MyPy}. In chapter~\ref{ch:Ldyn} we study
  7056. the alternative choice, that is, a dynamically typed language like
  7057. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  7058. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  7059. restrictive, for example, rejecting \racket{\code{(not
  7060. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  7061. fairly simple because the focus of this book is on compilation and not
  7062. type systems, about which there are already several excellent
  7063. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  7064. This chapter is organized as follows. We begin by defining the syntax
  7065. and interpreter for the \LangIf{} language
  7066. (section~\ref{sec:lang-if}). We then introduce the idea of type
  7067. checking (aka semantic analysis\index{subject}{semantic analysis})
  7068. and define a type checker for \LangIf{}
  7069. (section~\ref{sec:type-check-Lif}).
  7070. %
  7071. \racket{To compile \LangIf{} we need to enlarge the intermediate
  7072. language \LangCVar{} into \LangCIf{} (section~\ref{sec:Cif}) and
  7073. \LangXInt{} into \LangXIf{} (section~\ref{sec:x86-if}).}
  7074. %
  7075. The remaining sections of this chapter discuss how Booleans and
  7076. conditional control flow require changes to the existing compiler
  7077. passes and the addition of new ones. We introduce the \code{shrink}
  7078. pass to translate some operators into others, thereby reducing the
  7079. number of operators that need to be handled in later passes.
  7080. %
  7081. The main event of this chapter is the \code{explicate\_control} pass
  7082. that is responsible for translating \code{if}s into conditional
  7083. \code{goto}s (section~\ref{sec:explicate-control-Lif}).
  7084. %
  7085. Regarding register allocation, there is the interesting question of
  7086. how to handle conditional \code{goto}s during liveness analysis.
  7087. \section{The \LangIf{} Language}
  7088. \label{sec:lang-if}
  7089. Definitions of the concrete syntax and abstract syntax of the
  7090. \LangIf{} language are shown in figures~\ref{fig:Lif-concrete-syntax}
  7091. and~\ref{fig:Lif-syntax}, respectively. The \LangIf{} language
  7092. includes all of \LangVar{} {(shown in gray)}, the Boolean
  7093. literals\index{subject}{literals}
  7094. \TRUE{} and \FALSE{}, \racket{and} the \code{if} expression%
  7095. \python{, and the \code{if} statement}. We expand the set of
  7096. operators to include
  7097. \begin{enumerate}
  7098. \item the logical operators \key{and}, \key{or}, and \key{not},
  7099. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  7100. for comparing integers or Booleans for equality, and
  7101. \item the \key{<}, \key{<=}\index{subject}{lessthaneq@\texttt{<=}},
  7102. \key{>}\index{subject}{greaterthan@\texttt{>}}, and
  7103. \key{>=}\index{subject}{greaterthaneq@\texttt{>=}} operations for
  7104. comparing integers.
  7105. \end{enumerate}
  7106. \racket{We reorganize the abstract syntax for the primitive
  7107. operations given in figure~\ref{fig:Lif-syntax}, using only one grammar
  7108. rule for all of them. This means that the grammar no longer checks
  7109. whether the arity of an operator matches the number of
  7110. arguments. That responsibility is moved to the type checker for
  7111. \LangIf{} (section~\ref{sec:type-check-Lif}).}
  7112. \newcommand{\LifGrammarRacket}{
  7113. \begin{array}{lcl}
  7114. \Type &::=& \key{Boolean} \\
  7115. \itm{bool} &::=& \TRUE \MID \FALSE \\
  7116. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7117. \Exp &::=& \itm{bool}
  7118. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  7119. \MID (\key{not}\;\Exp) \\
  7120. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  7121. \end{array}
  7122. }
  7123. \newcommand{\LifASTRacket}{
  7124. \begin{array}{lcl}
  7125. \Type &::=& \key{Boolean} \\
  7126. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  7127. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7128. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  7129. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  7130. \end{array}
  7131. }
  7132. \newcommand{\LintOpAST}{
  7133. \begin{array}{rcl}
  7134. \Type &::=& \key{Integer} \\
  7135. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  7136. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  7137. \end{array}
  7138. }
  7139. \newcommand{\LifGrammarPython}{
  7140. \begin{array}{rcl}
  7141. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  7142. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  7143. \MID \key{not}~\Exp \\
  7144. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  7145. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  7146. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  7147. \end{array}
  7148. }
  7149. \newcommand{\LifASTPython}{
  7150. \begin{array}{lcl}
  7151. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  7152. %\itm{unaryop} &::=& \code{Not()} \\
  7153. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7154. \itm{bool} &::=& \code{True} \MID \code{False} \\
  7155. \Exp &::=& \BOOL{\itm{bool}}
  7156. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  7157. &\MID& \UNIOP{\key{Not()}}{\Exp}
  7158. \MID \CMP{\Exp}{\itm{cmp}}{\Exp} \\
  7159. &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  7160. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  7161. \end{array}
  7162. }
  7163. \begin{figure}[tp]
  7164. \centering
  7165. \begin{tcolorbox}[colback=white]
  7166. {\if\edition\racketEd
  7167. \[
  7168. \begin{array}{l}
  7169. \gray{\LintGrammarRacket{}} \\ \hline
  7170. \gray{\LvarGrammarRacket{}} \\ \hline
  7171. \LifGrammarRacket{} \\
  7172. \begin{array}{lcl}
  7173. \LangIfM{} &::=& \Exp
  7174. \end{array}
  7175. \end{array}
  7176. \]
  7177. \fi}
  7178. {\if\edition\pythonEd\pythonColor
  7179. \[
  7180. \begin{array}{l}
  7181. \gray{\LintGrammarPython} \\ \hline
  7182. \gray{\LvarGrammarPython} \\ \hline
  7183. \LifGrammarPython \\
  7184. \begin{array}{rcl}
  7185. \LangIfM{} &::=& \Stmt^{*}
  7186. \end{array}
  7187. \end{array}
  7188. \]
  7189. \fi}
  7190. \end{tcolorbox}
  7191. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  7192. (figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  7193. \label{fig:Lif-concrete-syntax}
  7194. \end{figure}
  7195. \begin{figure}[tp]
  7196. %\begin{minipage}{0.66\textwidth}
  7197. \begin{tcolorbox}[colback=white]
  7198. \centering
  7199. {\if\edition\racketEd
  7200. \[
  7201. \begin{array}{l}
  7202. \gray{\LintOpAST} \\ \hline
  7203. \gray{\LvarASTRacket{}} \\ \hline
  7204. \LifASTRacket{} \\
  7205. \begin{array}{lcl}
  7206. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  7207. \end{array}
  7208. \end{array}
  7209. \]
  7210. \fi}
  7211. {\if\edition\pythonEd\pythonColor
  7212. \[
  7213. \begin{array}{l}
  7214. \gray{\LintASTPython} \\ \hline
  7215. \gray{\LvarASTPython} \\ \hline
  7216. \LifASTPython \\
  7217. \begin{array}{lcl}
  7218. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  7219. \end{array}
  7220. \end{array}
  7221. \]
  7222. \fi}
  7223. \end{tcolorbox}
  7224. %\end{minipage}
  7225. \python{\index{subject}{not equal@\NOTEQNAME{}}}
  7226. \python{
  7227. \index{subject}{BoolOp@\texttt{BoolOp}}
  7228. \index{subject}{Compare@\texttt{Compare}}
  7229. \index{subject}{Lt@\texttt{Lt}}
  7230. \index{subject}{LtE@\texttt{LtE}}
  7231. \index{subject}{Gt@\texttt{Gt}}
  7232. \index{subject}{GtE@\texttt{GtE}}
  7233. }
  7234. \caption{The abstract syntax of \LangIf{}.}
  7235. \label{fig:Lif-syntax}
  7236. \end{figure}
  7237. Figure~\ref{fig:interp-Lif} shows the definition of the interpreter
  7238. for \LangIf{}, which inherits from the interpreter for \LangVar{}
  7239. (figure~\ref{fig:interp-Lvar}). The constants \TRUE{} and \FALSE{}
  7240. evaluate to the corresponding Boolean values, which is
  7241. inherited from the interpreter for \LangInt{} (figure~\ref{fig:interp-Lint-class}).
  7242. The conditional expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates
  7243. expression $e_1$ and then either evaluates $e_2$ or $e_3$, depending
  7244. on whether $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  7245. \code{and}, \code{or}, and \code{not} behave according to propositional
  7246. logic. In addition, the \code{and} and \code{or} operations perform
  7247. \emph{short-circuit evaluation}.
  7248. %
  7249. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  7250. is not evaluated if $e_1$ evaluates to \FALSE{}.
  7251. %
  7252. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  7253. evaluated if $e_1$ evaluates to \TRUE{}.
  7254. \racket{With the increase in the number of primitive operations, the
  7255. interpreter would become repetitive without some care. We refactor
  7256. the case for \code{Prim}, moving the code that differs with each
  7257. operation into the \code{interp\_op} method shown in
  7258. figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  7259. \code{or} operations separately because of their short-circuiting
  7260. behavior.}
  7261. \begin{figure}[tbp]
  7262. \begin{tcolorbox}[colback=white]
  7263. {\if\edition\racketEd
  7264. \begin{lstlisting}
  7265. (define interp-Lif-class
  7266. (class interp-Lvar-class
  7267. (super-new)
  7268. (define/public (interp_op op) ...)
  7269. (define/override ((interp_exp env) e)
  7270. (define recur (interp_exp env))
  7271. (match e
  7272. [(Bool b) b]
  7273. [(If cnd thn els)
  7274. (match (recur cnd)
  7275. [#t (recur thn)]
  7276. [#f (recur els)])]
  7277. [(Prim 'and (list e1 e2))
  7278. (match (recur e1)
  7279. [#t (match (recur e2) [#t #t] [#f #f])]
  7280. [#f #f])]
  7281. [(Prim 'or (list e1 e2))
  7282. (define v1 (recur e1))
  7283. (match v1
  7284. [#t #t]
  7285. [#f (match (recur e2) [#t #t] [#f #f])])]
  7286. [(Prim op args)
  7287. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  7288. [else ((super interp_exp env) e)]))
  7289. ))
  7290. (define (interp_Lif p)
  7291. (send (new interp-Lif-class) interp_program p))
  7292. \end{lstlisting}
  7293. \fi}
  7294. {\if\edition\pythonEd\pythonColor
  7295. \begin{lstlisting}
  7296. class InterpLif(InterpLvar):
  7297. def interp_exp(self, e, env):
  7298. match e:
  7299. case IfExp(test, body, orelse):
  7300. if self.interp_exp(test, env):
  7301. return self.interp_exp(body, env)
  7302. else:
  7303. return self.interp_exp(orelse, env)
  7304. case UnaryOp(Not(), v):
  7305. return not self.interp_exp(v, env)
  7306. case BoolOp(And(), values):
  7307. if self.interp_exp(values[0], env):
  7308. return self.interp_exp(values[1], env)
  7309. else:
  7310. return False
  7311. case BoolOp(Or(), values):
  7312. if self.interp_exp(values[0], env):
  7313. return True
  7314. else:
  7315. return self.interp_exp(values[1], env)
  7316. case Compare(left, [cmp], [right]):
  7317. l = self.interp_exp(left, env)
  7318. r = self.interp_exp(right, env)
  7319. return self.interp_cmp(cmp)(l, r)
  7320. case _:
  7321. return super().interp_exp(e, env)
  7322. def interp_stmt(self, s, env, cont):
  7323. match s:
  7324. case If(test, body, orelse):
  7325. match self.interp_exp(test, env):
  7326. case True:
  7327. return self.interp_stmts(body + cont, env)
  7328. case False:
  7329. return self.interp_stmts(orelse + cont, env)
  7330. case _:
  7331. return super().interp_stmt(s, env, cont)
  7332. ...
  7333. \end{lstlisting}
  7334. \fi}
  7335. \end{tcolorbox}
  7336. \caption{Interpreter for the \LangIf{} language. \racket{(See
  7337. figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  7338. \python{(See figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  7339. \label{fig:interp-Lif}
  7340. \end{figure}
  7341. {\if\edition\racketEd
  7342. \begin{figure}[tbp]
  7343. \begin{tcolorbox}[colback=white]
  7344. \begin{lstlisting}
  7345. (define/public (interp_op op)
  7346. (match op
  7347. ['+ fx+]
  7348. ['- fx-]
  7349. ['read read-fixnum]
  7350. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  7351. ['eq? (lambda (v1 v2)
  7352. (cond [(or (and (fixnum? v1) (fixnum? v2))
  7353. (and (boolean? v1) (boolean? v2))
  7354. (and (vector? v1) (vector? v2)))
  7355. (eq? v1 v2)]))]
  7356. ['< (lambda (v1 v2)
  7357. (cond [(and (fixnum? v1) (fixnum? v2))
  7358. (< v1 v2)]))]
  7359. ['<= (lambda (v1 v2)
  7360. (cond [(and (fixnum? v1) (fixnum? v2))
  7361. (<= v1 v2)]))]
  7362. ['> (lambda (v1 v2)
  7363. (cond [(and (fixnum? v1) (fixnum? v2))
  7364. (> v1 v2)]))]
  7365. ['>= (lambda (v1 v2)
  7366. (cond [(and (fixnum? v1) (fixnum? v2))
  7367. (>= v1 v2)]))]
  7368. [else (error 'interp_op "unknown operator")]))
  7369. \end{lstlisting}
  7370. \end{tcolorbox}
  7371. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  7372. \label{fig:interp-op-Lif}
  7373. \end{figure}
  7374. \fi}
  7375. {\if\edition\pythonEd\pythonColor
  7376. \begin{figure}
  7377. \begin{tcolorbox}[colback=white]
  7378. \begin{lstlisting}
  7379. class InterpLif(InterpLvar):
  7380. ...
  7381. def interp_cmp(self, cmp):
  7382. match cmp:
  7383. case Lt():
  7384. return lambda x, y: x < y
  7385. case LtE():
  7386. return lambda x, y: x <= y
  7387. case Gt():
  7388. return lambda x, y: x > y
  7389. case GtE():
  7390. return lambda x, y: x >= y
  7391. case Eq():
  7392. return lambda x, y: x == y
  7393. case NotEq():
  7394. return lambda x, y: x != y
  7395. \end{lstlisting}
  7396. \end{tcolorbox}
  7397. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  7398. \label{fig:interp-cmp-Lif}
  7399. \end{figure}
  7400. \fi}
  7401. \section{Type Checking \LangIf{} Programs}
  7402. \label{sec:type-check-Lif}
  7403. It is helpful to think about type checking\index{subject}{type
  7404. checking} in two complementary ways. A type checker predicts the
  7405. type of value that will be produced by each expression in the program.
  7406. For \LangIf{}, we have just two types, \INTTY{} and \BOOLTY{}. So, a
  7407. type checker should predict that {\if\edition\racketEd
  7408. \begin{lstlisting}
  7409. (+ 10 (- (+ 12 20)))
  7410. \end{lstlisting}
  7411. \fi}
  7412. {\if\edition\pythonEd\pythonColor
  7413. \begin{lstlisting}
  7414. 10 + -(12 + 20)
  7415. \end{lstlisting}
  7416. \fi}
  7417. \noindent produces a value of type \INTTY{}, whereas
  7418. {\if\edition\racketEd
  7419. \begin{lstlisting}
  7420. (and (not #f) #t)
  7421. \end{lstlisting}
  7422. \fi}
  7423. {\if\edition\pythonEd\pythonColor
  7424. \begin{lstlisting}
  7425. (not False) and True
  7426. \end{lstlisting}
  7427. \fi}
  7428. \noindent produces a value of type \BOOLTY{}.
  7429. A second way to think about type checking is that it enforces a set of
  7430. rules about which operators can be applied to which kinds of
  7431. values. For example, our type checker for \LangIf{} signals an error
  7432. for the following expression:
  7433. %
  7434. {\if\edition\racketEd
  7435. \begin{lstlisting}
  7436. (not (+ 10 (- (+ 12 20))))
  7437. \end{lstlisting}
  7438. \fi}
  7439. {\if\edition\pythonEd\pythonColor
  7440. \begin{lstlisting}
  7441. not (10 + -(12 + 20))
  7442. \end{lstlisting}
  7443. \fi}
  7444. \noindent The subexpression
  7445. \racket{\code{(+ 10 (- (+ 12 20)))}}
  7446. \python{\code{(10 + -(12 + 20))}}
  7447. has type \INTTY{}, but the type checker enforces the rule that the
  7448. argument of \code{not} must be an expression of type \BOOLTY{}.
  7449. We implement type checking using classes and methods because they
  7450. provide the open recursion needed to reuse code as we extend the type
  7451. checker in subsequent chapters, analogous to the use of classes and methods
  7452. for the interpreters (section~\ref{sec:extensible-interp}).
  7453. We separate the type checker for the \LangVar{} subset into its own
  7454. class, shown in figure~\ref{fig:type-check-Lvar}. The type checker for
  7455. \LangIf{} is shown in figure~\ref{fig:type-check-Lif}, and it inherits
  7456. from the type checker for \LangVar{}. These type checkers are in the
  7457. files
  7458. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  7459. and
  7460. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  7461. of the support code.
  7462. %
  7463. Each type checker is a structurally recursive function over the AST.
  7464. Given an input expression \code{e}, the type checker either signals an
  7465. error or returns \racket{an expression and its type.}\python{its type.}
  7466. %
  7467. \racket{It returns an expression because there are situations in which
  7468. we want to change or update the expression.}
  7469. Next we discuss the \code{type\_check\_exp} function of \LangVar{}
  7470. shown in figure~\ref{fig:type-check-Lvar}. The type of an integer
  7471. constant is \INTTY{}. To handle variables, the type checker uses the
  7472. environment \code{env} to map variables to types.
  7473. %
  7474. \racket{Consider the case for \key{let}. We type check the
  7475. initializing expression to obtain its type \key{T} and then
  7476. associate type \code{T} with the variable \code{x} in the
  7477. environment used to type check the body of the \key{let}. Thus,
  7478. when the type checker encounters a use of variable \code{x}, it can
  7479. find its type in the environment.}
  7480. %
  7481. \python{Consider the case for assignment. We type check the
  7482. initializing expression to obtain its type \key{t}. If the variable
  7483. \code{id} is already in the environment because there was a
  7484. prior assignment, we check that this initializer has the same type
  7485. as the prior one. If this is the first assignment to the variable,
  7486. we associate type \code{t} with the variable \code{id} in the
  7487. environment. Thus, when the type checker encounters a use of
  7488. variable \code{x}, it can find its type in the environment.}
  7489. %
  7490. \racket{Regarding primitive operators, we recursively analyze the
  7491. arguments and then invoke \code{type\_check\_op} to check whether
  7492. the argument types are allowed.}
  7493. %
  7494. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  7495. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  7496. \racket{Several auxiliary methods are used in the type checker. The
  7497. method \code{operator-types} defines a dictionary that maps the
  7498. operator names to their parameter and return types. The
  7499. \code{type-equal?} method determines whether two types are equal,
  7500. which for now simply dispatches to \code{equal?} (deep
  7501. equality). The \code{check-type-equal?} method triggers an error if
  7502. the two types are not equal. The \code{type-check-op} method looks
  7503. up the operator in the \code{operator-types} dictionary and then
  7504. checks whether the argument types are equal to the parameter types.
  7505. The result is the return type of the operator.}
  7506. %
  7507. \python{The auxiliary method \code{check\_type\_equal} triggers
  7508. an error if the two types are not equal.}
  7509. \begin{figure}[tbp]
  7510. \begin{tcolorbox}[colback=white]
  7511. {\if\edition\racketEd
  7512. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7513. (define type-check-Lvar-class
  7514. (class object%
  7515. (super-new)
  7516. (define/public (operator-types)
  7517. '((+ . ((Integer Integer) . Integer))
  7518. (- . ((Integer Integer) . Integer))
  7519. (read . (() . Integer))))
  7520. (define/public (type-equal? t1 t2) (equal? t1 t2))
  7521. (define/public (check-type-equal? t1 t2 e)
  7522. (unless (type-equal? t1 t2)
  7523. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  7524. (define/public (type-check-op op arg-types e)
  7525. (match (dict-ref (operator-types) op)
  7526. [`(,param-types . ,return-type)
  7527. (for ([at arg-types] [pt param-types])
  7528. (check-type-equal? at pt e))
  7529. return-type]
  7530. [else (error 'type-check-op "unrecognized ~a" op)]))
  7531. (define/public (type-check-exp env)
  7532. (lambda (e)
  7533. (match e
  7534. [(Int n) (values (Int n) 'Integer)]
  7535. [(Var x) (values (Var x) (dict-ref env x))]
  7536. [(Let x e body)
  7537. (define-values (e^ Te) ((type-check-exp env) e))
  7538. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  7539. (values (Let x e^ b) Tb)]
  7540. [(Prim op es)
  7541. (define-values (new-es ts)
  7542. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  7543. (values (Prim op new-es) (type-check-op op ts e))]
  7544. [else (error 'type-check-exp "couldn't match" e)])))
  7545. (define/public (type-check-program e)
  7546. (match e
  7547. [(Program info body)
  7548. (define-values (body^ Tb) ((type-check-exp '()) body))
  7549. (check-type-equal? Tb 'Integer body)
  7550. (Program info body^)]
  7551. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  7552. ))
  7553. (define (type-check-Lvar p)
  7554. (send (new type-check-Lvar-class) type-check-program p))
  7555. \end{lstlisting}
  7556. \fi}
  7557. {\if\edition\pythonEd\pythonColor
  7558. \begin{lstlisting}[escapechar=`]
  7559. class TypeCheckLvar:
  7560. def check_type_equal(self, t1, t2, e):
  7561. if t1 != t2:
  7562. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  7563. raise Exception(msg)
  7564. def type_check_exp(self, e, env):
  7565. match e:
  7566. case BinOp(left, (Add() | Sub()), right):
  7567. l = self.type_check_exp(left, env)
  7568. check_type_equal(l, int, left)
  7569. r = self.type_check_exp(right, env)
  7570. check_type_equal(r, int, right)
  7571. return int
  7572. case UnaryOp(USub(), v):
  7573. t = self.type_check_exp(v, env)
  7574. check_type_equal(t, int, v)
  7575. return int
  7576. case Name(id):
  7577. return env[id]
  7578. case Constant(value) if isinstance(value, int):
  7579. return int
  7580. case Call(Name('input_int'), []):
  7581. return int
  7582. def type_check_stmts(self, ss, env):
  7583. if len(ss) == 0:
  7584. return
  7585. match ss[0]:
  7586. case Assign([Name(id)], value):
  7587. t = self.type_check_exp(value, env)
  7588. if id in env:
  7589. check_type_equal(env[id], t, value)
  7590. else:
  7591. env[id] = t
  7592. return self.type_check_stmts(ss[1:], env)
  7593. case Expr(Call(Name('print'), [arg])):
  7594. t = self.type_check_exp(arg, env)
  7595. check_type_equal(t, int, arg)
  7596. return self.type_check_stmts(ss[1:], env)
  7597. case Expr(value):
  7598. self.type_check_exp(value, env)
  7599. return self.type_check_stmts(ss[1:], env)
  7600. def type_check_P(self, p):
  7601. match p:
  7602. case Module(body):
  7603. self.type_check_stmts(body, {})
  7604. \end{lstlisting}
  7605. \fi}
  7606. \end{tcolorbox}
  7607. \caption{Type checker for the \LangVar{} language.}
  7608. \label{fig:type-check-Lvar}
  7609. \end{figure}
  7610. \begin{figure}[tbp]
  7611. \begin{tcolorbox}[colback=white]
  7612. {\if\edition\racketEd
  7613. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7614. (define type-check-Lif-class
  7615. (class type-check-Lvar-class
  7616. (super-new)
  7617. (inherit check-type-equal?)
  7618. (define/override (operator-types)
  7619. (append '((and . ((Boolean Boolean) . Boolean))
  7620. (or . ((Boolean Boolean) . Boolean))
  7621. (< . ((Integer Integer) . Boolean))
  7622. (<= . ((Integer Integer) . Boolean))
  7623. (> . ((Integer Integer) . Boolean))
  7624. (>= . ((Integer Integer) . Boolean))
  7625. (not . ((Boolean) . Boolean)))
  7626. (super operator-types)))
  7627. (define/override (type-check-exp env)
  7628. (lambda (e)
  7629. (match e
  7630. [(Bool b) (values (Bool b) 'Boolean)]
  7631. [(Prim 'eq? (list e1 e2))
  7632. (define-values (e1^ T1) ((type-check-exp env) e1))
  7633. (define-values (e2^ T2) ((type-check-exp env) e2))
  7634. (check-type-equal? T1 T2 e)
  7635. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  7636. [(If cnd thn els)
  7637. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  7638. (define-values (thn^ Tt) ((type-check-exp env) thn))
  7639. (define-values (els^ Te) ((type-check-exp env) els))
  7640. (check-type-equal? Tc 'Boolean e)
  7641. (check-type-equal? Tt Te e)
  7642. (values (If cnd^ thn^ els^) Te)]
  7643. [else ((super type-check-exp env) e)])))
  7644. ))
  7645. (define (type-check-Lif p)
  7646. (send (new type-check-Lif-class) type-check-program p))
  7647. \end{lstlisting}
  7648. \fi}
  7649. {\if\edition\pythonEd\pythonColor
  7650. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7651. class TypeCheckLif(TypeCheckLvar):
  7652. def type_check_exp(self, e, env):
  7653. match e:
  7654. case Constant(value) if isinstance(value, bool):
  7655. return bool
  7656. case BinOp(left, Sub(), right):
  7657. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7658. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7659. return int
  7660. case UnaryOp(Not(), v):
  7661. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  7662. return bool
  7663. case BoolOp(op, values):
  7664. left = values[0] ; right = values[1]
  7665. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  7666. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  7667. return bool
  7668. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  7669. or isinstance(cmp, NotEq):
  7670. l = self.type_check_exp(left, env)
  7671. r = self.type_check_exp(right, env)
  7672. check_type_equal(l, r, e)
  7673. return bool
  7674. case Compare(left, [cmp], [right]):
  7675. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  7676. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  7677. return bool
  7678. case IfExp(test, body, orelse):
  7679. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7680. b = self.type_check_exp(body, env)
  7681. o = self.type_check_exp(orelse, env)
  7682. check_type_equal(b, o, e)
  7683. return b
  7684. case _:
  7685. return super().type_check_exp(e, env)
  7686. def type_check_stmts(self, ss, env):
  7687. if len(ss) == 0:
  7688. return
  7689. match ss[0]:
  7690. case If(test, body, orelse):
  7691. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  7692. b = self.type_check_stmts(body, env)
  7693. o = self.type_check_stmts(orelse, env)
  7694. check_type_equal(b, o, ss[0])
  7695. return self.type_check_stmts(ss[1:], env)
  7696. case _:
  7697. return super().type_check_stmts(ss, env)
  7698. \end{lstlisting}
  7699. \fi}
  7700. \end{tcolorbox}
  7701. \caption{Type checker for the \LangIf{} language.}
  7702. \label{fig:type-check-Lif}
  7703. \end{figure}
  7704. The definition of the type checker for \LangIf{} is shown in
  7705. figure~\ref{fig:type-check-Lif}.
  7706. %
  7707. The type of a Boolean constant is \BOOLTY{}.
  7708. %
  7709. \racket{The \code{operator-types} function adds dictionary entries for
  7710. the new operators.}
  7711. %
  7712. \python{The logical \code{not} operator requires its argument to be a
  7713. \BOOLTY{} and produces a \BOOLTY{}. Similarly for the logical \code{and}
  7714. and logical \code{or} operators.}
  7715. %
  7716. The equality operator requires the two arguments to have the same type,
  7717. and therefore we handle it separately from the other operators.
  7718. %
  7719. \python{The other comparisons (less-than, etc.) require their
  7720. arguments to be of type \INTTY{}, and they produce a \BOOLTY{}.}
  7721. %
  7722. The condition of an \code{if} must
  7723. be of \BOOLTY{} type, and the two branches must have the same type.
  7724. \begin{exercise}\normalfont\normalsize
  7725. Create ten new test programs in \LangIf{}. Half the programs should
  7726. have a type error.
  7727. \racket{For those programs, create an empty file with the
  7728. same base name and with file extension \code{.tyerr}. For example, if
  7729. the test \code{cond\_test\_14.rkt}
  7730. is expected to error, then create
  7731. an empty file named \code{cond\_test\_14.tyerr}.
  7732. This indicates to \code{interp-tests} and
  7733. \code{compiler-tests} that a type error is expected.}
  7734. %
  7735. The other half of the test programs should not have type errors.
  7736. %
  7737. \racket{In the \code{run-tests.rkt} script, change the second argument
  7738. of \code{interp-tests} and \code{compiler-tests} to
  7739. \code{type-check-Lif}, which causes the type checker to run prior to
  7740. the compiler passes. Temporarily change the \code{passes} to an
  7741. empty list and run the script, thereby checking that the new test
  7742. programs either type check or do not, as intended.}
  7743. %
  7744. Run the test script to check that these test programs type check as
  7745. expected.
  7746. \end{exercise}
  7747. \clearpage
  7748. \section{The \LangCIf{} Intermediate Language}
  7749. \label{sec:Cif}
  7750. {\if\edition\racketEd
  7751. %
  7752. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  7753. comparison operators to the \Exp{} nonterminal and the literals
  7754. \TRUE{} and \FALSE{} to the \Arg{} nonterminal. Regarding control
  7755. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  7756. \Tail{} nonterminal. The condition of an \code{if} statement is a
  7757. comparison operation and the branches are \code{goto} statements,
  7758. making it straightforward to compile \code{if} statements to x86. The
  7759. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  7760. expressions. A \code{goto} statement transfers control to the $\Tail$
  7761. expression corresponding to its label.
  7762. %
  7763. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  7764. \LangCIf{} intermediate language, and figure~\ref{fig:c1-syntax}
  7765. defines its abstract syntax.
  7766. %
  7767. \fi}
  7768. %
  7769. {\if\edition\pythonEd\pythonColor
  7770. %
  7771. The output of \key{explicate\_control} is a language similar to the
  7772. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  7773. \code{goto} statements, so we name it \LangCIf{}.
  7774. %
  7775. The \LangCIf{} language supports most of the operators in \LangIf{}, but
  7776. the arguments of operators are restricted to atomic expressions. The
  7777. \LangCIf{} language does not include \code{if} expressions, but it does
  7778. include a restricted form of \code{if} statement. The condition must be
  7779. a comparison, and the two branches may contain only \code{goto}
  7780. statements. These restrictions make it easier to translate \code{if}
  7781. statements to x86. The \LangCIf{} language also adds a \code{return}
  7782. statement to finish the program with a specified value.
  7783. %
  7784. The \key{CProgram} construct contains a dictionary mapping labels to
  7785. lists of statements that end with a \emph{tail} statement, which is
  7786. either a \code{return} statement, a \code{goto}, or an
  7787. \code{if} statement.
  7788. %
  7789. A \code{goto} transfers control to the sequence of statements
  7790. associated with its label.
  7791. %
  7792. Figure~\ref{fig:c1-concrete-syntax} shows the concrete syntax for \LangCIf{},
  7793. and figure~\ref{fig:c1-syntax} shows its
  7794. abstract syntax.
  7795. %
  7796. \fi}
  7797. %
  7798. \newcommand{\CifGrammarRacket}{
  7799. \begin{array}{lcl}
  7800. \Atm &::=& \itm{bool} \\
  7801. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7802. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  7803. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  7804. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  7805. \end{array}
  7806. }
  7807. \newcommand{\CifASTRacket}{
  7808. \begin{array}{lcl}
  7809. \Atm &::=& \BOOL{\itm{bool}} \\
  7810. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  7811. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  7812. \Tail &::= & \GOTO{\itm{label}} \\
  7813. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  7814. \end{array}
  7815. }
  7816. \newcommand{\CifGrammarPython}{
  7817. \begin{array}{lcl}
  7818. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  7819. \Exp &::= & \Atm \MID \CREAD{}
  7820. \MID \CUNIOP{\key{-}}{\Atm}
  7821. \MID \CBINOP{\key{+}}{\Atm}{\Atm}
  7822. \MID \CBINOP{\key{-}}{\Atm}{\Atm}
  7823. \MID \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  7824. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \MID \CASSIGN{\Var}{\Exp} \\
  7825. \Tail &::=& \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  7826. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  7827. \end{array}
  7828. }
  7829. \newcommand{\CifASTPython}{
  7830. \begin{array}{lcl}
  7831. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  7832. \Exp &::= & \Atm \MID \READ{}
  7833. \MID \UNIOP{\key{USub()}}{\Atm} \\
  7834. &\MID& \BINOP{\Atm}{\key{Sub()}}{\Atm}
  7835. \MID \BINOP{\Atm}{\key{Add()}}{\Atm} \\
  7836. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  7837. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  7838. &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  7839. \Tail &::= & \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  7840. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  7841. \end{array}
  7842. }
  7843. \begin{figure}[tbp]
  7844. \begin{tcolorbox}[colback=white]
  7845. \small
  7846. {\if\edition\racketEd
  7847. \[
  7848. \begin{array}{l}
  7849. \gray{\CvarGrammarRacket} \\ \hline
  7850. \CifGrammarRacket \\
  7851. \begin{array}{lcl}
  7852. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  7853. \end{array}
  7854. \end{array}
  7855. \]
  7856. \fi}
  7857. {\if\edition\pythonEd\pythonColor
  7858. \[
  7859. \begin{array}{l}
  7860. \CifGrammarPython \\
  7861. \begin{array}{lcl}
  7862. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}\;\Tail) \ldots
  7863. \end{array}
  7864. \end{array}
  7865. \]
  7866. \fi}
  7867. \end{tcolorbox}
  7868. \caption{The concrete syntax of the \LangCIf{} intermediate language%
  7869. \racket{, an extension of \LangCVar{} (figure~\ref{fig:c0-concrete-syntax})}.}
  7870. \label{fig:c1-concrete-syntax}
  7871. \end{figure}
  7872. \begin{figure}[tp]
  7873. \begin{tcolorbox}[colback=white]
  7874. \small
  7875. {\if\edition\racketEd
  7876. \[
  7877. \begin{array}{l}
  7878. \gray{\CvarASTRacket} \\ \hline
  7879. \CifASTRacket \\
  7880. \begin{array}{lcl}
  7881. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  7882. \end{array}
  7883. \end{array}
  7884. \]
  7885. \fi}
  7886. {\if\edition\pythonEd\pythonColor
  7887. \[
  7888. \begin{array}{l}
  7889. \CifASTPython \\
  7890. \begin{array}{lcl}
  7891. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\LS\Stmt,\ldots,\Tail\RS, \ldots \RC}
  7892. \end{array}
  7893. \end{array}
  7894. \]
  7895. \fi}
  7896. \end{tcolorbox}
  7897. \racket{
  7898. \index{subject}{IfStmt@\IFSTMTNAME{}}
  7899. }
  7900. \index{subject}{Goto@\texttt{Goto}}
  7901. \index{subject}{Return@\texttt{Return}}
  7902. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  7903. (figure~\ref{fig:c0-syntax})}.}
  7904. \label{fig:c1-syntax}
  7905. \end{figure}
  7906. \section{The \LangXIf{} Language}
  7907. \label{sec:x86-if}
  7908. \index{subject}{x86}
  7909. To implement Booleans, the new logical operations, the
  7910. comparison operations, and the \key{if} expression\python{ and
  7911. statement}, we delve further into the x86
  7912. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} present
  7913. the definitions of the concrete and abstract syntax for the \LangXIf{}
  7914. subset of x86, which includes instructions for logical operations,
  7915. comparisons, and \racket{conditional} jumps.
  7916. %
  7917. \python{The abstract syntax for an \LangXIf{} program contains a
  7918. dictionary mapping labels to sequences of instructions, each of
  7919. which we refer to as a \emph{basic block}\index{subject}{basic
  7920. block}.}
  7921. As x86 does not provide direct support for Booleans, we take the usual
  7922. approach of encoding Booleans as integers, with \code{True} as $1$ and
  7923. \code{False} as $0$.
  7924. Furthermore, x86 does not provide an instruction that directly
  7925. implements logical negation (\code{not} in \LangIf{} and \LangCIf{}).
  7926. However, the \code{xorq} instruction can be used to encode \code{not}.
  7927. The \key{xorq} instruction takes two arguments, performs a pairwise
  7928. exclusive-or ($\mathrm{XOR}$) operation on each bit of its arguments,
  7929. and writes the results into its second argument. Recall the following
  7930. truth table for exclusive-or:
  7931. \begin{center}
  7932. \begin{tabular}{l|cc}
  7933. & 0 & 1 \\ \hline
  7934. 0 & 0 & 1 \\
  7935. 1 & 1 & 0
  7936. \end{tabular}
  7937. \end{center}
  7938. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  7939. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  7940. for the bit $1$, the result is the opposite of the second bit. Thus,
  7941. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  7942. the first argument, as follows, where $\Arg$ is the translation of
  7943. $\Atm$ to x86:
  7944. \[
  7945. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  7946. \qquad\Rightarrow\qquad
  7947. \begin{array}{l}
  7948. \key{movq}~ \Arg\key{,} \Var\\
  7949. \key{xorq}~ \key{\$1,} \Var
  7950. \end{array}
  7951. \]
  7952. \newcommand{\GrammarXIf}{
  7953. \begin{array}{lcl}
  7954. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7955. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7956. \Arg &::=& \key{\%}\itm{bytereg}\\
  7957. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7958. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  7959. \MID \key{cmpq}~\Arg\key{,}~\Arg
  7960. \MID \key{set}cc~\Arg
  7961. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  7962. &\MID& \key{j}cc~\itm{label} \\
  7963. \end{array}
  7964. }
  7965. \begin{figure}[tp]
  7966. \begin{tcolorbox}[colback=white]
  7967. \[
  7968. \begin{array}{l}
  7969. \gray{\GrammarXInt} \\ \hline
  7970. \GrammarXIf \\
  7971. \begin{array}{lcl}
  7972. \LangXIfM{} &::= & \key{.globl main} \\
  7973. & & \key{main:} \; \Instr\ldots
  7974. \end{array}
  7975. \end{array}
  7976. \]
  7977. \end{tcolorbox}
  7978. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of figure~\ref{fig:x86-int-concrete}).}
  7979. \label{fig:x86-1-concrete}
  7980. \end{figure}
  7981. \newcommand{\ASTXIfRacket}{
  7982. \begin{array}{lcl}
  7983. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  7984. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  7985. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  7986. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  7987. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  7988. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  7989. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  7990. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  7991. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  7992. \end{array}
  7993. }
  7994. \newcommand{\ASTXIfPython}{
  7995. \begin{array}{lcl}
  7996. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  7997. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  7998. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  7999. \MID \BYTEREG{\itm{bytereg}} \\
  8000. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  8001. \Instr &::=& \python{\JMP{\itm{label}}}\\
  8002. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  8003. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  8004. &\MID& \UNIINSTR{\scode{set}\code{+}\itm{cc}}{\Arg}
  8005. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  8006. &\MID& \JMPIF{\itm{cc}}{\itm{label}}
  8007. \end{array}
  8008. }
  8009. \begin{figure}[tp]
  8010. \begin{tcolorbox}[colback=white]
  8011. \small
  8012. {\if\edition\racketEd
  8013. \[\arraycolsep=3pt
  8014. \begin{array}{l}
  8015. \gray{\ASTXIntRacket} \\ \hline
  8016. \ASTXIfRacket \\
  8017. \begin{array}{lcl}
  8018. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  8019. \end{array}
  8020. \end{array}
  8021. \]
  8022. \fi}
  8023. %
  8024. {\if\edition\pythonEd\pythonColor
  8025. \[
  8026. \begin{array}{l}
  8027. \gray{\ASTXIntPython} \\ \hline
  8028. \ASTXIfPython \\
  8029. \begin{array}{lcl}
  8030. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  8031. \end{array}
  8032. \end{array}
  8033. \]
  8034. \fi}
  8035. \end{tcolorbox}
  8036. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} shown in figure~\ref{fig:x86-int-ast}).}
  8037. \label{fig:x86-1}
  8038. \end{figure}
  8039. Next we consider the x86 instructions that are relevant for compiling
  8040. the comparison operations. The \key{cmpq} instruction compares its two
  8041. arguments to determine whether one argument is less than, equal to, or
  8042. greater than the other argument. The \key{cmpq} instruction is unusual
  8043. regarding the order of its arguments and where the result is
  8044. placed. The argument order is backward: if you want to test whether
  8045. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  8046. \key{cmpq} is placed in the special EFLAGS register. This register
  8047. cannot be accessed directly, but it can be queried by a number of
  8048. instructions, including the \key{set} instruction. The instruction
  8049. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$,
  8050. depending on whether the contents of the EFLAGS register matches the
  8051. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  8052. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  8053. The \key{set} instruction has a quirk in that its destination argument
  8054. must be a single-byte register, such as \code{al} (\code{l} for lower bits) or
  8055. \code{ah} (\code{h} for higher bits), which are part of the \code{rax}
  8056. register. Thankfully, the \key{movzbq} instruction can be used to
  8057. move from a single-byte register to a normal 64-bit register. The
  8058. abstract syntax for the \code{set} instruction differs from the
  8059. concrete syntax in that it separates the instruction name from the
  8060. condition code.
  8061. \python{The x86 instructions for jumping are relevant to the
  8062. compilation of \key{if} expressions.}
  8063. %
  8064. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  8065. counter to the address of the instruction after the specified
  8066. label.}
  8067. %
  8068. \racket{The x86 instruction for conditional jump is relevant to the
  8069. compilation of \key{if} expressions.}
  8070. %
  8071. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  8072. counter to point to the instruction after \itm{label}, depending on
  8073. whether the result in the EFLAGS register matches the condition code
  8074. \itm{cc}; otherwise, the jump instruction falls through to the next
  8075. instruction. Like the abstract syntax for \code{set}, the abstract
  8076. syntax for conditional jump separates the instruction name from the
  8077. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  8078. corresponds to \code{jle foo}. Because the conditional jump instruction
  8079. relies on the EFLAGS register, it is common for it to be immediately preceded by
  8080. a \key{cmpq} instruction to set the EFLAGS register.
  8081. \section{Shrink the \LangIf{} Language}
  8082. \label{sec:shrink-Lif}
  8083. The \code{shrink} pass translates some of the language features into
  8084. other features, thereby reducing the kinds of expressions in the
  8085. language. For example, the short-circuiting nature of the \code{and}
  8086. and \code{or} logical operators can be expressed using \code{if} as
  8087. follows.
  8088. \begin{align*}
  8089. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  8090. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  8091. \end{align*}
  8092. By performing these translations in the front end of the compiler,
  8093. subsequent passes of the compiler can be shorter.
  8094. On the other hand, translations sometimes reduce the efficiency of the
  8095. generated code by increasing the number of instructions. For example,
  8096. expressing subtraction in terms of addition and negation
  8097. \[
  8098. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  8099. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  8100. \]
  8101. produces code with two x86 instructions (\code{negq} and \code{addq})
  8102. instead of just one (\code{subq}). Thus, we do not recommend
  8103. translating subtraction into addition and negation.
  8104. \begin{exercise}\normalfont\normalsize
  8105. %
  8106. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  8107. the language by translating them to \code{if} expressions in \LangIf{}.
  8108. %
  8109. Create four test programs that involve these operators.
  8110. %
  8111. {\if\edition\racketEd
  8112. In the \code{run-tests.rkt} script, add the following entry for
  8113. \code{shrink} to the list of passes (it should be the only pass at
  8114. this point).
  8115. \begin{lstlisting}
  8116. (list "shrink" shrink interp_Lif type-check-Lif)
  8117. \end{lstlisting}
  8118. This instructs \code{interp-tests} to run the interpreter
  8119. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  8120. output of \code{shrink}.
  8121. \fi}
  8122. %
  8123. Run the script to test your compiler on all the test programs.
  8124. \end{exercise}
  8125. {\if\edition\racketEd
  8126. \section{Uniquify Variables}
  8127. \label{sec:uniquify-Lif}
  8128. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  8129. \code{if} expressions.
  8130. \begin{exercise}\normalfont\normalsize
  8131. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  8132. entry to the list of \code{passes} in the \code{run-tests.rkt} script:
  8133. \begin{lstlisting}
  8134. (list "uniquify" uniquify interp_Lif type_check_Lif)
  8135. \end{lstlisting}
  8136. Run the script to test your compiler.
  8137. \end{exercise}
  8138. \fi}
  8139. \section{Remove Complex Operands}
  8140. \label{sec:remove-complex-opera-Lif}
  8141. The output language of \code{remove\_complex\_operands} is
  8142. \LangIfANF{} (figure~\ref{fig:Lif-anf-syntax}), the monadic
  8143. normal form of \LangIf{}. A Boolean constant is an atomic expression,
  8144. but the \code{if} expression is not. All three subexpressions of an
  8145. \code{if} are allowed to be complex expressions, but the operands of
  8146. the \code{not} operator and comparison operators must be atomic.
  8147. %
  8148. \python{We add a new language form, the \code{Begin} expression, to aid
  8149. in the translation of \code{if} expressions. When we recursively
  8150. process the two branches of the \code{if}, we generate temporary
  8151. variables and their initializing expressions. However, these
  8152. expressions may contain side effects and should be executed only
  8153. when the condition of the \code{if} is true (for the ``then''
  8154. branch) or false (for the ``else'' branch). The \code{Begin} expression
  8155. provides a way to initialize the temporary variables within the two branches
  8156. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  8157. form executes the statements $ss$ and then returns the result of
  8158. expression $e$.}
  8159. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  8160. the new features in \LangIf{}. In recursively processing
  8161. subexpressions, recall that you should invoke \code{rco\_atom} when
  8162. the output needs to be an \Atm{} (as specified in the grammar for
  8163. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  8164. \Exp{}. Regarding \code{if}, it is particularly important
  8165. \emph{not} to replace its condition with a temporary variable, because
  8166. that would interfere with the generation of high-quality output in the
  8167. upcoming \code{explicate\_control} pass.
  8168. \newcommand{\LifMonadASTRacket}{
  8169. \begin{array}{rcl}
  8170. \Atm &::=& \BOOL{\itm{bool}}\\
  8171. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  8172. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  8173. \MID \IF{\Exp}{\Exp}{\Exp}
  8174. \end{array}
  8175. }
  8176. \newcommand{\LifMonadASTPython}{
  8177. \begin{array}{rcl}
  8178. \Atm &::=& \BOOL{\itm{bool}}\\
  8179. \Exp &::=& \UNIOP{\key{Not()}}{\Exp}
  8180. \MID \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  8181. &\MID& \IF{\Exp}{\Exp}{\Exp}
  8182. \MID \BEGIN{\Stmt^{*}}{\Exp}\\
  8183. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  8184. \end{array}
  8185. }
  8186. \begin{figure}[tp]
  8187. \centering
  8188. \begin{tcolorbox}[colback=white]
  8189. {\if\edition\racketEd
  8190. \[
  8191. \begin{array}{l}
  8192. \gray{\LvarMonadASTRacket} \\ \hline
  8193. \LifMonadASTRacket \\
  8194. \begin{array}{rcl}
  8195. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  8196. \end{array}
  8197. \end{array}
  8198. \]
  8199. \fi}
  8200. {\if\edition\pythonEd\pythonColor
  8201. \[
  8202. \begin{array}{l}
  8203. \gray{\LvarMonadASTPython} \\ \hline
  8204. \LifMonadASTPython \\
  8205. \begin{array}{rcl}
  8206. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  8207. \end{array}
  8208. \end{array}
  8209. \]
  8210. \fi}
  8211. \end{tcolorbox}
  8212. \python{\index{subject}{Begin@\texttt{Begin}}}
  8213. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  8214. (extends \LangVarANF in figure~\ref{fig:Lvar-anf-syntax}).}
  8215. \label{fig:Lif-anf-syntax}
  8216. \end{figure}
  8217. \begin{exercise}\normalfont\normalsize
  8218. %
  8219. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  8220. and \code{rco\_exp} functions.
  8221. %
  8222. Create three new \LangIf{} programs that exercise the interesting
  8223. code in this pass.
  8224. %
  8225. {\if\edition\racketEd
  8226. In the \code{run-tests.rkt} script, add the following entry to the
  8227. list of \code{passes} and then run the script to test your compiler.
  8228. \begin{lstlisting}
  8229. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  8230. \end{lstlisting}
  8231. \fi}
  8232. \end{exercise}
  8233. \section{Explicate Control}
  8234. \label{sec:explicate-control-Lif}
  8235. \racket{Recall that the purpose of \code{explicate\_control} is to
  8236. make the order of evaluation explicit in the syntax of the program.
  8237. With the addition of \key{if}, this becomes more interesting.}
  8238. %
  8239. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  8240. %
  8241. The main challenge to overcome is that the condition of an \key{if}
  8242. can be an arbitrary expression in \LangIf{}, whereas in \LangCIf{} the
  8243. condition must be a comparison.
  8244. As a motivating example, consider the following program that has an
  8245. \key{if} expression nested in the condition of another \key{if}:%
  8246. \python{\footnote{Programmers rarely write nested \code{if}
  8247. expressions, but they do write nested expressions involving
  8248. logical \code{and}, which, as we have seen, translates to
  8249. \code{if}.}}
  8250. % cond_test_41.rkt, if_lt_eq.py
  8251. \begin{center}
  8252. \begin{minipage}{0.96\textwidth}
  8253. {\if\edition\racketEd
  8254. \begin{lstlisting}
  8255. (let ([x (read)])
  8256. (let ([y (read)])
  8257. (if (if (< x 1) (eq? x 0) (eq? x 2))
  8258. (+ y 2)
  8259. (+ y 10))))
  8260. \end{lstlisting}
  8261. \fi}
  8262. {\if\edition\pythonEd\pythonColor
  8263. \begin{lstlisting}
  8264. x = input_int()
  8265. y = input_int()
  8266. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  8267. \end{lstlisting}
  8268. \fi}
  8269. \end{minipage}
  8270. \end{center}
  8271. %
  8272. The naive way to compile \key{if} and the comparison operations would
  8273. be to handle each of them in isolation, regardless of their context.
  8274. Each comparison would be translated into a \key{cmpq} instruction
  8275. followed by several instructions to move the result from the EFLAGS
  8276. register into a general purpose register or stack location. Each
  8277. \key{if} would be translated into a \key{cmpq} instruction followed by
  8278. a conditional jump. The generated code for the inner \key{if} in this
  8279. example would be as follows:
  8280. \begin{center}
  8281. \begin{minipage}{0.96\textwidth}
  8282. \begin{lstlisting}
  8283. cmpq $1, x
  8284. setl %al
  8285. movzbq %al, tmp
  8286. cmpq $1, tmp
  8287. je then_branch_1
  8288. jmp else_branch_1
  8289. \end{lstlisting}
  8290. \end{minipage}
  8291. \end{center}
  8292. Notice that the three instructions starting with \code{setl} are
  8293. redundant; the conditional jump could come immediately after the first
  8294. \code{cmpq}.
  8295. Our goal is to compile \key{if} expressions so that the relevant
  8296. comparison instruction appears directly before the conditional jump.
  8297. For example, we want to generate the following code for the inner
  8298. \code{if}:
  8299. \begin{center}
  8300. \begin{minipage}{0.96\textwidth}
  8301. \begin{lstlisting}
  8302. cmpq $1, x
  8303. jl then_branch_1
  8304. jmp else_branch_1
  8305. \end{lstlisting}
  8306. \end{minipage}
  8307. \end{center}
  8308. One way to achieve this goal is to reorganize the code at the level of
  8309. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  8310. the following code:
  8311. \begin{center}
  8312. \begin{minipage}{0.96\textwidth}
  8313. {\if\edition\racketEd
  8314. \begin{lstlisting}
  8315. (let ([x (read)])
  8316. (let ([y (read)])
  8317. (if (< x 1)
  8318. (if (eq? x 0)
  8319. (+ y 2)
  8320. (+ y 10))
  8321. (if (eq? x 2)
  8322. (+ y 2)
  8323. (+ y 10)))))
  8324. \end{lstlisting}
  8325. \fi}
  8326. {\if\edition\pythonEd\pythonColor
  8327. \begin{lstlisting}
  8328. x = input_int()
  8329. y = input_int()
  8330. print(((y + 2) if x == 0 else (y + 10)) \
  8331. if (x < 1) \
  8332. else ((y + 2) if (x == 2) else (y + 10)))
  8333. \end{lstlisting}
  8334. \fi}
  8335. \end{minipage}
  8336. \end{center}
  8337. Unfortunately, this approach duplicates the two branches from the
  8338. outer \code{if}, and a compiler must never duplicate code! After all,
  8339. the two branches could be very large expressions.
  8340. How can we apply this transformation without duplicating code? In
  8341. other words, how can two different parts of a program refer to one
  8342. piece of code?
  8343. %
  8344. The answer is that we must move away from abstract syntax \emph{trees}
  8345. and instead use \emph{graphs}.
  8346. %
  8347. At the level of x86 assembly, this is straightforward because we can
  8348. label the code for each branch and insert jumps in all the places that
  8349. need to execute the branch. In this way, jump instructions are edges
  8350. in the graph and the basic blocks are the nodes.
  8351. %
  8352. Likewise, our language \LangCIf{} provides the ability to label a
  8353. sequence of statements and to jump to a label via \code{goto}.
  8354. As a preview of what \code{explicate\_control} will do,
  8355. figure~\ref{fig:explicate-control-s1-38} shows the output of
  8356. \code{explicate\_control} on this example. Note how the condition of
  8357. every \code{if} is a comparison operation and that we have not
  8358. duplicated any code but instead have used labels and \code{goto} to
  8359. enable sharing of code.
  8360. \begin{figure}[tbp]
  8361. \begin{tcolorbox}[colback=white]
  8362. {\if\edition\racketEd
  8363. \begin{tabular}{lll}
  8364. \begin{minipage}{0.4\textwidth}
  8365. % cond_test_41.rkt
  8366. \begin{lstlisting}
  8367. (let ([x (read)])
  8368. (let ([y (read)])
  8369. (if (if (< x 1)
  8370. (eq? x 0)
  8371. (eq? x 2))
  8372. (+ y 2)
  8373. (+ y 10))))
  8374. \end{lstlisting}
  8375. \end{minipage}
  8376. &
  8377. $\Rightarrow$
  8378. &
  8379. \begin{minipage}{0.55\textwidth}
  8380. \begin{lstlisting}
  8381. start:
  8382. x = (read);
  8383. y = (read);
  8384. if (< x 1)
  8385. goto block_4;
  8386. else
  8387. goto block_5;
  8388. block_4:
  8389. if (eq? x 0)
  8390. goto block_2;
  8391. else
  8392. goto block_3;
  8393. block_5:
  8394. if (eq? x 2)
  8395. goto block_2;
  8396. else
  8397. goto block_3;
  8398. block_2:
  8399. return (+ y 2);
  8400. block_3:
  8401. return (+ y 10);
  8402. \end{lstlisting}
  8403. \end{minipage}
  8404. \end{tabular}
  8405. \fi}
  8406. {\if\edition\pythonEd\pythonColor
  8407. \begin{tabular}{lll}
  8408. \begin{minipage}{0.4\textwidth}
  8409. % tests/if/if_lt_eq.py
  8410. \begin{lstlisting}
  8411. x = input_int()
  8412. y = input_int()
  8413. print(y + 2 \
  8414. if (x == 0 \
  8415. if x < 1 \
  8416. else x == 2) \
  8417. else y + 10)
  8418. \end{lstlisting}
  8419. \end{minipage}
  8420. &
  8421. $\Rightarrow\qquad$
  8422. &
  8423. \begin{minipage}{0.55\textwidth}
  8424. \begin{lstlisting}
  8425. start:
  8426. x = input_int()
  8427. y = input_int()
  8428. if x < 1:
  8429. goto block_6
  8430. else:
  8431. goto block_7
  8432. block_6:
  8433. if x == 0:
  8434. goto block_4
  8435. else:
  8436. goto block_5
  8437. block_7:
  8438. if x == 2:
  8439. goto block_4
  8440. else:
  8441. goto block_5
  8442. block_4:
  8443. tmp.82 = (y + 2)
  8444. goto block_3
  8445. block_5:
  8446. tmp.82 = (y + 10)
  8447. goto block_3
  8448. block_3:
  8449. print(tmp.82)
  8450. return 0
  8451. \end{lstlisting}
  8452. \end{minipage}
  8453. \end{tabular}
  8454. \fi}
  8455. \end{tcolorbox}
  8456. \caption{Translation from \LangIf{} to \LangCIf{}
  8457. via the \code{explicate\_control}.}
  8458. \label{fig:explicate-control-s1-38}
  8459. \end{figure}
  8460. {\if\edition\racketEd
  8461. %
  8462. Recall that in section~\ref{sec:explicate-control-Lvar} we implement
  8463. \code{explicate\_control} for \LangVar{} using two recursive
  8464. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  8465. former function translates expressions in tail position, whereas the
  8466. latter function translates expressions on the right-hand side of a
  8467. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  8468. have a new kind of position to deal with: the predicate position of
  8469. the \key{if}. We need another function, \code{explicate\_pred}, that
  8470. decides how to compile an \key{if} by analyzing its condition. So,
  8471. \code{explicate\_pred} takes an \LangIf{} expression and two
  8472. \LangCIf{} tails for the \emph{then} branch and \emph{else} branch
  8473. and outputs a tail. In the following paragraphs we discuss specific
  8474. cases in the \code{explicate\_tail}, \code{explicate\_assign}, and
  8475. \code{explicate\_pred} functions.
  8476. %
  8477. \fi}
  8478. %
  8479. {\if\edition\pythonEd\pythonColor
  8480. %
  8481. We recommend implementing \code{explicate\_control} using the
  8482. following four auxiliary functions.
  8483. \begin{description}
  8484. \item[\code{explicate\_effect}] generates code for expressions as
  8485. statements, so their result is ignored and only their side effects
  8486. matter.
  8487. \item[\code{explicate\_assign}] generates code for expressions
  8488. on the right-hand side of an assignment.
  8489. \item[\code{explicate\_pred}] generates code for an \code{if}
  8490. expression or statement by analyzing the condition expression.
  8491. \item[\code{explicate\_stmt}] generates code for statements.
  8492. \end{description}
  8493. These four functions should build the dictionary of basic blocks. The
  8494. following auxiliary function \code{create\_block} is used to create a
  8495. new basic block from a list of statements. If the list just contains a
  8496. \code{goto}, then \code{create\_block} returns the list. Otherwise
  8497. \code{create\_block} creates a new basic block and returns a
  8498. \code{goto} to its label.
  8499. \begin{center}
  8500. \begin{minipage}{\textwidth}
  8501. \begin{lstlisting}
  8502. def create_block(stmts, basic_blocks):
  8503. match stmts:
  8504. case [Goto(l)]:
  8505. return stmts
  8506. case _:
  8507. label = label_name(generate_name('block'))
  8508. basic_blocks[label] = stmts
  8509. return [Goto(label)]
  8510. \end{lstlisting}
  8511. \end{minipage}
  8512. \end{center}
  8513. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  8514. \code{explicate\_control} pass.
  8515. The \code{explicate\_effect} function has three parameters: (1) the
  8516. expression to be compiled; (2) the already-compiled code for this
  8517. expression's \emph{continuation}, that is, the list of statements that
  8518. should execute after this expression; and (3) the dictionary of
  8519. generated basic blocks. The \code{explicate\_effect} function returns
  8520. a list of \LangCIf{} statements and it may add to the dictionary of
  8521. basic blocks.
  8522. %
  8523. Let's consider a few of the cases for the expression to be compiled.
  8524. If the expression to be compiled is a constant, then it can be
  8525. discarded because it has no side effects. If it's a \CREAD{}, then it
  8526. has a side effect and should be preserved. So the expression should be
  8527. translated into a statement using the \code{Expr} AST class. If the
  8528. expression to be compiled is an \code{if} expression, we translate the
  8529. two branches using \code{explicate\_effect} and then translate the
  8530. condition expression using \code{explicate\_pred}, which generates
  8531. code for the entire \code{if}.
  8532. The \code{explicate\_assign} function has four parameters: (1) the
  8533. right-hand side of the assignment, (2) the left-hand side of the
  8534. assignment (the variable), (3) the continuation, and (4) the dictionary
  8535. of basic blocks. The \code{explicate\_assign} function returns a list
  8536. of \LangCIf{} statements, and it may add to the dictionary of basic
  8537. blocks.
  8538. When the right-hand side is an \code{if} expression, there is some
  8539. work to do. In particular, the two branches should be translated using
  8540. \code{explicate\_assign}, and the condition expression should be
  8541. translated using \code{explicate\_pred}. Otherwise we can simply
  8542. generate an assignment statement, with the given left- and right-hand
  8543. sides, concatenated with its continuation.
  8544. \begin{figure}[tbp]
  8545. \begin{tcolorbox}[colback=white]
  8546. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  8547. def explicate_effect(e, cont, basic_blocks):
  8548. match e:
  8549. case IfExp(test, body, orelse):
  8550. ...
  8551. case Call(func, args):
  8552. ...
  8553. case Begin(body, result):
  8554. ...
  8555. case _:
  8556. ...
  8557. def explicate_assign(rhs, lhs, cont, basic_blocks):
  8558. match rhs:
  8559. case IfExp(test, body, orelse):
  8560. ...
  8561. case Begin(body, result):
  8562. ...
  8563. case _:
  8564. return [Assign([lhs], rhs)] + cont
  8565. def explicate_pred(cnd, thn, els, basic_blocks):
  8566. match cnd:
  8567. case Compare(left, [op], [right]):
  8568. goto_thn = create_block(thn, basic_blocks)
  8569. goto_els = create_block(els, basic_blocks)
  8570. return [If(cnd, goto_thn, goto_els)]
  8571. case Constant(True):
  8572. return thn;
  8573. case Constant(False):
  8574. return els;
  8575. case UnaryOp(Not(), operand):
  8576. ...
  8577. case IfExp(test, body, orelse):
  8578. ...
  8579. case Begin(body, result):
  8580. ...
  8581. case _:
  8582. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  8583. create_block(els, basic_blocks),
  8584. create_block(thn, basic_blocks))]
  8585. def explicate_stmt(s, cont, basic_blocks):
  8586. match s:
  8587. case Assign([lhs], rhs):
  8588. return explicate_assign(rhs, lhs, cont, basic_blocks)
  8589. case Expr(value):
  8590. return explicate_effect(value, cont, basic_blocks)
  8591. case If(test, body, orelse):
  8592. ...
  8593. def explicate_control(p):
  8594. match p:
  8595. case Module(body):
  8596. new_body = [Return(Constant(0))]
  8597. basic_blocks = {}
  8598. for s in reversed(body):
  8599. new_body = explicate_stmt(s, new_body, basic_blocks)
  8600. basic_blocks[label_name('start')] = new_body
  8601. return CProgram(basic_blocks)
  8602. \end{lstlisting}
  8603. \end{tcolorbox}
  8604. \caption{Skeleton for the \code{explicate\_control} pass.}
  8605. \label{fig:explicate-control-Lif}
  8606. \end{figure}
  8607. \fi}
  8608. {\if\edition\racketEd
  8609. \subsection{Explicate Tail and Assign}
  8610. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  8611. additional cases for Boolean constants and \key{if}. The cases for
  8612. \code{if} should recursively compile the two branches using either
  8613. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  8614. cases should then invoke \code{explicate\_pred} on the condition
  8615. expression, passing in the generated code for the two branches. For
  8616. example, consider the following program with an \code{if} in tail
  8617. position.
  8618. % cond_test_6.rkt
  8619. \begin{lstlisting}
  8620. (let ([x (read)])
  8621. (if (eq? x 0) 42 777))
  8622. \end{lstlisting}
  8623. The two branches are recursively compiled to return statements. We
  8624. then delegate to \code{explicate\_pred}, passing the condition
  8625. \code{(eq? x 0)} and the two return statements. We return to this
  8626. example shortly when we discuss \code{explicate\_pred}.
  8627. Next let us consider a program with an \code{if} on the right-hand
  8628. side of a \code{let}.
  8629. \begin{lstlisting}
  8630. (let ([y (read)])
  8631. (let ([x (if (eq? y 0) 40 777)])
  8632. (+ x 2)))
  8633. \end{lstlisting}
  8634. Note that the body of the inner \code{let} will have already been
  8635. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  8636. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  8637. to recursively process both branches of the \code{if}, and we do not
  8638. want to duplicate code, so we generate the following block using an
  8639. auxiliary function named \code{create\_block}, discussed in the next
  8640. section.
  8641. \begin{lstlisting}
  8642. block_6:
  8643. return (+ x 2)
  8644. \end{lstlisting}
  8645. We then use \code{goto block\_6;} as the \code{cont} argument for
  8646. compiling the branches. So the two branches compile to
  8647. \begin{center}
  8648. \begin{minipage}{0.2\textwidth}
  8649. \begin{lstlisting}
  8650. x = 40;
  8651. goto block_6;
  8652. \end{lstlisting}
  8653. \end{minipage}
  8654. \hspace{0.5in} and \hspace{0.5in}
  8655. \begin{minipage}{0.2\textwidth}
  8656. \begin{lstlisting}
  8657. x = 777;
  8658. goto block_6;
  8659. \end{lstlisting}
  8660. \end{minipage}
  8661. \end{center}
  8662. Finally, we delegate to \code{explicate\_pred}, passing the condition
  8663. \code{(eq? y 0)} and the previously presented code for the branches.
  8664. \subsection{Create Block}
  8665. We recommend implementing the \code{create\_block} auxiliary function
  8666. as follows, using a global variable \code{basic-blocks} to store a
  8667. dictionary that maps labels to $\Tail$ expressions. The main idea is
  8668. that \code{create\_block} generates a new label and then associates
  8669. the given \code{tail} with the new label in the \code{basic-blocks}
  8670. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  8671. new label. However, if the given \code{tail} is already a \code{Goto},
  8672. then there is no need to generate a new label and entry in
  8673. \code{basic-blocks}; we can simply return that \code{Goto}.
  8674. %
  8675. \begin{lstlisting}
  8676. (define (create_block tail)
  8677. (match tail
  8678. [(Goto label) (Goto label)]
  8679. [else
  8680. (let ([label (gensym 'block)])
  8681. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8682. (Goto label))]))
  8683. \end{lstlisting}
  8684. \fi}
  8685. {\if\edition\racketEd
  8686. \subsection{Explicate Predicate}
  8687. The skeleton for the \code{explicate\_pred} function is given in
  8688. figure~\ref{fig:explicate-pred}. It takes three parameters: (1)
  8689. \code{cnd}, the condition expression of the \code{if}; (2) \code{thn},
  8690. the code generated by explicate for the \emph{then} branch; and (3)
  8691. \code{els}, the code generated by explicate for the \emph{else}
  8692. branch. The \code{explicate\_pred} function should match on
  8693. \code{cnd} with a case for every kind of expression that can have type
  8694. \BOOLTY{}.
  8695. \begin{figure}[tbp]
  8696. \begin{tcolorbox}[colback=white]
  8697. \begin{lstlisting}
  8698. (define (explicate_pred cnd thn els)
  8699. (match cnd
  8700. [(Var x) ___]
  8701. [(Let x rhs body) ___]
  8702. [(Prim 'not (list e)) ___]
  8703. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  8704. (IfStmt (Prim op es) (create_block thn)
  8705. (create_block els))]
  8706. [(Bool b) (if b thn els)]
  8707. [(If cnd^ thn^ els^) ___]
  8708. [else (error "explicate_pred unhandled case" cnd)]))
  8709. \end{lstlisting}
  8710. \end{tcolorbox}
  8711. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  8712. \label{fig:explicate-pred}
  8713. \end{figure}
  8714. \fi}
  8715. %
  8716. {\if\edition\pythonEd\pythonColor
  8717. The \code{explicate\_pred} function has four parameters: (1) the
  8718. condition expression, (2) the generated statements for the \emph{then}
  8719. branch, (3) the generated statements for the \emph{else} branch, and
  8720. (4) the dictionary of basic blocks. The \code{explicate\_pred}
  8721. function returns a list of statements, and it adds to the dictionary
  8722. of basic blocks.
  8723. \fi}
  8724. Consider the case for comparison operators. We translate the
  8725. comparison to an \code{if} statement whose branches are \code{goto}
  8726. statements created by applying \code{create\_block} to the \code{thn}
  8727. and \code{els} parameters. Let us illustrate this translation by
  8728. returning to the program with an \code{if} expression in tail
  8729. position, shown next. We invoke \code{explicate\_pred} on its
  8730. condition \racket{\code{(eq? x 0)}}\python{\code{x == 0}}.
  8731. %
  8732. {\if\edition\racketEd
  8733. \begin{lstlisting}
  8734. (let ([x (read)])
  8735. (if (eq? x 0) 42 777))
  8736. \end{lstlisting}
  8737. \fi}
  8738. %
  8739. {\if\edition\pythonEd\pythonColor
  8740. \begin{lstlisting}
  8741. x = input_int()
  8742. 42 if x == 0 else 777
  8743. \end{lstlisting}
  8744. \fi}
  8745. %
  8746. \noindent The two branches \code{42} and \code{777} were already
  8747. compiled to \code{return} statements, from which we now create the
  8748. following blocks:
  8749. %
  8750. \begin{center}
  8751. \begin{minipage}{\textwidth}
  8752. \begin{lstlisting}
  8753. block_1:
  8754. return 42;
  8755. block_2:
  8756. return 777;
  8757. \end{lstlisting}
  8758. \end{minipage}
  8759. \end{center}
  8760. %
  8761. After that, \code{explicate\_pred} compiles the comparison
  8762. \racket{\code{(eq? x 0)}}
  8763. \python{\code{x == 0}}
  8764. to the following \code{if} statement:
  8765. %
  8766. {\if\edition\racketEd
  8767. \begin{center}
  8768. \begin{minipage}{\textwidth}
  8769. \begin{lstlisting}
  8770. if (eq? x 0)
  8771. goto block_1;
  8772. else
  8773. goto block_2;
  8774. \end{lstlisting}
  8775. \end{minipage}
  8776. \end{center}
  8777. \fi}
  8778. {\if\edition\pythonEd\pythonColor
  8779. \begin{center}
  8780. \begin{minipage}{\textwidth}
  8781. \begin{lstlisting}
  8782. if x == 0:
  8783. goto block_1;
  8784. else
  8785. goto block_2;
  8786. \end{lstlisting}
  8787. \end{minipage}
  8788. \end{center}
  8789. \fi}
  8790. Next consider the case for Boolean constants. We perform a kind of
  8791. partial evaluation\index{subject}{partialevaluation@partial evaluation} and output
  8792. either the \code{thn} or \code{els} parameter, depending on whether the
  8793. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  8794. following program:
  8795. {\if\edition\racketEd
  8796. \begin{lstlisting}
  8797. (if #t 42 777)
  8798. \end{lstlisting}
  8799. \fi}
  8800. {\if\edition\pythonEd\pythonColor
  8801. \begin{lstlisting}
  8802. 42 if True else 777
  8803. \end{lstlisting}
  8804. \fi}
  8805. %
  8806. \noindent Again, the two branches \code{42} and \code{777} were
  8807. compiled to \code{return} statements, so \code{explicate\_pred}
  8808. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  8809. code for the \emph{then} branch.
  8810. \begin{lstlisting}
  8811. return 42;
  8812. \end{lstlisting}
  8813. This case demonstrates that we sometimes discard the \code{thn} or
  8814. \code{els} blocks that are input to \code{explicate\_pred}.
  8815. The case for \key{if} expressions in \code{explicate\_pred} is
  8816. particularly illuminating because it deals with the challenges
  8817. discussed previously regarding nested \key{if} expressions
  8818. (figure~\ref{fig:explicate-control-s1-38}). The
  8819. \racket{\lstinline{thn^}}\python{\code{body}} and
  8820. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  8821. \key{if} inherit their context from the current one, that is,
  8822. predicate context. So, you should recursively apply
  8823. \code{explicate\_pred} to the
  8824. \racket{\lstinline{thn^}}\python{\code{body}} and
  8825. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  8826. those recursive calls, pass \code{thn} and \code{els} as the extra
  8827. parameters. Thus, \code{thn} and \code{els} may be used twice, once
  8828. inside each recursive call. As discussed previously, to avoid
  8829. duplicating code, we need to add them to the dictionary of basic
  8830. blocks so that we can instead refer to them by name and execute them
  8831. with a \key{goto}.
  8832. {\if\edition\pythonEd\pythonColor
  8833. %
  8834. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  8835. three parameters: (1) the statement to be compiled, (2) the code for its
  8836. continuation, and (3) the dictionary of basic blocks. The
  8837. \code{explicate\_stmt} returns a list of statements, and it may add to
  8838. the dictionary of basic blocks. The cases for assignment and an
  8839. expression-statement are given in full in the skeleton code: they
  8840. simply dispatch to \code{explicate\_assign} and
  8841. \code{explicate\_effect}, respectively. The case for \code{if}
  8842. statements is not given; it is similar to the case for \code{if}
  8843. expressions.
  8844. The \code{explicate\_control} function itself is given in
  8845. figure~\ref{fig:explicate-control-Lif}. It applies
  8846. \code{explicate\_stmt} to each statement in the program, from back to
  8847. front. Thus, the result so far, stored in \code{new\_body}, can be
  8848. used as the continuation parameter in the next call to
  8849. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  8850. \code{Return} statement. Once complete, we add the \code{new\_body} to
  8851. the dictionary of basic blocks, labeling it the ``start'' block.
  8852. %
  8853. \fi}
  8854. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  8855. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  8856. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  8857. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  8858. %% results from the two recursive calls. We complete the case for
  8859. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  8860. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  8861. %% the result $B_5$.
  8862. %% \[
  8863. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  8864. %% \quad\Rightarrow\quad
  8865. %% B_5
  8866. %% \]
  8867. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  8868. %% inherit the current context, so they are in tail position. Thus, the
  8869. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  8870. %% \code{explicate\_tail}.
  8871. %% %
  8872. %% We need to pass $B_0$ as the accumulator argument for both of these
  8873. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  8874. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  8875. %% to the control-flow graph and obtain a promised goto $G_0$.
  8876. %% %
  8877. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  8878. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  8879. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  8880. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  8881. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  8882. %% \[
  8883. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  8884. %% \]
  8885. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  8886. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  8887. %% should not be confused with the labels for the blocks that appear in
  8888. %% the generated code. We initially construct unlabeled blocks; we only
  8889. %% attach labels to blocks when we add them to the control-flow graph, as
  8890. %% we see in the next case.
  8891. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  8892. %% function. The context of the \key{if} is an assignment to some
  8893. %% variable $x$ and then the control continues to some promised block
  8894. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  8895. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  8896. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  8897. %% branches of the \key{if} inherit the current context, so they are in
  8898. %% assignment positions. Let $B_2$ be the result of applying
  8899. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  8900. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  8901. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  8902. %% the result of applying \code{explicate\_pred} to the predicate
  8903. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  8904. %% translates to the promise $B_4$.
  8905. %% \[
  8906. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  8907. %% \]
  8908. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  8909. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  8910. \code{remove\_complex\_operands} pass and then the
  8911. \code{explicate\_control} pass on the example program. We walk through
  8912. the output program.
  8913. %
  8914. Following the order of evaluation in the output of
  8915. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  8916. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  8917. in the predicate of the inner \key{if}. In the output of
  8918. \code{explicate\_control}, in the
  8919. block labeled \code{start}, two assignment statements are followed by an
  8920. \code{if} statement that branches to \racket{\code{block\_4}}\python{\code{block\_6}}
  8921. or \racket{\code{block\_5}}\python{\code{block\_7}}.
  8922. The blocks associated with those labels contain the
  8923. translations of the code
  8924. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8925. and
  8926. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  8927. respectively. In particular, we start
  8928. \racket{\code{block\_4}}\python{\code{block\_6}}
  8929. with the comparison
  8930. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  8931. and then branch to \racket{\code{block\_2}}\python{\code{block\_4}}
  8932. or \racket{\code{block\_3}}\python{\code{block\_5}},
  8933. which correspond to the two branches of the outer \key{if}, that is,
  8934. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  8935. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  8936. %
  8937. The story for \racket{\code{block\_5}}\python{\code{block\_7}}
  8938. is similar to that of \racket{\code{block\_4}}\python{\code{block\_6}}.
  8939. %
  8940. \python{The \code{block\_3} is the translation of the \code{print} statement.}
  8941. {\if\edition\racketEd
  8942. \subsection{Interactions between Explicate and Shrink}
  8943. The way in which the \code{shrink} pass transforms logical operations
  8944. such as \code{and} and \code{or} can impact the quality of code
  8945. generated by \code{explicate\_control}. For example, consider the
  8946. following program:
  8947. % cond_test_21.rkt, and_eq_input.py
  8948. \begin{lstlisting}
  8949. (if (and (eq? (read) 0) (eq? (read) 1))
  8950. 0
  8951. 42)
  8952. \end{lstlisting}
  8953. The \code{and} operation should transform into something that the
  8954. \code{explicate\_pred} function can analyze and descend through to
  8955. reach the underlying \code{eq?} conditions. Ideally, for this program
  8956. your \code{explicate\_control} pass should generate code similar to
  8957. the following:
  8958. \begin{center}
  8959. \begin{minipage}{\textwidth}
  8960. \begin{lstlisting}
  8961. start:
  8962. tmp1 = (read);
  8963. if (eq? tmp1 0) goto block40;
  8964. else goto block39;
  8965. block40:
  8966. tmp2 = (read);
  8967. if (eq? tmp2 1) goto block38;
  8968. else goto block39;
  8969. block38:
  8970. return 0;
  8971. block39:
  8972. return 42;
  8973. \end{lstlisting}
  8974. \end{minipage}
  8975. \end{center}
  8976. \fi}
  8977. \begin{exercise}\normalfont\normalsize
  8978. \racket{
  8979. Implement the pass \code{explicate\_control} by adding the cases for
  8980. Boolean constants and \key{if} to the \code{explicate\_tail} and
  8981. \code{explicate\_assign} functions. Implement the auxiliary function
  8982. \code{explicate\_pred} for predicate contexts.}
  8983. \python{Implement \code{explicate\_control} pass with its
  8984. four auxiliary functions.}
  8985. %
  8986. Create test cases that exercise all the new cases in the code for
  8987. this pass.
  8988. %
  8989. {\if\edition\racketEd
  8990. Add the following entry to the list of \code{passes} in
  8991. \code{run-tests.rkt}:
  8992. \begin{lstlisting}
  8993. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  8994. \end{lstlisting}
  8995. and then run \code{run-tests.rkt} to test your compiler.
  8996. \fi}
  8997. \end{exercise}
  8998. \section{Select Instructions}
  8999. \label{sec:select-Lif}
  9000. \index{subject}{select instructions}
  9001. The \code{select\_instructions} pass translates \LangCIf{} to
  9002. \LangXIfVar{}.
  9003. %
  9004. \racket{Recall that we implement this pass using three auxiliary
  9005. functions, one for each of the nonterminals $\Atm$, $\Stmt$, and
  9006. $\Tail$ in \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  9007. %
  9008. \racket{For $\Atm$, we have new cases for the Booleans.}
  9009. %
  9010. \python{We begin with the Boolean constants.}
  9011. As previously discussed, we encode them as integers.
  9012. \[
  9013. \TRUE{} \quad\Rightarrow\quad \key{1}
  9014. \qquad\qquad
  9015. \FALSE{} \quad\Rightarrow\quad \key{0}
  9016. \]
  9017. For translating statements, we discuss some of the cases. The
  9018. \code{not} operation can be implemented in terms of \code{xorq}, as we
  9019. discussed at the beginning of this section. Given an assignment, if
  9020. the left-hand-side variable is the same as the argument of \code{not},
  9021. then just the \code{xorq} instruction suffices.
  9022. \[
  9023. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  9024. \quad\Rightarrow\quad
  9025. \key{xorq}~\key{\$}1\key{,}~\Var
  9026. \]
  9027. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  9028. semantics of x86. In the following translation, let $\Arg$ be the
  9029. result of translating $\Atm$ to x86.
  9030. \[
  9031. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  9032. \quad\Rightarrow\quad
  9033. \begin{array}{l}
  9034. \key{movq}~\Arg\key{,}~\Var\\
  9035. \key{xorq}~\key{\$}1\key{,}~\Var
  9036. \end{array}
  9037. \]
  9038. Next consider the cases for equality comparisons. Translating this
  9039. operation to x86 is slightly involved due to the unusual nature of the
  9040. \key{cmpq} instruction that we discussed in section~\ref{sec:x86-if}.
  9041. We recommend translating an assignment with an equality on the
  9042. right-hand side into a sequence of three instructions. \\
  9043. \begin{tabular}{lll}
  9044. \begin{minipage}{0.4\textwidth}
  9045. $\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$
  9046. \end{minipage}
  9047. &
  9048. $\Rightarrow$
  9049. &
  9050. \begin{minipage}{0.4\textwidth}
  9051. \begin{lstlisting}
  9052. cmpq |$\Arg_2$|, |$\Arg_1$|
  9053. sete %al
  9054. movzbq %al, |$\Var$|
  9055. \end{lstlisting}
  9056. \end{minipage}
  9057. \end{tabular} \\
  9058. The translations for the other comparison operators are similar to
  9059. this but use different condition codes for the \code{set} instruction.
  9060. \racket{Regarding the $\Tail$ nonterminal, we have two new cases:
  9061. \key{goto} and \key{if} statements. Both are straightforward to
  9062. translate to x86.}
  9063. %
  9064. A \key{goto} statement becomes a jump instruction.
  9065. \[
  9066. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  9067. \]
  9068. %
  9069. An \key{if} statement becomes a compare instruction followed by a
  9070. conditional jump (for the \emph{then} branch), and the fall-through is to
  9071. a regular jump (for the \emph{else} branch).\\
  9072. \begin{tabular}{lll}
  9073. \begin{minipage}{0.4\textwidth}
  9074. \begin{lstlisting}
  9075. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  9076. goto |$\ell_1$||$\racket{\key{;}}$|
  9077. else|$\python{\key{:}}$|
  9078. goto |$\ell_2$||$\racket{\key{;}}$|
  9079. \end{lstlisting}
  9080. \end{minipage}
  9081. &
  9082. $\Rightarrow$
  9083. &
  9084. \begin{minipage}{0.4\textwidth}
  9085. \begin{lstlisting}
  9086. cmpq |$\Arg_2$|, |$\Arg_1$|
  9087. je |$\ell_1$|
  9088. jmp |$\ell_2$|
  9089. \end{lstlisting}
  9090. \end{minipage}
  9091. \end{tabular} \\
  9092. Again, the translations for the other comparison operators are similar to this
  9093. but use different condition codes for the conditional jump instruction.
  9094. \python{Regarding the \key{return} statement, we recommend treating it
  9095. as an assignment to the \key{rax} register followed by a jump to the
  9096. conclusion of the \code{main} function. (See section~\ref{sec:prelude-conclusion-cond} for more about the conclusion of \code{main}.)}
  9097. \begin{exercise}\normalfont\normalsize
  9098. Expand your \code{select\_instructions} pass to handle the new
  9099. features of the \LangCIf{} language.
  9100. %
  9101. {\if\edition\racketEd
  9102. Add the following entry to the list of \code{passes} in
  9103. \code{run-tests.rkt}
  9104. \begin{lstlisting}
  9105. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  9106. \end{lstlisting}
  9107. \fi}
  9108. %
  9109. Run the script to test your compiler on all the test programs.
  9110. \end{exercise}
  9111. \section{Register Allocation}
  9112. \label{sec:register-allocation-Lif}
  9113. \index{subject}{register allocation}
  9114. The changes required for compiling \LangIf{} affect liveness analysis,
  9115. building the interference graph, and assigning homes, but the graph
  9116. coloring algorithm itself does not change.
  9117. \subsection{Liveness Analysis}
  9118. \label{sec:liveness-analysis-Lif}
  9119. \index{subject}{liveness analysis}
  9120. Recall that for \LangVar{} we implemented liveness analysis for a
  9121. single basic block (section~\ref{sec:liveness-analysis-Lvar}). With
  9122. the addition of \key{if} expressions to \LangIf{},
  9123. \code{explicate\_control} produces many basic blocks.
  9124. %% We recommend that you create a new auxiliary function named
  9125. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  9126. %% control-flow graph.
  9127. The first question is, in what order should we process the basic blocks?
  9128. Recall that to perform liveness analysis on a basic block we need to
  9129. know the live-after set for the last instruction in the block. If a
  9130. basic block has no successors (i.e., contains no jumps to other
  9131. blocks), then it has an empty live-after set and we can immediately
  9132. apply liveness analysis to it. If a basic block has some successors,
  9133. then we need to complete liveness analysis on those blocks
  9134. first. These ordering constraints are the reverse of a
  9135. \emph{topological order}\index{subject}{topological order} on a graph
  9136. representation of the program. In particular, the \emph{control flow
  9137. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  9138. of a program has a node for each basic block and an edge for each jump
  9139. from one block to another. It is straightforward to generate a CFG
  9140. from the dictionary of basic blocks. One then transposes the CFG and
  9141. applies the topological sort algorithm.
  9142. %
  9143. %
  9144. \racket{We recommend using the \code{tsort} and \code{transpose}
  9145. functions of the Racket \code{graph} package to accomplish this.}
  9146. %
  9147. \python{We provide implementations of \code{topological\_sort} and
  9148. \code{transpose} in the file \code{graph.py} of the support code.}
  9149. %
  9150. As an aside, a topological ordering is only guaranteed to exist if the
  9151. graph does not contain any cycles. This is the case for the
  9152. control-flow graphs that we generate from \LangIf{} programs.
  9153. However, in chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  9154. and learn how to handle cycles in the control-flow graph.
  9155. \racket{You need to construct a directed graph to represent the
  9156. control-flow graph. Do not use the \code{directed-graph} of the
  9157. \code{graph} package because that allows at most one edge
  9158. between each pair of vertices, whereas a control-flow graph may have
  9159. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  9160. file in the support code implements a graph representation that
  9161. allows multiple edges between a pair of vertices.}
  9162. {\if\edition\racketEd
  9163. The next question is how to analyze jump instructions. Recall that in
  9164. section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  9165. \code{label->live} that maps each label to the set of live locations
  9166. at the beginning of its block. We use \code{label->live} to determine
  9167. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  9168. that we have many basic blocks, \code{label->live} needs to be updated
  9169. as we process the blocks. In particular, after performing liveness
  9170. analysis on a block, we take the live-before set of its first
  9171. instruction and associate that with the block's label in the
  9172. \code{label->live} alist.
  9173. \fi}
  9174. %
  9175. {\if\edition\pythonEd\pythonColor
  9176. %
  9177. The next question is how to analyze jump instructions. The locations
  9178. that are live before a \code{jmp} should be the locations in
  9179. $L_{\mathsf{before}}$ at the target of the jump. So we recommend
  9180. maintaining a dictionary named \code{live\_before\_block} that maps each
  9181. label to the $L_{\mathsf{before}}$ for the first instruction in its
  9182. block. After performing liveness analysis on each block, we take the
  9183. live-before set of its first instruction and associate that with the
  9184. block's label in the \code{live\_before\_block} dictionary.
  9185. %
  9186. \fi}
  9187. In \LangXIfVar{} we also have the conditional jump
  9188. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  9189. this instruction is particularly interesting because during
  9190. compilation, we do not know which way a conditional jump will go. Thus
  9191. we do not know whether to use the live-before set for the block
  9192. associated with the $\itm{label}$ or the live-before set for the
  9193. following instruction. So we use both, by taking the union of the
  9194. live-before sets from the following instruction and from the mapping
  9195. for $\itm{label}$ in
  9196. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  9197. The auxiliary functions for computing the variables in an
  9198. instruction's argument and for computing the variables read-from ($R$)
  9199. or written-to ($W$) by an instruction need to be updated to handle the
  9200. new kinds of arguments and instructions in \LangXIfVar{}.
  9201. \begin{exercise}\normalfont\normalsize
  9202. {\if\edition\racketEd
  9203. %
  9204. Update the \code{uncover\_live} pass to apply liveness analysis to
  9205. every basic block in the program.
  9206. %
  9207. Add the following entry to the list of \code{passes} in the
  9208. \code{run-tests.rkt} script:
  9209. \begin{lstlisting}
  9210. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  9211. \end{lstlisting}
  9212. \fi}
  9213. {\if\edition\pythonEd\pythonColor
  9214. %
  9215. Update the \code{uncover\_live} function to perform liveness analysis,
  9216. in reverse topological order, on all the basic blocks in the
  9217. program.
  9218. %
  9219. \fi}
  9220. % Check that the live-after sets that you generate for
  9221. % example X matches the following... -Jeremy
  9222. \end{exercise}
  9223. \subsection{Build the Interference Graph}
  9224. \label{sec:build-interference-Lif}
  9225. Many of the new instructions in \LangXIfVar{} can be handled in the
  9226. same way as the instructions in \LangXVar{}.
  9227. % Thus, if your code was
  9228. % already quite general, it will not need to be changed to handle the
  9229. % new instructions. If your code is not general enough, we recommend that
  9230. % you change your code to be more general. For example, you can factor
  9231. % out the computing of the the read and write sets for each kind of
  9232. % instruction into auxiliary functions.
  9233. %
  9234. Some instructions, such as the \key{movzbq} instruction, require special care,
  9235. similar to the \key{movq} instruction. Refer to rule number 1 in
  9236. section~\ref{sec:build-interference}.
  9237. \begin{exercise}\normalfont\normalsize
  9238. Update the \code{build\_interference} pass for \LangXIfVar{}.
  9239. {\if\edition\racketEd
  9240. Add the following entries to the list of \code{passes} in the
  9241. \code{run-tests.rkt} script:
  9242. \begin{lstlisting}
  9243. (list "build_interference" build_interference interp-pseudo-x86-1)
  9244. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  9245. \end{lstlisting}
  9246. \fi}
  9247. % Check that the interference graph that you generate for
  9248. % example X matches the following graph G... -Jeremy
  9249. \end{exercise}
  9250. \section{Patch Instructions}
  9251. The new instructions \key{cmpq} and \key{movzbq} have some special
  9252. restrictions that need to be handled in the \code{patch\_instructions}
  9253. pass.
  9254. %
  9255. The second argument of the \key{cmpq} instruction must not be an
  9256. immediate value (such as an integer). So, if you are comparing two
  9257. immediates, we recommend inserting a \key{movq} instruction to put the
  9258. second argument in \key{rax}. On the other hand, if you implemented
  9259. the partial evaluator (section~\ref{sec:pe-Lvar}), you could
  9260. update it for \LangIf{} and then this situation would not arise.
  9261. %
  9262. As usual, \key{cmpq} may have at most one memory reference.
  9263. %
  9264. The second argument of the \key{movzbq} must be a register.
  9265. \begin{exercise}\normalfont\normalsize
  9266. %
  9267. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  9268. %
  9269. {\if\edition\racketEd
  9270. Add the following entry to the list of \code{passes} in
  9271. \code{run-tests.rkt}, and then run this script to test your compiler.
  9272. \begin{lstlisting}
  9273. (list "patch_instructions" patch_instructions interp-x86-1)
  9274. \end{lstlisting}
  9275. \fi}
  9276. \end{exercise}
  9277. {\if\edition\pythonEd\pythonColor
  9278. \section{Generate Prelude and Conclusion}
  9279. \label{sec:prelude-conclusion-cond}
  9280. The generation of the \code{main} function with its prelude and
  9281. conclusion must change to accommodate how the program now consists of
  9282. one or more basic blocks. After the prelude in \code{main}, jump to
  9283. the \code{start} block. Place the conclusion in a basic block labeled
  9284. with \code{conclusion}.
  9285. \fi}
  9286. Figure~\ref{fig:if-example-x86} shows a simple example program in
  9287. \LangIf{} translated to x86, showing the results of
  9288. \code{explicate\_control}, \code{select\_instructions}, and the final
  9289. x86 assembly.
  9290. \begin{figure}[tbp]
  9291. \begin{tcolorbox}[colback=white]
  9292. {\if\edition\racketEd
  9293. \begin{tabular}{lll}
  9294. \begin{minipage}{0.4\textwidth}
  9295. % cond_test_20.rkt, eq_input.py
  9296. \begin{lstlisting}
  9297. (if (eq? (read) 1) 42 0)
  9298. \end{lstlisting}
  9299. $\Downarrow$
  9300. \begin{lstlisting}
  9301. start:
  9302. tmp7951 = (read);
  9303. if (eq? tmp7951 1)
  9304. goto block7952;
  9305. else
  9306. goto block7953;
  9307. block7952:
  9308. return 42;
  9309. block7953:
  9310. return 0;
  9311. \end{lstlisting}
  9312. $\Downarrow$
  9313. \begin{lstlisting}
  9314. start:
  9315. callq read_int
  9316. movq %rax, tmp7951
  9317. cmpq $1, tmp7951
  9318. je block7952
  9319. jmp block7953
  9320. block7953:
  9321. movq $0, %rax
  9322. jmp conclusion
  9323. block7952:
  9324. movq $42, %rax
  9325. jmp conclusion
  9326. \end{lstlisting}
  9327. \end{minipage}
  9328. &
  9329. $\Rightarrow\qquad$
  9330. \begin{minipage}{0.4\textwidth}
  9331. \begin{lstlisting}
  9332. start:
  9333. callq read_int
  9334. movq %rax, %rcx
  9335. cmpq $1, %rcx
  9336. je block7952
  9337. jmp block7953
  9338. block7953:
  9339. movq $0, %rax
  9340. jmp conclusion
  9341. block7952:
  9342. movq $42, %rax
  9343. jmp conclusion
  9344. .globl main
  9345. main:
  9346. pushq %rbp
  9347. movq %rsp, %rbp
  9348. pushq %r13
  9349. pushq %r12
  9350. pushq %rbx
  9351. pushq %r14
  9352. subq $0, %rsp
  9353. jmp start
  9354. conclusion:
  9355. addq $0, %rsp
  9356. popq %r14
  9357. popq %rbx
  9358. popq %r12
  9359. popq %r13
  9360. popq %rbp
  9361. retq
  9362. \end{lstlisting}
  9363. \end{minipage}
  9364. \end{tabular}
  9365. \fi}
  9366. {\if\edition\pythonEd\pythonColor
  9367. \begin{tabular}{lll}
  9368. \begin{minipage}{0.4\textwidth}
  9369. % cond_test_20.rkt, eq_input.py
  9370. \begin{lstlisting}
  9371. print(42 if input_int() == 1 else 0)
  9372. \end{lstlisting}
  9373. $\Downarrow$
  9374. \begin{lstlisting}
  9375. start:
  9376. tmp_0 = input_int()
  9377. if tmp_0 == 1:
  9378. goto block_3
  9379. else:
  9380. goto block_4
  9381. block_3:
  9382. tmp_1 = 42
  9383. goto block_2
  9384. block_4:
  9385. tmp_1 = 0
  9386. goto block_2
  9387. block_2:
  9388. print(tmp_1)
  9389. return 0
  9390. \end{lstlisting}
  9391. $\Downarrow$
  9392. \begin{lstlisting}
  9393. start:
  9394. callq read_int
  9395. movq %rax, tmp_0
  9396. cmpq 1, tmp_0
  9397. je block_3
  9398. jmp block_4
  9399. block_3:
  9400. movq 42, tmp_1
  9401. jmp block_2
  9402. block_4:
  9403. movq 0, tmp_1
  9404. jmp block_2
  9405. block_2:
  9406. movq tmp_1, %rdi
  9407. callq print_int
  9408. movq 0, %rax
  9409. jmp conclusion
  9410. \end{lstlisting}
  9411. \end{minipage}
  9412. &
  9413. $\Rightarrow\qquad$
  9414. \begin{minipage}{0.4\textwidth}
  9415. \begin{lstlisting}
  9416. .globl main
  9417. main:
  9418. pushq %rbp
  9419. movq %rsp, %rbp
  9420. subq $0, %rsp
  9421. jmp start
  9422. start:
  9423. callq read_int
  9424. movq %rax, %rcx
  9425. cmpq $1, %rcx
  9426. je block_3
  9427. jmp block_4
  9428. block_3:
  9429. movq $42, %rcx
  9430. jmp block_2
  9431. block_4:
  9432. movq $0, %rcx
  9433. jmp block_2
  9434. block_2:
  9435. movq %rcx, %rdi
  9436. callq print_int
  9437. movq $0, %rax
  9438. jmp conclusion
  9439. conclusion:
  9440. addq $0, %rsp
  9441. popq %rbp
  9442. retq
  9443. \end{lstlisting}
  9444. \end{minipage}
  9445. \end{tabular}
  9446. \fi}
  9447. \end{tcolorbox}
  9448. \caption{Example compilation of an \key{if} expression to x86, showing
  9449. the results of \code{explicate\_control},
  9450. \code{select\_instructions}, and the final x86 assembly code. }
  9451. \label{fig:if-example-x86}
  9452. \end{figure}
  9453. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  9454. compilation of \LangIf{}.
  9455. \begin{figure}[htbp]
  9456. \begin{tcolorbox}[colback=white]
  9457. {\if\edition\racketEd
  9458. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9459. \node (Lif-2) at (0,2) {\large \LangIf{}};
  9460. \node (Lif-3) at (3,2) {\large \LangIf{}};
  9461. \node (Lif-4) at (6,2) {\large \LangIf{}};
  9462. \node (Lif-5) at (10,2) {\large \LangIfANF{}};
  9463. \node (C1-1) at (0,0) {\large \LangCIf{}};
  9464. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  9465. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  9466. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  9467. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  9468. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  9469. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  9470. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  9471. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  9472. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-5);
  9473. \path[->,bend left=10] (Lif-5) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C1-1);
  9474. \path[->,bend right=15] (C1-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  9475. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9476. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  9477. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  9478. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  9479. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion } (x86-5);
  9480. \end{tikzpicture}
  9481. \fi}
  9482. {\if\edition\pythonEd\pythonColor
  9483. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  9484. \node (Lif-1) at (0,2) {\large \LangIf{}};
  9485. \node (Lif-2) at (4,2) {\large \LangIf{}};
  9486. \node (Lif-3) at (8,2) {\large \LangIfANF{}};
  9487. \node (C-1) at (0,0) {\large \LangCIf{}};
  9488. \node (x86-1) at (0,-2) {\large \LangXIfVar{}};
  9489. \node (x86-2) at (4,-2) {\large \LangXIfVar{}};
  9490. \node (x86-3) at (8,-2) {\large \LangXIf{}};
  9491. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  9492. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  9493. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lif-3);
  9494. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize \ \ explicate\_control} (C-1);
  9495. \path[->,bend right=15] (C-1) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-1);
  9496. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  9497. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-3);
  9498. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-4);
  9499. \end{tikzpicture}
  9500. \fi}
  9501. \end{tcolorbox}
  9502. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  9503. \label{fig:Lif-passes}
  9504. \end{figure}
  9505. \section{Challenge: Optimize Blocks and Remove Jumps}
  9506. \label{sec:opt-jumps}
  9507. We discuss two challenges that involve optimizing the control-flow of
  9508. the program.
  9509. \subsection{Optimize Blocks}
  9510. The algorithm for \code{explicate\_control} that we discussed in
  9511. section~\ref{sec:explicate-control-Lif} sometimes generates too many
  9512. blocks. It creates a block whenever a continuation \emph{might} get
  9513. used more than once (for example, whenever the \code{cont} parameter
  9514. is passed into two or more recursive calls). However, some
  9515. continuation arguments may not be used at all. Consider the case for
  9516. the constant \TRUE{} in \code{explicate\_pred}, in which we discard
  9517. the \code{els} continuation.
  9518. %
  9519. {\if\edition\racketEd
  9520. The following example program falls into this
  9521. case, and it creates two unused blocks.
  9522. \begin{center}
  9523. \begin{tabular}{lll}
  9524. \begin{minipage}{0.4\textwidth}
  9525. % cond_test_82.rkt
  9526. \begin{lstlisting}
  9527. (let ([y (if #t
  9528. (read)
  9529. (if (eq? (read) 0)
  9530. 777
  9531. (let ([x (read)])
  9532. (+ 1 x))))])
  9533. (+ y 2))
  9534. \end{lstlisting}
  9535. \end{minipage}
  9536. &
  9537. $\Rightarrow$
  9538. &
  9539. \begin{minipage}{0.4\textwidth}
  9540. \begin{lstlisting}
  9541. start:
  9542. y = (read);
  9543. goto block_5;
  9544. block_5:
  9545. return (+ y 2);
  9546. block_6:
  9547. y = 777;
  9548. goto block_5;
  9549. block_7:
  9550. x = (read);
  9551. y = (+ 1 x2);
  9552. goto block_5;
  9553. \end{lstlisting}
  9554. \end{minipage}
  9555. \end{tabular}
  9556. \end{center}
  9557. \fi}
  9558. {\if\edition\pythonEd
  9559. The following example program falls into this
  9560. case, and it creates the unused \code{block\_9}.
  9561. \begin{center}
  9562. \begin{minipage}{0.4\textwidth}
  9563. % if/if_true.py
  9564. \begin{lstlisting}
  9565. if True:
  9566. print(0)
  9567. else:
  9568. x = 1 if False else 2
  9569. print(x)
  9570. \end{lstlisting}
  9571. \end{minipage}
  9572. $\Rightarrow\qquad\qquad$
  9573. \begin{minipage}{0.4\textwidth}
  9574. \begin{lstlisting}
  9575. start:
  9576. print(0)
  9577. goto block_8
  9578. block_9:
  9579. print(x)
  9580. goto block_8
  9581. block_8:
  9582. return 0
  9583. \end{lstlisting}
  9584. \end{minipage}
  9585. \end{center}
  9586. \fi}
  9587. The question is, how can we decide whether to create a basic block?
  9588. \emph{Lazy evaluation}\index{subject}{lazy
  9589. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  9590. delaying the creation of a basic block until the point in time at which
  9591. we know that it will be used.
  9592. %
  9593. {\if\edition\racketEd
  9594. %
  9595. Racket provides support for
  9596. lazy evaluation with the
  9597. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  9598. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  9599. \index{subject}{delay} creates a
  9600. \emph{promise}\index{subject}{promise} in which the evaluation of the
  9601. expressions is postponed. When \key{(force}
  9602. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  9603. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  9604. result of $e_n$ is cached in the promise and returned. If \code{force}
  9605. is applied again to the same promise, then the cached result is
  9606. returned. If \code{force} is applied to an argument that is not a
  9607. promise, \code{force} simply returns the argument.
  9608. %
  9609. \fi}
  9610. %
  9611. {\if\edition\pythonEd\pythonColor
  9612. %
  9613. Although Python does not provide direct support for lazy evaluation,
  9614. it is easy to mimic. We \emph{delay} the evaluation of a computation
  9615. by wrapping it inside a function with no parameters. We \emph{force}
  9616. its evaluation by calling the function. However, we might need to
  9617. force multiple times, so we store the result of calling the
  9618. function instead of recomputing it each time. The following
  9619. \code{Promise} class handles this memoization process.
  9620. \begin{minipage}{0.8\textwidth}
  9621. \begin{lstlisting}
  9622. @dataclass
  9623. class Promise:
  9624. fun : typing.Any
  9625. cache : list[stmt] = None
  9626. def force(self):
  9627. if self.cache is None:
  9628. self.cache = self.fun(); return self.cache
  9629. else:
  9630. return self.cache
  9631. \end{lstlisting}
  9632. \end{minipage}
  9633. \noindent However, in some cases of \code{explicate\_pred}, we return
  9634. a list of statements, and in other cases we return a function that
  9635. computes a list of statements. To uniformly deal with both regular
  9636. data and promises, we define the following \code{force} function that
  9637. checks whether its input is delayed (i.e., whether it is a
  9638. \code{Promise}) and then either (1) forces the promise or (2) returns
  9639. the input.
  9640. %
  9641. \begin{lstlisting}
  9642. def force(promise):
  9643. if isinstance(promise, Promise):
  9644. return promise.force()
  9645. else:
  9646. return promise
  9647. \end{lstlisting}
  9648. %
  9649. \fi}
  9650. We use promises for the input and output of the functions
  9651. \code{explicate\_pred}, \code{explicate\_assign},
  9652. %
  9653. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  9654. %
  9655. So, instead of taking and returning \racket{$\Tail$
  9656. expressions}\python{lists of statements}, they take and return
  9657. promises. Furthermore, when we come to a situation in which a
  9658. continuation might be used more than once, as in the case for
  9659. \code{if} in \code{explicate\_pred}, we create a delayed computation
  9660. that creates a basic block for each continuation (if there is not
  9661. already one) and then returns a \code{goto} statement to that basic
  9662. block. When we come to a situation in which we have a promise but need an
  9663. actual piece of code, for example, to create a larger piece of code with a
  9664. constructor such as \code{Seq}, then insert a call to \code{force}.
  9665. %
  9666. {\if\edition\racketEd
  9667. %
  9668. Also, we must modify the \code{create\_block} function to begin with
  9669. \code{delay} to create a promise. When forced, this promise forces the
  9670. original promise. If that returns a \code{Goto} (because the block was
  9671. already added to \code{basic-blocks}), then we return the
  9672. \code{Goto}. Otherwise, we add the block to \code{basic-blocks} and
  9673. return a \code{Goto} to the new label.
  9674. \begin{center}
  9675. \begin{minipage}{\textwidth}
  9676. \begin{lstlisting}
  9677. (define (create_block tail)
  9678. (delay
  9679. (define t (force tail))
  9680. (match t
  9681. [(Goto label) (Goto label)]
  9682. [else
  9683. (let ([label (gensym 'block)])
  9684. (set! basic-blocks (cons (cons label t) basic-blocks))
  9685. (Goto label))])))
  9686. \end{lstlisting}
  9687. \end{minipage}
  9688. \end{center}
  9689. \fi}
  9690. {\if\edition\pythonEd\pythonColor
  9691. %
  9692. Here is the new version of the \code{create\_block} auxiliary function
  9693. that delays the creation of the new basic block.\\
  9694. \begin{minipage}{\textwidth}
  9695. \begin{lstlisting}
  9696. def create_block(promise, basic_blocks):
  9697. def delay():
  9698. stmts = force(promise)
  9699. match stmts:
  9700. case [Goto(l)]:
  9701. return [Goto(l)]
  9702. case _:
  9703. label = label_name(generate_name('block'))
  9704. basic_blocks[label] = stmts
  9705. return [Goto(label)]
  9706. return Promise(delay)
  9707. \end{lstlisting}
  9708. \end{minipage}
  9709. \fi}
  9710. Figure~\ref{fig:explicate-control-challenge} shows the output of
  9711. improved \code{explicate\_control} on this example.
  9712. \racket{As you can see, the number of basic blocks has been reduced
  9713. from four blocks to two blocks.}%
  9714. \python{As you can see, the number of basic blocks has been reduced
  9715. from three blocks to two blocks.}
  9716. \begin{figure}[tbp]
  9717. \begin{tcolorbox}[colback=white]
  9718. {\if\edition\racketEd
  9719. \begin{tabular}{lll}
  9720. \begin{minipage}{0.45\textwidth}
  9721. % cond_test_82.rkt
  9722. \begin{lstlisting}
  9723. (let ([y (if #t
  9724. (read)
  9725. (if (eq? (read) 0)
  9726. 777
  9727. (let ([x (read)])
  9728. (+ 1 x))))])
  9729. (+ y 2))
  9730. \end{lstlisting}
  9731. \end{minipage}
  9732. &
  9733. $\quad\Rightarrow\quad$
  9734. &
  9735. \begin{minipage}{0.4\textwidth}
  9736. \begin{lstlisting}
  9737. start:
  9738. y = (read);
  9739. goto block_5;
  9740. block_5:
  9741. return (+ y 2);
  9742. \end{lstlisting}
  9743. \end{minipage}
  9744. \end{tabular}
  9745. \fi}
  9746. {\if\edition\pythonEd\pythonColor
  9747. \begin{tabular}{lll}
  9748. \begin{minipage}{0.4\textwidth}
  9749. % if/if_true.py
  9750. \begin{lstlisting}
  9751. if True:
  9752. print(0)
  9753. else:
  9754. x = 1 if False else 2
  9755. print(x)
  9756. \end{lstlisting}
  9757. \end{minipage}
  9758. &
  9759. $\Rightarrow$
  9760. &
  9761. \begin{minipage}{0.55\textwidth}
  9762. \begin{lstlisting}
  9763. start:
  9764. print(0)
  9765. goto block_4
  9766. block_4:
  9767. return 0
  9768. \end{lstlisting}
  9769. \end{minipage}
  9770. \end{tabular}
  9771. \fi}
  9772. \end{tcolorbox}
  9773. \caption{Translation from \LangIf{} to \LangCIf{}
  9774. via the improved \code{explicate\_control}.}
  9775. \label{fig:explicate-control-challenge}
  9776. \end{figure}
  9777. %% Recall that in the example output of \code{explicate\_control} in
  9778. %% figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  9779. %% \code{block60} are trivial blocks, they do nothing but jump to another
  9780. %% block. The first goal of this challenge assignment is to remove those
  9781. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  9782. %% \code{explicate\_control} on the left and shows the result of bypassing
  9783. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  9784. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  9785. %% \code{block55}. The optimized code on the right of
  9786. %% figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  9787. %% \code{then} branch jumping directly to \code{block55}. The story is
  9788. %% similar for the \code{else} branch, as well as for the two branches in
  9789. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  9790. %% have been optimized in this way, there are no longer any jumps to
  9791. %% blocks \code{block57} through \code{block60}, so they can be removed.
  9792. %% \begin{figure}[tbp]
  9793. %% \begin{tabular}{lll}
  9794. %% \begin{minipage}{0.4\textwidth}
  9795. %% \begin{lstlisting}
  9796. %% block62:
  9797. %% tmp54 = (read);
  9798. %% if (eq? tmp54 2) then
  9799. %% goto block59;
  9800. %% else
  9801. %% goto block60;
  9802. %% block61:
  9803. %% tmp53 = (read);
  9804. %% if (eq? tmp53 0) then
  9805. %% goto block57;
  9806. %% else
  9807. %% goto block58;
  9808. %% block60:
  9809. %% goto block56;
  9810. %% block59:
  9811. %% goto block55;
  9812. %% block58:
  9813. %% goto block56;
  9814. %% block57:
  9815. %% goto block55;
  9816. %% block56:
  9817. %% return (+ 700 77);
  9818. %% block55:
  9819. %% return (+ 10 32);
  9820. %% start:
  9821. %% tmp52 = (read);
  9822. %% if (eq? tmp52 1) then
  9823. %% goto block61;
  9824. %% else
  9825. %% goto block62;
  9826. %% \end{lstlisting}
  9827. %% \end{minipage}
  9828. %% &
  9829. %% $\Rightarrow$
  9830. %% &
  9831. %% \begin{minipage}{0.55\textwidth}
  9832. %% \begin{lstlisting}
  9833. %% block62:
  9834. %% tmp54 = (read);
  9835. %% if (eq? tmp54 2) then
  9836. %% goto block55;
  9837. %% else
  9838. %% goto block56;
  9839. %% block61:
  9840. %% tmp53 = (read);
  9841. %% if (eq? tmp53 0) then
  9842. %% goto block55;
  9843. %% else
  9844. %% goto block56;
  9845. %% block56:
  9846. %% return (+ 700 77);
  9847. %% block55:
  9848. %% return (+ 10 32);
  9849. %% start:
  9850. %% tmp52 = (read);
  9851. %% if (eq? tmp52 1) then
  9852. %% goto block61;
  9853. %% else
  9854. %% goto block62;
  9855. %% \end{lstlisting}
  9856. %% \end{minipage}
  9857. %% \end{tabular}
  9858. %% \caption{Optimize jumps by removing trivial blocks.}
  9859. %% \label{fig:optimize-jumps}
  9860. %% \end{figure}
  9861. %% The name of this pass is \code{optimize-jumps}. We recommend
  9862. %% implementing this pass in two phases. The first phrase builds a hash
  9863. %% table that maps labels to possibly improved labels. The second phase
  9864. %% changes the target of each \code{goto} to use the improved label. If
  9865. %% the label is for a trivial block, then the hash table should map the
  9866. %% label to the first non-trivial block that can be reached from this
  9867. %% label by jumping through trivial blocks. If the label is for a
  9868. %% non-trivial block, then the hash table should map the label to itself;
  9869. %% we do not want to change jumps to non-trivial blocks.
  9870. %% The first phase can be accomplished by constructing an empty hash
  9871. %% table, call it \code{short-cut}, and then iterating over the control
  9872. %% flow graph. Each time you encounter a block that is just a \code{goto},
  9873. %% then update the hash table, mapping the block's source to the target
  9874. %% of the \code{goto}. Also, the hash table may already have mapped some
  9875. %% labels to the block's source, to you must iterate through the hash
  9876. %% table and update all of those so that they instead map to the target
  9877. %% of the \code{goto}.
  9878. %% For the second phase, we recommend iterating through the $\Tail$ of
  9879. %% each block in the program, updating the target of every \code{goto}
  9880. %% according to the mapping in \code{short-cut}.
  9881. \begin{exercise}\normalfont\normalsize
  9882. Implement the improvements to the \code{explicate\_control} pass.
  9883. Check that it removes trivial blocks in a few example programs. Then
  9884. check that your compiler still passes all your tests.
  9885. \end{exercise}
  9886. \subsection{Remove Jumps}
  9887. There is an opportunity for removing jumps that is apparent in the
  9888. example of figure~\ref{fig:if-example-x86}. The \code{start} block
  9889. ends with a jump to \racket{\code{block\_5}}\python{\code{block\_4}},
  9890. and there are no other jumps to
  9891. \racket{\code{block\_5}}\python{\code{block\_4}} in the rest of the program.
  9892. In this situation we can avoid the runtime overhead of this jump by merging
  9893. \racket{\code{block\_5}}\python{\code{block\_4}}
  9894. into the preceding block, which in this case is the \code{start} block.
  9895. Figure~\ref{fig:remove-jumps} shows the output of
  9896. \code{allocate\_registers} on the left and the result of this
  9897. optimization on the right.
  9898. \begin{figure}[tbp]
  9899. \begin{tcolorbox}[colback=white]
  9900. {\if\edition\racketEd
  9901. \begin{tabular}{lll}
  9902. \begin{minipage}{0.5\textwidth}
  9903. % cond_test_82.rkt
  9904. \begin{lstlisting}
  9905. start:
  9906. callq read_int
  9907. movq %rax, %rcx
  9908. jmp block_5
  9909. block_5:
  9910. movq %rcx, %rax
  9911. addq $2, %rax
  9912. jmp conclusion
  9913. \end{lstlisting}
  9914. \end{minipage}
  9915. &
  9916. $\Rightarrow\qquad$
  9917. \begin{minipage}{0.4\textwidth}
  9918. \begin{lstlisting}
  9919. start:
  9920. callq read_int
  9921. movq %rax, %rcx
  9922. movq %rcx, %rax
  9923. addq $2, %rax
  9924. jmp conclusion
  9925. \end{lstlisting}
  9926. \end{minipage}
  9927. \end{tabular}
  9928. \fi}
  9929. {\if\edition\pythonEd\pythonColor
  9930. \begin{tabular}{lll}
  9931. \begin{minipage}{0.5\textwidth}
  9932. % cond_test_20.rkt
  9933. \begin{lstlisting}
  9934. start:
  9935. callq read_int
  9936. movq %rax, tmp_0
  9937. cmpq 1, tmp_0
  9938. je block_3
  9939. jmp block_4
  9940. block_3:
  9941. movq 42, tmp_1
  9942. jmp block_2
  9943. block_4:
  9944. movq 0, tmp_1
  9945. jmp block_2
  9946. block_2:
  9947. movq tmp_1, %rdi
  9948. callq print_int
  9949. movq 0, %rax
  9950. jmp conclusion
  9951. \end{lstlisting}
  9952. \end{minipage}
  9953. &
  9954. $\Rightarrow\qquad$
  9955. \begin{minipage}{0.4\textwidth}
  9956. \begin{lstlisting}
  9957. start:
  9958. callq read_int
  9959. movq %rax, tmp_0
  9960. cmpq 1, tmp_0
  9961. je block_3
  9962. movq 0, tmp_1
  9963. jmp block_2
  9964. block_3:
  9965. movq 42, tmp_1
  9966. jmp block_2
  9967. block_2:
  9968. movq tmp_1, %rdi
  9969. callq print_int
  9970. movq 0, %rax
  9971. jmp conclusion
  9972. \end{lstlisting}
  9973. \end{minipage}
  9974. \end{tabular}
  9975. \fi}
  9976. \end{tcolorbox}
  9977. \caption{Merging basic blocks by removing unnecessary jumps.}
  9978. \label{fig:remove-jumps}
  9979. \end{figure}
  9980. \begin{exercise}\normalfont\normalsize
  9981. %
  9982. Implement a pass named \code{remove\_jumps} that merges basic blocks
  9983. into their preceding basic block, when there is only one preceding
  9984. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  9985. %
  9986. {\if\edition\racketEd
  9987. In the \code{run-tests.rkt} script, add the following entry to the
  9988. list of \code{passes} between \code{allocate\_registers}
  9989. and \code{patch\_instructions}:
  9990. \begin{lstlisting}
  9991. (list "remove_jumps" remove_jumps interp-pseudo-x86-1)
  9992. \end{lstlisting}
  9993. \fi}
  9994. %
  9995. Run the script to test your compiler.
  9996. %
  9997. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  9998. blocks on several test programs.
  9999. \end{exercise}
  10000. \section{Further Reading}
  10001. \label{sec:cond-further-reading}
  10002. The algorithm for the \code{explicate\_control} pass is based on the
  10003. \code{expose-basic-blocks} pass in the course notes of
  10004. \citet{Dybvig:2010aa}.
  10005. %
  10006. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  10007. \citet{Appel:2003fk}, and is related to translations into continuation
  10008. passing
  10009. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  10010. %
  10011. The treatment of conditionals in the \code{explicate\_control} pass is
  10012. similar to short-cut Boolean
  10013. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  10014. and the case-of-case transformation~\citep{PeytonJones:1998}.
  10015. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10016. \chapter{Loops and Dataflow Analysis}
  10017. \label{ch:Lwhile}
  10018. \setcounter{footnote}{0}
  10019. % TODO: define R'_8
  10020. % TODO: multi-graph
  10021. {\if\edition\racketEd
  10022. %
  10023. In this chapter we study two features that are the hallmarks of
  10024. imperative programming languages: loops and assignments to local
  10025. variables. The following example demonstrates these new features by
  10026. computing the sum of the first five positive integers:
  10027. % similar to loop_test_1.rkt
  10028. \begin{lstlisting}
  10029. (let ([sum 0])
  10030. (let ([i 5])
  10031. (begin
  10032. (while (> i 0)
  10033. (begin
  10034. (set! sum (+ sum i))
  10035. (set! i (- i 1))))
  10036. sum)))
  10037. \end{lstlisting}
  10038. The \code{while} loop consists of a condition and a
  10039. body.\footnote{The \code{while} loop is not a built-in
  10040. feature of the Racket language, but Racket includes many looping
  10041. constructs and it is straightforward to define \code{while} as a
  10042. macro.} The body is evaluated repeatedly so long as the condition
  10043. remains true.
  10044. %
  10045. The \code{set!} consists of a variable and a right-hand side
  10046. expression. The \code{set!} updates value of the variable to the
  10047. value of the right-hand side.
  10048. %
  10049. The primary purpose of both the \code{while} loop and \code{set!} is
  10050. to cause side effects, so they do not give a meaningful result
  10051. value. Instead, their result is the \code{\#<void>} value. The
  10052. expression \code{(void)} is an explicit way to create the
  10053. \code{\#<void>} value, and it has type \code{Void}. The
  10054. \code{\#<void>} value can be passed around just like other values
  10055. inside an \LangLoop{} program, and it can be compared for equality with
  10056. another \code{\#<void>} value. However, there are no other operations
  10057. specific to the \code{\#<void>} value in \LangLoop{}. In contrast,
  10058. Racket defines the \code{void?} predicate that returns \code{\#t}
  10059. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  10060. %
  10061. \footnote{Racket's \code{Void} type corresponds to what is often
  10062. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  10063. by a single value \code{\#<void>}, which corresponds to \code{unit}
  10064. or \code{()} in the literature~\citep{Pierce:2002hj}.}
  10065. %
  10066. With the addition of side effect-producing features such as
  10067. \code{while} loop and \code{set!}, it is helpful to include a language
  10068. feature for sequencing side effects: the \code{begin} expression. It
  10069. consists of one or more subexpressions that are evaluated
  10070. left to right.
  10071. %
  10072. \fi}
  10073. {\if\edition\pythonEd\pythonColor
  10074. %
  10075. In this chapter we study loops, one of the hallmarks of imperative
  10076. programming languages. The following example demonstrates the
  10077. \code{while} loop by computing the sum of the first five positive
  10078. integers.
  10079. \begin{lstlisting}
  10080. sum = 0
  10081. i = 5
  10082. while i > 0:
  10083. sum = sum + i
  10084. i = i - 1
  10085. print(sum)
  10086. \end{lstlisting}
  10087. The \code{while} loop consists of a condition and a body (a sequence
  10088. of statements). The body is evaluated repeatedly so long as the
  10089. condition remains true.
  10090. %
  10091. \fi}
  10092. \section{The \LangLoop{} Language}
  10093. \newcommand{\LwhileGrammarRacket}{
  10094. \begin{array}{lcl}
  10095. \Type &::=& \key{Void}\\
  10096. \Exp &::=& \CSETBANG{\Var}{\Exp}
  10097. \MID \CBEGIN{\Exp^{*}}{\Exp}
  10098. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  10099. \end{array}
  10100. }
  10101. \newcommand{\LwhileASTRacket}{
  10102. \begin{array}{lcl}
  10103. \Type &::=& \key{Void}\\
  10104. \Exp &::=& \SETBANG{\Var}{\Exp}
  10105. \MID \BEGIN{\Exp^{*}}{\Exp}
  10106. \MID \WHILE{\Exp}{\Exp}
  10107. \MID \VOID{}
  10108. \end{array}
  10109. }
  10110. \newcommand{\LwhileGrammarPython}{
  10111. \begin{array}{rcl}
  10112. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  10113. \end{array}
  10114. }
  10115. \newcommand{\LwhileASTPython}{
  10116. \begin{array}{lcl}
  10117. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10118. \end{array}
  10119. }
  10120. \begin{figure}[tp]
  10121. \centering
  10122. \begin{tcolorbox}[colback=white]
  10123. \small
  10124. {\if\edition\racketEd
  10125. \[
  10126. \begin{array}{l}
  10127. \gray{\LintGrammarRacket{}} \\ \hline
  10128. \gray{\LvarGrammarRacket{}} \\ \hline
  10129. \gray{\LifGrammarRacket{}} \\ \hline
  10130. \LwhileGrammarRacket \\
  10131. \begin{array}{lcl}
  10132. \LangLoopM{} &::=& \Exp
  10133. \end{array}
  10134. \end{array}
  10135. \]
  10136. \fi}
  10137. {\if\edition\pythonEd\pythonColor
  10138. \[
  10139. \begin{array}{l}
  10140. \gray{\LintGrammarPython} \\ \hline
  10141. \gray{\LvarGrammarPython} \\ \hline
  10142. \gray{\LifGrammarPython} \\ \hline
  10143. \LwhileGrammarPython \\
  10144. \begin{array}{rcl}
  10145. \LangLoopM{} &::=& \Stmt^{*}
  10146. \end{array}
  10147. \end{array}
  10148. \]
  10149. \fi}
  10150. \end{tcolorbox}
  10151. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-concrete-syntax}).}
  10152. \label{fig:Lwhile-concrete-syntax}
  10153. \end{figure}
  10154. \begin{figure}[tp]
  10155. \centering
  10156. \begin{tcolorbox}[colback=white]
  10157. \small
  10158. {\if\edition\racketEd
  10159. \[
  10160. \begin{array}{l}
  10161. \gray{\LintOpAST} \\ \hline
  10162. \gray{\LvarASTRacket{}} \\ \hline
  10163. \gray{\LifASTRacket{}} \\ \hline
  10164. \LwhileASTRacket{} \\
  10165. \begin{array}{lcl}
  10166. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10167. \end{array}
  10168. \end{array}
  10169. \]
  10170. \fi}
  10171. {\if\edition\pythonEd\pythonColor
  10172. \[
  10173. \begin{array}{l}
  10174. \gray{\LintASTPython} \\ \hline
  10175. \gray{\LvarASTPython} \\ \hline
  10176. \gray{\LifASTPython} \\ \hline
  10177. \LwhileASTPython \\
  10178. \begin{array}{lcl}
  10179. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10180. \end{array}
  10181. \end{array}
  10182. \]
  10183. \fi}
  10184. \end{tcolorbox}
  10185. \python{
  10186. \index{subject}{While@\texttt{While}}
  10187. }
  10188. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (figure~\ref{fig:Lif-syntax}).}
  10189. \label{fig:Lwhile-syntax}
  10190. \end{figure}
  10191. Figure~\ref{fig:Lwhile-concrete-syntax} shows the definition of the
  10192. concrete syntax of \LangLoop{}, and figure~\ref{fig:Lwhile-syntax}
  10193. shows the definition of its abstract syntax.
  10194. %
  10195. The definitional interpreter for \LangLoop{} is shown in
  10196. figure~\ref{fig:interp-Lwhile}.
  10197. %
  10198. {\if\edition\racketEd
  10199. %
  10200. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  10201. and \code{Void}, and we make changes to the cases for \code{Var} and
  10202. \code{Let} regarding variables. To support assignment to variables and
  10203. to make their lifetimes indefinite (see the second example in
  10204. section~\ref{sec:assignment-scoping}), we box the value that is bound
  10205. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  10206. value.
  10207. %
  10208. Now we discuss the new cases. For \code{SetBang}, we find the
  10209. variable in the environment to obtain a boxed value, and then we change
  10210. it using \code{set-box!} to the result of evaluating the right-hand
  10211. side. The result value of a \code{SetBang} is \code{\#<void>}.
  10212. %
  10213. For the \code{WhileLoop}, we repeatedly (1) evaluate the condition, and
  10214. if the result is true, (2) evaluate the body.
  10215. The result value of a \code{while} loop is also \code{\#<void>}.
  10216. %
  10217. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  10218. subexpressions \itm{es} for their effects and then evaluates
  10219. and returns the result from \itm{body}.
  10220. %
  10221. The $\VOID{}$ expression produces the \code{\#<void>} value.
  10222. %
  10223. \fi}
  10224. {\if\edition\pythonEd\pythonColor
  10225. %
  10226. We add a new case for \code{While} in the \code{interp\_stmts}
  10227. function, in which we repeatedly interpret the \code{body} so long as the
  10228. \code{test} expression remains true.
  10229. %
  10230. \fi}
  10231. \begin{figure}[tbp]
  10232. \begin{tcolorbox}[colback=white]
  10233. {\if\edition\racketEd
  10234. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10235. (define interp-Lwhile-class
  10236. (class interp-Lif-class
  10237. (super-new)
  10238. (define/override ((interp-exp env) e)
  10239. (define recur (interp-exp env))
  10240. (match e
  10241. [(Let x e body)
  10242. (define new-env (dict-set env x (box (recur e))))
  10243. ((interp-exp new-env) body)]
  10244. [(Var x) (unbox (dict-ref env x))]
  10245. [(SetBang x rhs)
  10246. (set-box! (dict-ref env x) (recur rhs))]
  10247. [(WhileLoop cnd body)
  10248. (define (loop)
  10249. (cond [(recur cnd) (recur body) (loop)]
  10250. [else (void)]))
  10251. (loop)]
  10252. [(Begin es body)
  10253. (for ([e es]) (recur e))
  10254. (recur body)]
  10255. [(Void) (void)]
  10256. [else ((super interp-exp env) e)]))
  10257. ))
  10258. (define (interp-Lwhile p)
  10259. (send (new interp-Lwhile-class) interp-program p))
  10260. \end{lstlisting}
  10261. \fi}
  10262. {\if\edition\pythonEd\pythonColor
  10263. \begin{lstlisting}
  10264. class InterpLwhile(InterpLif):
  10265. def interp_stmt(self, s, env, cont):
  10266. match s:
  10267. case While(test, body, []):
  10268. if self.interp_exp(test, env):
  10269. self.interp_stmts(body + [s] + cont, env)
  10270. else:
  10271. return self.interp_stmts(cont, env)
  10272. case _:
  10273. return super().interp_stmt(s, env, cont)
  10274. \end{lstlisting}
  10275. \fi}
  10276. \end{tcolorbox}
  10277. \caption{Interpreter for \LangLoop{}.}
  10278. \label{fig:interp-Lwhile}
  10279. \end{figure}
  10280. The definition of the type checker for \LangLoop{} is shown in
  10281. figure~\ref{fig:type-check-Lwhile}.
  10282. %
  10283. {\if\edition\racketEd
  10284. %
  10285. The type checking of the \code{SetBang} expression requires the type
  10286. of the variable and the right-hand side to agree. The result type is
  10287. \code{Void}. For \code{while}, the condition must be a \BOOLTY{}
  10288. and the result type is \code{Void}. For \code{Begin}, the result type
  10289. is the type of its last subexpression.
  10290. %
  10291. \fi}
  10292. %
  10293. {\if\edition\pythonEd\pythonColor
  10294. %
  10295. A \code{while} loop is well typed if the type of the \code{test}
  10296. expression is \code{bool} and the statements in the \code{body} are
  10297. well typed.
  10298. %
  10299. \fi}
  10300. \begin{figure}[tbp]
  10301. \begin{tcolorbox}[colback=white]
  10302. {\if\edition\racketEd
  10303. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  10304. (define type-check-Lwhile-class
  10305. (class type-check-Lif-class
  10306. (super-new)
  10307. (inherit check-type-equal?)
  10308. (define/override (type-check-exp env)
  10309. (lambda (e)
  10310. (define recur (type-check-exp env))
  10311. (match e
  10312. [(SetBang x rhs)
  10313. (define-values (rhs^ rhsT) (recur rhs))
  10314. (define varT (dict-ref env x))
  10315. (check-type-equal? rhsT varT e)
  10316. (values (SetBang x rhs^) 'Void)]
  10317. [(WhileLoop cnd body)
  10318. (define-values (cnd^ Tc) (recur cnd))
  10319. (check-type-equal? Tc 'Boolean e)
  10320. (define-values (body^ Tbody) ((type-check-exp env) body))
  10321. (values (WhileLoop cnd^ body^) 'Void)]
  10322. [(Begin es body)
  10323. (define-values (es^ ts)
  10324. (for/lists (l1 l2) ([e es]) (recur e)))
  10325. (define-values (body^ Tbody) (recur body))
  10326. (values (Begin es^ body^) Tbody)]
  10327. [else ((super type-check-exp env) e)])))
  10328. ))
  10329. (define (type-check-Lwhile p)
  10330. (send (new type-check-Lwhile-class) type-check-program p))
  10331. \end{lstlisting}
  10332. \fi}
  10333. {\if\edition\pythonEd\pythonColor
  10334. \begin{lstlisting}
  10335. class TypeCheckLwhile(TypeCheckLif):
  10336. def type_check_stmts(self, ss, env):
  10337. if len(ss) == 0:
  10338. return
  10339. match ss[0]:
  10340. case While(test, body, []):
  10341. test_t = self.type_check_exp(test, env)
  10342. check_type_equal(bool, test_t, test)
  10343. body_t = self.type_check_stmts(body, env)
  10344. return self.type_check_stmts(ss[1:], env)
  10345. case _:
  10346. return super().type_check_stmts(ss, env)
  10347. \end{lstlisting}
  10348. \fi}
  10349. \end{tcolorbox}
  10350. \caption{Type checker for the \LangLoop{} language.}
  10351. \label{fig:type-check-Lwhile}
  10352. \end{figure}
  10353. {\if\edition\racketEd
  10354. %
  10355. At first glance, the translation of these language features to x86
  10356. seems straightforward because the \LangCIf{} intermediate language
  10357. already supports all the ingredients that we need: assignment,
  10358. \code{goto}, conditional branching, and sequencing. However,
  10359. complications arise, which we discuss in the next section. After
  10360. that we introduce the changes necessary to the existing passes.
  10361. %
  10362. \fi}
  10363. {\if\edition\pythonEd\pythonColor
  10364. %
  10365. At first glance, the translation of \code{while} loops to x86 seems
  10366. straightforward because the \LangCIf{} intermediate language already
  10367. supports \code{goto} and conditional branching. However, there are
  10368. complications that arise, which we discuss in the next section. After
  10369. that we introduce the changes necessary to the existing passes.
  10370. %
  10371. \fi}
  10372. \section{Cyclic Control Flow and Dataflow Analysis}
  10373. \label{sec:dataflow-analysis}
  10374. Up until this point, the programs generated in
  10375. \code{explicate\_control} were guaranteed to be acyclic. However, each
  10376. \code{while} loop introduces a cycle. Does that matter?
  10377. %
  10378. Indeed, it does. Recall that for register allocation, the compiler
  10379. performs liveness analysis to determine which variables can share the
  10380. same register. To accomplish this, we analyzed the control-flow graph
  10381. in reverse topological order
  10382. (section~\ref{sec:liveness-analysis-Lif}), but topological order is
  10383. well defined only for acyclic graphs.
  10384. Let us return to the example of computing the sum of the first five
  10385. positive integers. Here is the program after instruction
  10386. selection\index{subject}{instruction selection} but before register
  10387. allocation.
  10388. \begin{center}
  10389. {\if\edition\racketEd
  10390. \begin{minipage}{0.45\textwidth}
  10391. \begin{lstlisting}
  10392. (define (main) : Integer
  10393. mainstart:
  10394. movq $0, sum
  10395. movq $5, i
  10396. jmp block5
  10397. block5:
  10398. movq i, tmp3
  10399. cmpq tmp3, $0
  10400. jl block7
  10401. jmp block8
  10402. \end{lstlisting}
  10403. \end{minipage}
  10404. \begin{minipage}{0.45\textwidth}
  10405. \begin{lstlisting}
  10406. block7:
  10407. addq i, sum
  10408. movq $1, tmp4
  10409. negq tmp4
  10410. addq tmp4, i
  10411. jmp block5
  10412. block8:
  10413. movq $27, %rax
  10414. addq sum, %rax
  10415. jmp mainconclusion)
  10416. \end{lstlisting}
  10417. \end{minipage}
  10418. \fi}
  10419. {\if\edition\pythonEd\pythonColor
  10420. \begin{minipage}{0.45\textwidth}
  10421. \begin{lstlisting}
  10422. mainstart:
  10423. movq $0, sum
  10424. movq $5, i
  10425. jmp block5
  10426. block5:
  10427. cmpq $0, i
  10428. jg block7
  10429. jmp block8
  10430. \end{lstlisting}
  10431. \end{minipage}
  10432. \begin{minipage}{0.45\textwidth}
  10433. \begin{lstlisting}
  10434. block7:
  10435. addq i, sum
  10436. subq $1, i
  10437. jmp block5
  10438. block8:
  10439. movq sum, %rdi
  10440. callq print_int
  10441. movq $0, %rax
  10442. jmp mainconclusion
  10443. \end{lstlisting}
  10444. \end{minipage}
  10445. \fi}
  10446. \end{center}
  10447. Recall that liveness analysis works backward, starting at the end
  10448. of each function. For this example we could start with \code{block8}
  10449. because we know what is live at the beginning of the conclusion:
  10450. only \code{rax} and \code{rsp}. So the live-before set
  10451. for \code{block8} is \code{\{rsp,sum\}}.
  10452. %
  10453. Next we might try to analyze \code{block5} or \code{block7}, but
  10454. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  10455. we are stuck.
  10456. The way out of this impasse is to realize that we can compute an
  10457. underapproximation of each live-before set by starting with empty
  10458. live-after sets. By \emph{underapproximation}, we mean that the set
  10459. contains only variables that are live for some execution of the
  10460. program, but the set may be missing some variables that are live.
  10461. Next, the underapproximations for each block can be improved by (1)
  10462. updating the live-after set for each block using the approximate
  10463. live-before sets from the other blocks, and (2) performing liveness
  10464. analysis again on each block. In fact, by iterating this process, the
  10465. underapproximations eventually become the correct solutions!
  10466. %
  10467. This approach of iteratively analyzing a control-flow graph is
  10468. applicable to many static analysis problems and goes by the name
  10469. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  10470. \citet{Kildall:1973vn} in his PhD thesis at the University of
  10471. Washington.
  10472. Let us apply this approach to the previously presented example. We use
  10473. the empty set for the initial live-before set for each block. Let
  10474. $m_0$ be the following mapping from label names to sets of locations
  10475. (variables and registers):
  10476. \begin{center}
  10477. \begin{lstlisting}
  10478. mainstart: {}, block5: {}, block7: {}, block8: {}
  10479. \end{lstlisting}
  10480. \end{center}
  10481. Using the above live-before approximations, we determine the
  10482. live-after for each block and then apply liveness analysis to each
  10483. block. This produces our next approximation $m_1$ of the live-before
  10484. sets.
  10485. \begin{center}
  10486. \begin{lstlisting}
  10487. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  10488. \end{lstlisting}
  10489. \end{center}
  10490. For the second round, the live-after for \code{mainstart} is the
  10491. current live-before for \code{block5}, which is \code{\{i\}}. Therefore
  10492. the liveness analysis for \code{mainstart} computes the empty set. The
  10493. live-after for \code{block5} is the union of the live-before sets for
  10494. \code{block7} and \code{block8}, which is \code{\{i, rsp, sum\}}.
  10495. So the liveness analysis for \code{block5} computes \code{\{i, rsp,
  10496. sum\}}. The live-after for \code{block7} is the live-before for
  10497. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  10498. So the liveness analysis for \code{block7} remains \code{\{i, sum\}}.
  10499. Together these yield the following approximation $m_2$ of
  10500. the live-before sets:
  10501. \begin{center}
  10502. \begin{lstlisting}
  10503. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  10504. \end{lstlisting}
  10505. \end{center}
  10506. In the preceding iteration, only \code{block5} changed, so we can
  10507. limit our attention to \code{mainstart} and \code{block7}, the two
  10508. blocks that jump to \code{block5}. As a result, the live-before sets
  10509. for \code{mainstart} and \code{block7} are updated to include
  10510. \code{rsp}, yielding the following approximation $m_3$:
  10511. \begin{center}
  10512. \begin{lstlisting}
  10513. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  10514. \end{lstlisting}
  10515. \end{center}
  10516. Because \code{block7} changed, we analyze \code{block5} once more, but
  10517. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  10518. our approximations have converged, so $m_3$ is the solution.
  10519. This iteration process is guaranteed to converge to a solution by the
  10520. Kleene fixed-point theorem, a general theorem about functions on
  10521. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  10522. any collection that comes with a partial ordering\index{subject}{partialordering@partial ordering} $\sqsubseteq$ on its
  10523. elements, a least element $\bot$ (pronounced \emph{bottom}), and a
  10524. join operator
  10525. $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{join}\footnote{Technically speaking, we
  10526. will be working with join semilattices.} When two elements are
  10527. ordered $m_i \sqsubseteq m_j$, it means that $m_j$ contains at least
  10528. as much information as $m_i$, so we can think of $m_j$ as a
  10529. better-than-or-equal-to approximation in relation to $m_i$. The
  10530. bottom element $\bot$ represents the complete lack of information,
  10531. that is, the worst approximation. The join operator takes two lattice
  10532. elements and combines their information; that is, it produces the
  10533. least upper bound of the two.\index{subject}{least upper bound}
  10534. A dataflow analysis typically involves two lattices: one lattice to
  10535. represent abstract states and another lattice that aggregates the
  10536. abstract states of all the blocks in the control-flow graph. For
  10537. liveness analysis, an abstract state is a set of locations. We form
  10538. the lattice $L$ by taking its elements to be sets of locations, the
  10539. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  10540. set, and the join operator to be set union.
  10541. %
  10542. We form a second lattice $M$ by taking its elements to be mappings
  10543. from the block labels to sets of locations (elements of $L$). We
  10544. order the mappings point-wise, using the ordering of $L$. So, given any
  10545. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  10546. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  10547. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  10548. to the empty set, $\bot_M(\ell) = \emptyset$.
  10549. We can think of one iteration of liveness analysis applied to the
  10550. whole program as being a function $f$ on the lattice $M$. It takes a
  10551. mapping as input and computes a new mapping.
  10552. \[
  10553. f(m_i) = m_{i+1}
  10554. \]
  10555. Next let us think for a moment about what a final solution $m_s$
  10556. should look like. If we perform liveness analysis using the solution
  10557. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  10558. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  10559. \[
  10560. f(m_s) = m_s
  10561. \]
  10562. Furthermore, the solution should include only locations that are
  10563. forced to be there by performing liveness analysis on the program, so
  10564. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  10565. The Kleene fixed-point theorem states that if a function $f$ is
  10566. monotone (better inputs produce better outputs), then the least fixed
  10567. point of $f$ is the least upper bound of the \emph{ascending Kleene
  10568. chain} that starts at $\bot$ and iterates $f$ as
  10569. follows:\index{subject}{Kleene fixed-point theorem}
  10570. \[
  10571. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10572. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  10573. \]
  10574. When a lattice contains only finitely long ascending chains, then
  10575. every Kleene chain tops out at some fixed point after some number of
  10576. iterations of $f$.
  10577. \[
  10578. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  10579. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  10580. \]
  10581. The liveness analysis is indeed a monotone function and the lattice
  10582. $M$ has finitely long ascending chains because there are only a
  10583. finite number of variables and blocks in the program. Thus we are
  10584. guaranteed that iteratively applying liveness analysis to all blocks
  10585. in the program will eventually produce the least fixed point solution.
  10586. Next let us consider dataflow analysis in general and discuss the
  10587. generic work list algorithm (figure~\ref{fig:generic-dataflow}).
  10588. %
  10589. The algorithm has four parameters: the control-flow graph \code{G}, a
  10590. function \code{transfer} that applies the analysis to one block, and the
  10591. \code{bottom} and \code{join} operators for the lattice of abstract
  10592. states. The \code{analyze\_dataflow} function is formulated as a
  10593. \emph{forward} dataflow analysis; that is, the inputs to the transfer
  10594. function come from the predecessor nodes in the control-flow
  10595. graph. However, liveness analysis is a \emph{backward} dataflow
  10596. analysis, so in that case one must supply the \code{analyze\_dataflow}
  10597. function with the transpose of the control-flow graph.
  10598. The algorithm begins by creating the bottom mapping, represented by a
  10599. hash table. It then pushes all the nodes in the control-flow graph
  10600. onto the work list (a queue). The algorithm repeats the \code{while}
  10601. loop as long as there are items in the work list. In each iteration, a
  10602. node is popped from the work list and processed. The \code{input} for
  10603. the node is computed by taking the join of the abstract states of all
  10604. the predecessor nodes. The \code{transfer} function is then applied to
  10605. obtain the \code{output} abstract state. If the output differs from
  10606. the previous state for this block, the mapping for this block is
  10607. updated and its successor nodes are pushed onto the work list.
  10608. \begin{figure}[tb]
  10609. \begin{tcolorbox}[colback=white]
  10610. {\if\edition\racketEd
  10611. \begin{lstlisting}
  10612. (define (analyze_dataflow G transfer bottom join)
  10613. (define mapping (make-hash))
  10614. (for ([v (in-vertices G)])
  10615. (dict-set! mapping v bottom))
  10616. (define worklist (make-queue))
  10617. (for ([v (in-vertices G)])
  10618. (enqueue! worklist v))
  10619. (define trans-G (transpose G))
  10620. (while (not (queue-empty? worklist))
  10621. (define node (dequeue! worklist))
  10622. (define input (for/fold ([state bottom])
  10623. ([pred (in-neighbors trans-G node)])
  10624. (join state (dict-ref mapping pred))))
  10625. (define output (transfer node input))
  10626. (cond [(not (equal? output (dict-ref mapping node)))
  10627. (dict-set! mapping node output)
  10628. (for ([v (in-neighbors G node)])
  10629. (enqueue! worklist v))]))
  10630. mapping)
  10631. \end{lstlisting}
  10632. \fi}
  10633. {\if\edition\pythonEd\pythonColor
  10634. \begin{lstlisting}
  10635. def analyze_dataflow(G, transfer, bottom, join):
  10636. trans_G = transpose(G)
  10637. mapping = dict((v, bottom) for v in G.vertices())
  10638. worklist = deque(G.vertices)
  10639. while worklist:
  10640. node = worklist.pop()
  10641. inputs = [mapping[v] for v in trans_G.adjacent(node)]
  10642. input = reduce(join, inputs, bottom)
  10643. output = transfer(node, input)
  10644. if output != mapping[node]:
  10645. mapping[node] = output
  10646. worklist.extend(G.adjacent(node))
  10647. \end{lstlisting}
  10648. \fi}
  10649. \end{tcolorbox}
  10650. \caption{Generic work list algorithm for dataflow analysis.}
  10651. \label{fig:generic-dataflow}
  10652. \end{figure}
  10653. {\if\edition\racketEd
  10654. \section{Mutable Variables and Remove Complex Operands}
  10655. There is a subtle interaction between the
  10656. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  10657. and the left-to-right order of evaluation of Racket. Consider the
  10658. following example:
  10659. \begin{lstlisting}
  10660. (let ([x 2])
  10661. (+ x (begin (set! x 40) x)))
  10662. \end{lstlisting}
  10663. The result of this program is \code{42} because the first read from
  10664. \code{x} produces \code{2} and the second produces \code{40}. However,
  10665. if we naively apply the \code{remove\_complex\_operands} pass to this
  10666. example we obtain the following program whose result is \code{80}!
  10667. \begin{lstlisting}
  10668. (let ([x 2])
  10669. (let ([tmp (begin (set! x 40) x)])
  10670. (+ x tmp)))
  10671. \end{lstlisting}
  10672. The problem is that with mutable variables, the ordering between
  10673. reads and writes is important, and the
  10674. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  10675. before the first read of \code{x}.
  10676. We recommend solving this problem by giving special treatment to reads
  10677. from mutable variables, that is, variables that occur on the left-hand
  10678. side of a \code{set!}. We mark each read from a mutable variable with
  10679. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  10680. that the read operation is effectful in that it can produce different
  10681. results at different points in time. Let's apply this idea to the
  10682. following variation that also involves a variable that is not mutated:
  10683. % loop_test_24.rkt
  10684. \begin{lstlisting}
  10685. (let ([x 2])
  10686. (let ([y 0])
  10687. (+ y (+ x (begin (set! x 40) x)))))
  10688. \end{lstlisting}
  10689. We first analyze this program to discover that variable \code{x}
  10690. is mutable but \code{y} is not. We then transform the program as
  10691. follows, replacing each occurrence of \code{x} with \code{(get! x)}:
  10692. \begin{lstlisting}
  10693. (let ([x 2])
  10694. (let ([y 0])
  10695. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  10696. \end{lstlisting}
  10697. Now that we have a clear distinction between reads from mutable and
  10698. immutable variables, we can apply the \code{remove\_complex\_operands}
  10699. pass, where reads from immutable variables are still classified as
  10700. atomic expressions but reads from mutable variables are classified as
  10701. complex. Thus, \code{remove\_complex\_operands} yields the following
  10702. program:\\
  10703. \begin{minipage}{\textwidth}
  10704. \begin{lstlisting}
  10705. (let ([x 2])
  10706. (let ([y 0])
  10707. (let ([t1 x])
  10708. (let ([t2 (begin (set! x 40) x)])
  10709. (let ([t3 (+ t1 t2)])
  10710. (+ y t3))))))
  10711. \end{lstlisting}
  10712. \end{minipage}
  10713. The temporary variable \code{t1} gets the value of \code{x} before the
  10714. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  10715. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  10716. do not generate a temporary variable for the occurrence of \code{y}
  10717. because it's an immutable variable. We want to avoid such unnecessary
  10718. extra temporaries because they would needlessly increase the number of
  10719. variables, making it more likely for some of them to be spilled. The
  10720. result of this program is \code{42}, the same as the result prior to
  10721. \code{remove\_complex\_operands}.
  10722. The approach that we've sketched requires only a small
  10723. modification to \code{remove\_complex\_operands} to handle
  10724. \code{get!}. However, it requires a new pass, called
  10725. \code{uncover-get!}, that we discuss in
  10726. section~\ref{sec:uncover-get-bang}.
  10727. As an aside, this problematic interaction between \code{set!} and the
  10728. pass \code{remove\_complex\_operands} is particular to Racket and not
  10729. its predecessor, the Scheme language. The key difference is that
  10730. Scheme does not specify an order of evaluation for the arguments of an
  10731. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  10732. Scheme is free to choose any ordering: both \code{42} and \code{80}
  10733. would be correct results for the example program. Interestingly,
  10734. Racket is implemented on top of the Chez Scheme
  10735. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  10736. presented in this section (using extra \code{let} bindings to control
  10737. the order of evaluation) is used in the translation from Racket to
  10738. Scheme~\citep{Flatt:2019tb}.
  10739. \fi} % racket
  10740. Having discussed the complications that arise from adding support for
  10741. assignment and loops, we turn to discussing the individual compilation
  10742. passes.
  10743. {\if\edition\racketEd
  10744. \section{Uncover \texttt{get!}}
  10745. \label{sec:uncover-get-bang}
  10746. The goal of this pass is to mark uses of mutable variables so that
  10747. \code{remove\_complex\_operands} can treat them as complex expressions
  10748. and thereby preserve their ordering relative to the side effects in
  10749. other operands. So, the first step is to collect all the mutable
  10750. variables. We recommend creating an auxiliary function for this,
  10751. named \code{collect-set!}, that recursively traverses expressions,
  10752. returning the set of all variables that occur on the left-hand side of a
  10753. \code{set!}. Here's an excerpt of its implementation.
  10754. \begin{center}
  10755. \begin{minipage}{\textwidth}
  10756. \begin{lstlisting}
  10757. (define (collect-set! e)
  10758. (match e
  10759. [(Var x) (set)]
  10760. [(Int n) (set)]
  10761. [(Let x rhs body)
  10762. (set-union (collect-set! rhs) (collect-set! body))]
  10763. [(SetBang var rhs)
  10764. (set-union (set var) (collect-set! rhs))]
  10765. ...))
  10766. \end{lstlisting}
  10767. \end{minipage}
  10768. \end{center}
  10769. By placing this pass after \code{uniquify}, we need not worry about
  10770. variable shadowing, and our logic for \code{Let} can remain simple, as
  10771. in this excerpt.
  10772. The second step is to mark the occurrences of the mutable variables
  10773. with the new \code{GetBang} AST node (\code{get!} in concrete
  10774. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  10775. function, which takes two parameters: the set of mutable variables
  10776. \code{set!-vars} and the expression \code{e} to be processed. The
  10777. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  10778. mutable variable or leaves it alone if not.
  10779. \begin{center}
  10780. \begin{minipage}{\textwidth}
  10781. \begin{lstlisting}
  10782. (define ((uncover-get!-exp set!-vars) e)
  10783. (match e
  10784. [(Var x)
  10785. (if (set-member? set!-vars x)
  10786. (GetBang x)
  10787. (Var x))]
  10788. ...))
  10789. \end{lstlisting}
  10790. \end{minipage}
  10791. \end{center}
  10792. To wrap things up, define the \code{uncover-get!} function for
  10793. processing a whole program, using \code{collect-set!} to obtain the
  10794. set of mutable variables and then \code{uncover-get!-exp} to replace
  10795. their occurrences with \code{GetBang}.
  10796. \fi}
  10797. \section{Remove Complex Operands}
  10798. \label{sec:rco-loop}
  10799. {\if\edition\racketEd
  10800. %
  10801. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  10802. \code{while} are all complex expressions. The subexpressions of
  10803. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  10804. %
  10805. \fi}
  10806. {\if\edition\pythonEd\pythonColor
  10807. %
  10808. The change needed for this pass is to add a case for the \code{while}
  10809. statement. The condition of a loop is allowed to be a complex
  10810. expression, just like the condition of the \code{if} statement.
  10811. %
  10812. \fi}
  10813. %
  10814. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  10815. \LangLoopANF{} of this pass.
  10816. \newcommand{\LwhileMonadASTRacket}{
  10817. \begin{array}{rcl}
  10818. \Atm &::=& \VOID{} \\
  10819. \Exp &::=& \GETBANG{\Var}
  10820. \MID \SETBANG{\Var}{\Exp}
  10821. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  10822. &\MID& \WHILE{\Exp}{\Exp}
  10823. \end{array}
  10824. }
  10825. \newcommand{\LwhileMonadASTPython}{
  10826. \begin{array}{rcl}
  10827. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  10828. \end{array}
  10829. }
  10830. \begin{figure}[tp]
  10831. \centering
  10832. \begin{tcolorbox}[colback=white]
  10833. \small
  10834. {\if\edition\racketEd
  10835. \[
  10836. \begin{array}{l}
  10837. \gray{\LvarMonadASTRacket} \\ \hline
  10838. \gray{\LifMonadASTRacket} \\ \hline
  10839. \LwhileMonadASTRacket \\
  10840. \begin{array}{rcl}
  10841. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  10842. \end{array}
  10843. \end{array}
  10844. \]
  10845. \fi}
  10846. {\if\edition\pythonEd\pythonColor
  10847. \[
  10848. \begin{array}{l}
  10849. \gray{\LvarMonadASTPython} \\ \hline
  10850. \gray{\LifMonadASTPython} \\ \hline
  10851. \LwhileMonadASTPython \\
  10852. \begin{array}{rcl}
  10853. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  10854. \end{array}
  10855. \end{array}
  10856. \]
  10857. \fi}
  10858. \end{tcolorbox}
  10859. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  10860. \label{fig:Lwhile-anf-syntax}
  10861. \end{figure}
  10862. {\if\edition\racketEd
  10863. %
  10864. As usual, when a complex expression appears in a grammar position that
  10865. needs to be atomic, such as the argument of a primitive operator, we
  10866. must introduce a temporary variable and bind it to the complex
  10867. expression. This approach applies, unchanged, to handle the new
  10868. language forms. For example, in the following code there are two
  10869. \code{begin} expressions appearing as arguments to the \code{+}
  10870. operator. The output of \code{rco\_exp} is then shown, in which the
  10871. \code{begin} expressions have been bound to temporary
  10872. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  10873. allowed to have arbitrary expressions in their right-hand side
  10874. expression, so it is fine to place \code{begin} there.
  10875. %
  10876. \begin{center}
  10877. \begin{tabular}{lcl}
  10878. \begin{minipage}{0.4\textwidth}
  10879. \begin{lstlisting}
  10880. (let ([x2 10])
  10881. (let ([y3 0])
  10882. (+ (+ (begin
  10883. (set! y3 (read))
  10884. (get! x2))
  10885. (begin
  10886. (set! x2 (read))
  10887. (get! y3)))
  10888. (get! x2))))
  10889. \end{lstlisting}
  10890. \end{minipage}
  10891. &
  10892. $\Rightarrow$
  10893. &
  10894. \begin{minipage}{0.4\textwidth}
  10895. \begin{lstlisting}
  10896. (let ([x2 10])
  10897. (let ([y3 0])
  10898. (let ([tmp4 (begin
  10899. (set! y3 (read))
  10900. x2)])
  10901. (let ([tmp5 (begin
  10902. (set! x2 (read))
  10903. y3)])
  10904. (let ([tmp6 (+ tmp4 tmp5)])
  10905. (let ([tmp7 x2])
  10906. (+ tmp6 tmp7)))))))
  10907. \end{lstlisting}
  10908. \end{minipage}
  10909. \end{tabular}
  10910. \end{center}
  10911. \fi}
  10912. \section{Explicate Control \racket{and \LangCLoop{}}}
  10913. \label{sec:explicate-loop}
  10914. \newcommand{\CloopASTRacket}{
  10915. \begin{array}{lcl}
  10916. \Atm &::=& \VOID \\
  10917. \Stmt &::=& \READ{}
  10918. \end{array}
  10919. }
  10920. {\if\edition\racketEd
  10921. Recall that in the \code{explicate\_control} pass we define one helper
  10922. function for each kind of position in the program. For the \LangVar{}
  10923. language of integers and variables, we needed assignment and tail
  10924. positions. The \code{if} expressions of \LangIf{} introduced predicate
  10925. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  10926. another kind of position: effect position. Except for the last
  10927. subexpression, the subexpressions inside a \code{begin} are evaluated
  10928. only for their effect. Their result values are discarded. We can
  10929. generate better code by taking this fact into account.
  10930. The output language of \code{explicate\_control} is \LangCLoop{}
  10931. (figure~\ref{fig:c7-syntax}), which is nearly identical to
  10932. \LangCIf{}. The only syntactic differences are the addition of \VOID{}
  10933. and that \code{read} may appear as a statement. The most significant
  10934. difference between the programs generated by \code{explicate\_control}
  10935. in chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  10936. chapter is that the control-flow graphs of the latter may contain
  10937. cycles.
  10938. \begin{figure}[tp]
  10939. \begin{tcolorbox}[colback=white]
  10940. \small
  10941. \[
  10942. \begin{array}{l}
  10943. \gray{\CvarASTRacket} \\ \hline
  10944. \gray{\CifASTRacket} \\ \hline
  10945. \CloopASTRacket \\
  10946. \begin{array}{lcl}
  10947. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  10948. \end{array}
  10949. \end{array}
  10950. \]
  10951. \end{tcolorbox}
  10952. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (figure~\ref{fig:c1-syntax}).}
  10953. \label{fig:c7-syntax}
  10954. \end{figure}
  10955. The new auxiliary function \code{explicate\_effect} takes an
  10956. expression (in an effect position) and the code for its
  10957. continuation. The function returns a $\Tail$ that includes the
  10958. generated code for the input expression followed by the
  10959. continuation. If the expression is obviously pure, that is, never
  10960. causes side effects, then the expression can be removed, so the result
  10961. is just the continuation.
  10962. %
  10963. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  10964. interesting; the generated code is depicted in the following diagram:
  10965. \begin{center}
  10966. \begin{minipage}{0.3\textwidth}
  10967. \xymatrix{
  10968. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  10969. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  10970. & *+[F]{\txt{\itm{cont}}} \\
  10971. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  10972. }
  10973. \end{minipage}
  10974. \end{center}
  10975. We start by creating a fresh label $\itm{loop}$ for the top of the
  10976. loop. Next, recursively process the \itm{body} (in effect position)
  10977. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  10978. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  10979. \itm{body'} as the \emph{then} branch and the continuation block as the
  10980. \emph{else} branch. The result should be added to the dictionary of
  10981. \code{basic-blocks} with the label \itm{loop}. The result for the
  10982. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  10983. The auxiliary functions for tail, assignment, and predicate positions
  10984. need to be updated. The three new language forms, \code{while},
  10985. \code{set!}, and \code{begin}, can appear in assignment and tail
  10986. positions. Only \code{begin} may appear in predicate positions; the
  10987. other two have result type \code{Void}.
  10988. \fi}
  10989. %
  10990. {\if\edition\pythonEd\pythonColor
  10991. %
  10992. The output of this pass is the language \LangCIf{}. No new language
  10993. features are needed in the output, because a \code{while} loop can be
  10994. expressed in terms of \code{goto} and \code{if} statements, which are
  10995. already in \LangCIf{}.
  10996. %
  10997. Add a case for the \code{while} statement to the
  10998. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  10999. the condition expression.
  11000. %
  11001. \fi}
  11002. {\if\edition\racketEd
  11003. \section{Select Instructions}
  11004. \label{sec:select-instructions-loop}
  11005. \index{subject}{select instructions}
  11006. Only two small additions are needed in the \code{select\_instructions}
  11007. pass to handle the changes to \LangCLoop{}. First, to handle the
  11008. addition of \VOID{} we simply translate it to \code{0}. Second,
  11009. \code{read} may appear as a stand-alone statement instead of
  11010. appearing only on the right-hand side of an assignment statement. The code
  11011. generation is nearly identical to the one for assignment; just leave
  11012. off the instruction for moving the result into the left-hand side.
  11013. \fi}
  11014. \section{Register Allocation}
  11015. \label{sec:register-allocation-loop}
  11016. As discussed in section~\ref{sec:dataflow-analysis}, the presence of
  11017. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  11018. which complicates the liveness analysis needed for register
  11019. allocation.
  11020. %
  11021. We recommend using the generic \code{analyze\_dataflow} function that
  11022. was presented at the end of section~\ref{sec:dataflow-analysis} to
  11023. perform liveness analysis, replacing the code in
  11024. \code{uncover\_live} that processed the basic blocks in topological
  11025. order (section~\ref{sec:liveness-analysis-Lif}).
  11026. The \code{analyze\_dataflow} function has the following four parameters.
  11027. \begin{enumerate}
  11028. \item The first parameter \code{G} should be passed the transpose
  11029. of the control-flow graph.
  11030. \item The second parameter \code{transfer} should be passed a function
  11031. that applies liveness analysis to a basic block. It takes two
  11032. parameters: the label for the block to analyze and the live-after
  11033. set for that block. The transfer function should return the
  11034. live-before set for the block.
  11035. %
  11036. \racket{Also, as a side effect, it should update the block's
  11037. $\itm{info}$ with the liveness information for each instruction.}
  11038. %
  11039. \python{Also, as a side effect, it should update the live-before and
  11040. live-after sets for each instruction.}
  11041. %
  11042. To implement the \code{transfer} function, you should be able to
  11043. reuse the code you already have for analyzing basic blocks.
  11044. \item The third and fourth parameters of \code{analyze\_dataflow} are
  11045. \code{bottom} and \code{join} for the lattice of abstract states,
  11046. that is, sets of locations. For liveness analysis, the bottom of the
  11047. lattice is the empty set, and the join operator is set union.
  11048. \end{enumerate}
  11049. \begin{figure}[tp]
  11050. \begin{tcolorbox}[colback=white]
  11051. {\if\edition\racketEd
  11052. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11053. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11054. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  11055. \node (F1-4) at (6,2) {\large \LangLoop{}};
  11056. \node (F1-5) at (9,2) {\large \LangLoop{}};
  11057. \node (F1-6) at (9,0) {\large \LangLoopANF{}};
  11058. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11059. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11060. \node (x86-2-1) at (0,-4) {\large \LangXIfVar{}};
  11061. \node (x86-2-2) at (4,-4) {\large \LangXIfVar{}};
  11062. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11063. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11064. \node (x86-5) at (8,-4) {\large \LangXIf{}};
  11065. \path[->,bend left=15] (Lfun) edge [above] node
  11066. {\ttfamily\footnotesize shrink} (Lfun-2);
  11067. \path[->,bend left=15] (Lfun-2) edge [above] node
  11068. {\ttfamily\footnotesize uniquify} (F1-4);
  11069. \path[->,bend left=15] (F1-4) edge [above] node
  11070. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  11071. \path[->,bend left=15] (F1-5) edge [left] node
  11072. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11073. \path[->,bend left=10] (F1-6) edge [above] node
  11074. {\ttfamily\footnotesize explicate\_control} (C3-2);
  11075. \path[->,bend left=15] (C3-2) edge [right] node
  11076. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11077. \path[->,bend right=15] (x86-2) edge [right] node
  11078. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11079. \path[->,bend right=15] (x86-2-1) edge [below] node
  11080. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  11081. \path[->,bend right=15] (x86-2-2) edge [right] node
  11082. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  11083. \path[->,bend left=15] (x86-3) edge [above] node
  11084. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11085. \path[->,bend left=15] (x86-4) edge [right] node
  11086. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11087. \end{tikzpicture}
  11088. \fi}
  11089. {\if\edition\pythonEd\pythonColor
  11090. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  11091. \node (Lfun) at (0,2) {\large \LangLoop{}};
  11092. \node (Lfun-2) at (4,2) {\large \LangLoop{}};
  11093. \node (F1-6) at (8,2) {\large \LangLoopANF{}};
  11094. \node (C3-2) at (0,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  11095. \node (x86-2) at (0,-2) {\large \LangXIfVar{}};
  11096. \node (x86-3) at (4,-2) {\large \LangXIfVar{}};
  11097. \node (x86-4) at (8,-2) {\large \LangXIf{}};
  11098. \node (x86-5) at (12,-2) {\large \LangXIf{}};
  11099. \path[->,bend left=15] (Lfun) edge [above] node
  11100. {\ttfamily\footnotesize shrink} (Lfun-2);
  11101. \path[->,bend left=15] (Lfun-2) edge [above] node
  11102. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  11103. \path[->,bend left=10] (F1-6) edge [right] node
  11104. {\ttfamily\footnotesize \ \ explicate\_control} (C3-2);
  11105. \path[->,bend right=15] (C3-2) edge [right] node
  11106. {\ttfamily\footnotesize select\_instructions} (x86-2);
  11107. \path[->,bend right=15] (x86-2) edge [below] node
  11108. {\ttfamily\footnotesize assign\_homes} (x86-3);
  11109. \path[->,bend left=15] (x86-3) edge [above] node
  11110. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  11111. \path[->,bend right=15] (x86-4) edge [below] node
  11112. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  11113. \end{tikzpicture}
  11114. \fi}
  11115. \end{tcolorbox}
  11116. \caption{Diagram of the passes for \LangLoop{}.}
  11117. \label{fig:Lwhile-passes}
  11118. \end{figure}
  11119. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  11120. for the compilation of \LangLoop{}.
  11121. % Further Reading: dataflow analysis
  11122. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  11123. \chapter{Tuples and Garbage Collection}
  11124. \label{ch:Lvec}
  11125. \index{subject}{tuple}
  11126. \index{subject}{vector}
  11127. \setcounter{footnote}{0}
  11128. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  11129. %% all the IR grammars are spelled out! \\ --Jeremy}
  11130. %% \margincomment{\scriptsize Be more explicit about how to deal with
  11131. %% the root stack. \\ --Jeremy}
  11132. In this chapter we study the implementation of tuples\racket{, called
  11133. vectors in Racket}. A tuple is a fixed-length sequence of elements
  11134. in which each element may have a different type.
  11135. %
  11136. This language feature is the first to use the computer's
  11137. \emph{heap}\index{subject}{heap}, because the lifetime of a tuple is
  11138. indefinite; that is, a tuple lives forever from the programmer's
  11139. viewpoint. Of course, from an implementer's viewpoint, it is important
  11140. to reclaim the space associated with a tuple when it is no longer
  11141. needed, which is why we also study \emph{garbage collection}
  11142. \index{subject}{garbage collection} techniques in this chapter.
  11143. Section~\ref{sec:r3} introduces the \LangVec{} language, including its
  11144. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  11145. language (chapter~\ref{ch:Lwhile}) with tuples.
  11146. %
  11147. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  11148. copying live tuples back and forth between two halves of the heap. The
  11149. garbage collector requires coordination with the compiler so that it
  11150. can find all the live tuples.
  11151. %
  11152. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  11153. discuss the necessary changes and additions to the compiler passes,
  11154. including a new compiler pass named \code{expose\_allocation}.
  11155. \section{The \LangVec{} Language}
  11156. \label{sec:r3}
  11157. Figure~\ref{fig:Lvec-concrete-syntax} shows the definition of the
  11158. concrete syntax for \LangVec{}, and figure~\ref{fig:Lvec-syntax} shows
  11159. the definition of the abstract syntax.
  11160. %
  11161. \racket{The \LangVec{} language includes the forms \code{vector} for
  11162. creating a tuple, \code{vector-ref} for reading an element of a
  11163. tuple, \code{vector-set!} for writing to an element of a tuple, and
  11164. \code{vector-length} for obtaining the number of elements of a
  11165. tuple.}
  11166. %
  11167. \python{The \LangVec{} language adds (1) tuple creation via a
  11168. comma-separated list of expressions; (2) accessing an element of a
  11169. tuple with the square bracket notation (i.e., \code{t[n]} returns
  11170. the element at index \code{n} of tuple \code{t}); (3) the \code{is}
  11171. comparison operator; and (4) obtaining the number of elements (the
  11172. length) of a tuple. In this chapter, we restrict access indices to
  11173. constant integers.}
  11174. %
  11175. The following program shows an example of the use of tuples. It creates a tuple
  11176. \code{t} containing the elements \code{40},
  11177. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  11178. contains just \code{2}. The element at index $1$ of \code{t} is
  11179. \racket{\code{\#t}}\python{\code{True}}, so the \emph{then} branch of the
  11180. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  11181. to which we add \code{2}, the element at index $0$ of the tuple.
  11182. The result of the program is \code{42}.
  11183. %
  11184. {\if\edition\racketEd
  11185. \begin{lstlisting}
  11186. (let ([t (vector 40 #t (vector 2))])
  11187. (if (vector-ref t 1)
  11188. (+ (vector-ref t 0)
  11189. (vector-ref (vector-ref t 2) 0))
  11190. 44))
  11191. \end{lstlisting}
  11192. \fi}
  11193. {\if\edition\pythonEd\pythonColor
  11194. \begin{lstlisting}
  11195. t = 40, True, (2,)
  11196. print(t[0] + t[2][0] if t[1] else 44)
  11197. \end{lstlisting}
  11198. \fi}
  11199. \newcommand{\LtupGrammarRacket}{
  11200. \begin{array}{lcl}
  11201. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11202. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  11203. \MID \LP\key{vector-length}\;\Exp\RP \\
  11204. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  11205. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  11206. \end{array}
  11207. }
  11208. \newcommand{\LtupASTRacket}{
  11209. \begin{array}{lcl}
  11210. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  11211. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  11212. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  11213. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp}
  11214. % &\MID& \LP\key{HasType}~\Exp~\Type \RP
  11215. \end{array}
  11216. }
  11217. \newcommand{\LtupGrammarPython}{
  11218. \begin{array}{rcl}
  11219. \itm{cmp} &::= & \key{is} \\
  11220. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  11221. \end{array}
  11222. }
  11223. \newcommand{\LtupASTPython}{
  11224. \begin{array}{lcl}
  11225. \itm{cmp} &::= & \code{Is()} \\
  11226. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  11227. &\MID& \LEN{\Exp}
  11228. \end{array}
  11229. }
  11230. \begin{figure}[tbp]
  11231. \centering
  11232. \begin{tcolorbox}[colback=white]
  11233. \small
  11234. {\if\edition\racketEd
  11235. \[
  11236. \begin{array}{l}
  11237. \gray{\LintGrammarRacket{}} \\ \hline
  11238. \gray{\LvarGrammarRacket{}} \\ \hline
  11239. \gray{\LifGrammarRacket{}} \\ \hline
  11240. \gray{\LwhileGrammarRacket} \\ \hline
  11241. \LtupGrammarRacket \\
  11242. \begin{array}{lcl}
  11243. \LangVecM{} &::=& \Exp
  11244. \end{array}
  11245. \end{array}
  11246. \]
  11247. \fi}
  11248. {\if\edition\pythonEd\pythonColor
  11249. \[
  11250. \begin{array}{l}
  11251. \gray{\LintGrammarPython{}} \\ \hline
  11252. \gray{\LvarGrammarPython{}} \\ \hline
  11253. \gray{\LifGrammarPython{}} \\ \hline
  11254. \gray{\LwhileGrammarPython} \\ \hline
  11255. \LtupGrammarPython \\
  11256. \begin{array}{rcl}
  11257. \LangVecM{} &::=& \Stmt^{*}
  11258. \end{array}
  11259. \end{array}
  11260. \]
  11261. \fi}
  11262. \end{tcolorbox}
  11263. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  11264. (figure~\ref{fig:Lwhile-concrete-syntax}).}
  11265. \label{fig:Lvec-concrete-syntax}
  11266. \end{figure}
  11267. \begin{figure}[tp]
  11268. \centering
  11269. \begin{tcolorbox}[colback=white]
  11270. \small
  11271. {\if\edition\racketEd
  11272. \[
  11273. \begin{array}{l}
  11274. \gray{\LintOpAST} \\ \hline
  11275. \gray{\LvarASTRacket{}} \\ \hline
  11276. \gray{\LifASTRacket{}} \\ \hline
  11277. \gray{\LwhileASTRacket{}} \\ \hline
  11278. \LtupASTRacket{} \\
  11279. \begin{array}{lcl}
  11280. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  11281. \end{array}
  11282. \end{array}
  11283. \]
  11284. \fi}
  11285. {\if\edition\pythonEd\pythonColor
  11286. \[
  11287. \begin{array}{l}
  11288. \gray{\LintASTPython} \\ \hline
  11289. \gray{\LvarASTPython} \\ \hline
  11290. \gray{\LifASTPython} \\ \hline
  11291. \gray{\LwhileASTPython} \\ \hline
  11292. \LtupASTPython \\
  11293. \begin{array}{lcl}
  11294. \LangVecM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11295. \end{array}
  11296. \end{array}
  11297. \]
  11298. \fi}
  11299. \end{tcolorbox}
  11300. \caption{The abstract syntax of \LangVec{}.}
  11301. \label{fig:Lvec-syntax}
  11302. \end{figure}
  11303. Tuples raise several interesting new issues. First, variable binding
  11304. performs a shallow copy in dealing with tuples, which means that
  11305. different variables can refer to the same tuple; that is, two
  11306. variables can be \emph{aliases}\index{subject}{alias} for the same
  11307. entity. Consider the following example, in which \code{t1} and
  11308. \code{t2} refer to the same tuple value and \code{t3} refers to a
  11309. different tuple value with equal elements. The result of the
  11310. program is \code{42}.
  11311. \begin{center}
  11312. \begin{minipage}{0.96\textwidth}
  11313. {\if\edition\racketEd
  11314. \begin{lstlisting}
  11315. (let ([t1 (vector 3 7)])
  11316. (let ([t2 t1])
  11317. (let ([t3 (vector 3 7)])
  11318. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  11319. 42
  11320. 0))))
  11321. \end{lstlisting}
  11322. \fi}
  11323. {\if\edition\pythonEd\pythonColor
  11324. \begin{lstlisting}
  11325. t1 = 3, 7
  11326. t2 = t1
  11327. t3 = 3, 7
  11328. print(42 if (t1 is t2) and not (t1 is t3) else 0)
  11329. \end{lstlisting}
  11330. \fi}
  11331. \end{minipage}
  11332. \end{center}
  11333. {\if\edition\racketEd
  11334. Whether two variables are aliased or not affects what happens
  11335. when the underlying tuple is mutated\index{subject}{mutation}.
  11336. Consider the following example in which \code{t1} and \code{t2}
  11337. again refer to the same tuple value.
  11338. \begin{center}
  11339. \begin{minipage}{0.96\textwidth}
  11340. \begin{lstlisting}
  11341. (let ([t1 (vector 3 7)])
  11342. (let ([t2 t1])
  11343. (let ([_ (vector-set! t2 0 42)])
  11344. (vector-ref t1 0))))
  11345. \end{lstlisting}
  11346. \end{minipage}
  11347. \end{center}
  11348. The mutation through \code{t2} is visible in referencing the tuple
  11349. from \code{t1}, so the result of this program is \code{42}.
  11350. \fi}
  11351. The next issue concerns the lifetime of tuples. When does a tuple's
  11352. lifetime end? Notice that \LangVec{} does not include an operation
  11353. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  11354. to any notion of static scoping.
  11355. %
  11356. {\if\edition\racketEd
  11357. %
  11358. For example, the following program returns \code{42} even though the
  11359. variable \code{w} goes out of scope prior to the \code{vector-ref}
  11360. that reads from the vector to which it was bound.
  11361. \begin{center}
  11362. \begin{minipage}{0.96\textwidth}
  11363. \begin{lstlisting}
  11364. (let ([v (vector (vector 44))])
  11365. (let ([x (let ([w (vector 42)])
  11366. (let ([_ (vector-set! v 0 w)])
  11367. 0))])
  11368. (+ x (vector-ref (vector-ref v 0) 0))))
  11369. \end{lstlisting}
  11370. \end{minipage}
  11371. \end{center}
  11372. \fi}
  11373. %
  11374. {\if\edition\pythonEd\pythonColor
  11375. %
  11376. For example, the following program returns \code{42} even though the
  11377. variable \code{x} goes out of scope when the function returns, prior
  11378. to reading the tuple element at index $0$. (We study the compilation
  11379. of functions in chapter~\ref{ch:Lfun}.)
  11380. %
  11381. \begin{center}
  11382. \begin{minipage}{0.96\textwidth}
  11383. \begin{lstlisting}
  11384. def f():
  11385. x = 42, 43
  11386. return x
  11387. t = f()
  11388. print(t[0])
  11389. \end{lstlisting}
  11390. \end{minipage}
  11391. \end{center}
  11392. \fi}
  11393. %
  11394. From the perspective of programmer-observable behavior, tuples live
  11395. forever. However, if they really lived forever then many long-running
  11396. programs would run out of memory. To solve this problem, the
  11397. language's runtime system performs automatic garbage collection.
  11398. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  11399. \LangVec{} language.
  11400. %
  11401. \racket{We define the \code{vector}, \code{vector-ref},
  11402. \code{vector-set!}, and \code{vector-length} operations for
  11403. \LangVec{} in terms of the corresponding operations in Racket. One
  11404. subtle point is that the \code{vector-set!} operation returns the
  11405. \code{\#<void>} value.}
  11406. %
  11407. \python{We represent tuples with Python lists in the interpreter
  11408. because we need to write to them
  11409. (section~\ref{sec:expose-allocation}). (Python tuples are
  11410. immutable.) We define element access, the \code{is} operator, and
  11411. the \code{len} operator for \LangVec{} in terms of the corresponding
  11412. operations in Python.}
  11413. \begin{figure}[tbp]
  11414. \begin{tcolorbox}[colback=white]
  11415. {\if\edition\racketEd
  11416. \begin{lstlisting}
  11417. (define interp-Lvec-class
  11418. (class interp-Lwhile-class
  11419. (super-new)
  11420. (define/override (interp-op op)
  11421. (match op
  11422. ['eq? (lambda (v1 v2)
  11423. (cond [(or (and (fixnum? v1) (fixnum? v2))
  11424. (and (boolean? v1) (boolean? v2))
  11425. (and (vector? v1) (vector? v2))
  11426. (and (void? v1) (void? v2)))
  11427. (eq? v1 v2)]))]
  11428. ['vector vector]
  11429. ['vector-length vector-length]
  11430. ['vector-ref vector-ref]
  11431. ['vector-set! vector-set!]
  11432. [else (super interp-op op)]
  11433. ))
  11434. (define/override ((interp-exp env) e)
  11435. (match e
  11436. [(HasType e t) ((interp-exp env) e)]
  11437. [else ((super interp-exp env) e)]
  11438. ))
  11439. ))
  11440. (define (interp-Lvec p)
  11441. (send (new interp-Lvec-class) interp-program p))
  11442. \end{lstlisting}
  11443. \fi}
  11444. %
  11445. {\if\edition\pythonEd\pythonColor
  11446. \begin{lstlisting}
  11447. class InterpLtup(InterpLwhile):
  11448. def interp_cmp(self, cmp):
  11449. match cmp:
  11450. case Is():
  11451. return lambda x, y: x is y
  11452. case _:
  11453. return super().interp_cmp(cmp)
  11454. def interp_exp(self, e, env):
  11455. match e:
  11456. case Tuple(es, Load()):
  11457. return tuple([self.interp_exp(e, env) for e in es])
  11458. case Subscript(tup, index, Load()):
  11459. t = self.interp_exp(tup, env)
  11460. n = self.interp_exp(index, env)
  11461. return t[n]
  11462. case _:
  11463. return super().interp_exp(e, env)
  11464. \end{lstlisting}
  11465. \fi}
  11466. \end{tcolorbox}
  11467. \caption{Interpreter for the \LangVec{} language.}
  11468. \label{fig:interp-Lvec}
  11469. \end{figure}
  11470. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  11471. \LangVec{}.
  11472. %
  11473. The type of a tuple is a
  11474. \racket{\code{Vector}}\python{\code{TupleType}} type that contains a
  11475. type for each of its elements.
  11476. %
  11477. \racket{To create the s-expression for the \code{Vector} type, we use the
  11478. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  11479. operator} \code{,@} to insert the list \code{t*} without its usual
  11480. start and end parentheses. \index{subject}{unquote-splicing}}
  11481. %
  11482. The type of accessing the ith element of a tuple is the ith element
  11483. type of the tuple's type, if there is one. If not, an error is
  11484. signaled. Note that the index \code{i} is required to be a constant
  11485. integer (and not, for example, a call to
  11486. \racket{\code{read}}\python{\code{input\_int}}) so that the type checker
  11487. can determine the element's type given the tuple type.
  11488. %
  11489. \racket{
  11490. Regarding writing an element to a tuple, the element's type must
  11491. be equal to the ith element type of the tuple's type.
  11492. The result type is \code{Void}.}
  11493. %% When allocating a tuple,
  11494. %% we need to know which elements of the tuple are themselves tuples for
  11495. %% the purposes of garbage collection. We can obtain this information
  11496. %% during type checking. The type checker shown in
  11497. %% figure~\ref{fig:type-check-Lvec} not only computes the type of an
  11498. %% expression; it also
  11499. %% %
  11500. %% \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  11501. %% where $T$ is the tuple's type.
  11502. %
  11503. %records the type of each tuple expression in a new field named \code{has\_type}.
  11504. \begin{figure}[tp]
  11505. \begin{tcolorbox}[colback=white]
  11506. {\if\edition\racketEd
  11507. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11508. (define type-check-Lvec-class
  11509. (class type-check-Lif-class
  11510. (super-new)
  11511. (inherit check-type-equal?)
  11512. (define/override (type-check-exp env)
  11513. (lambda (e)
  11514. (define recur (type-check-exp env))
  11515. (match e
  11516. [(Prim 'vector es)
  11517. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  11518. (define t `(Vector ,@t*))
  11519. (values (Prim 'vector e*) t)]
  11520. [(Prim 'vector-ref (list e1 (Int i)))
  11521. (define-values (e1^ t) (recur e1))
  11522. (match t
  11523. [`(Vector ,ts ...)
  11524. (unless (and (0 . <= . i) (i . < . (length ts)))
  11525. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11526. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  11527. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11528. [(Prim 'vector-set! (list e1 (Int i) elt) )
  11529. (define-values (e-vec t-vec) (recur e1))
  11530. (define-values (e-elt^ t-elt) (recur elt))
  11531. (match t-vec
  11532. [`(Vector ,ts ...)
  11533. (unless (and (0 . <= . i) (i . < . (length ts)))
  11534. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  11535. (check-type-equal? (list-ref ts i) t-elt e)
  11536. (values (Prim 'vector-set! (list e-vec (Int i) e-elt^)) 'Void)]
  11537. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  11538. [(Prim 'vector-length (list e))
  11539. (define-values (e^ t) (recur e))
  11540. (match t
  11541. [`(Vector ,ts ...)
  11542. (values (Prim 'vector-length (list e^)) 'Integer)]
  11543. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  11544. [(Prim 'eq? (list arg1 arg2))
  11545. (define-values (e1 t1) (recur arg1))
  11546. (define-values (e2 t2) (recur arg2))
  11547. (match* (t1 t2)
  11548. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  11549. [(other wise) (check-type-equal? t1 t2 e)])
  11550. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  11551. [else ((super type-check-exp env) e)]
  11552. )))
  11553. ))
  11554. (define (type-check-Lvec p)
  11555. (send (new type-check-Lvec-class) type-check-program p))
  11556. \end{lstlisting}
  11557. \fi}
  11558. {\if\edition\pythonEd\pythonColor
  11559. \begin{lstlisting}
  11560. class TypeCheckLtup(TypeCheckLwhile):
  11561. def type_check_exp(self, e, env):
  11562. match e:
  11563. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  11564. l = self.type_check_exp(left, env)
  11565. r = self.type_check_exp(right, env)
  11566. check_type_equal(l, r, e)
  11567. return bool
  11568. case Tuple(es, Load()):
  11569. ts = [self.type_check_exp(e, env) for e in es]
  11570. e.has_type = TupleType(ts)
  11571. return e.has_type
  11572. case Subscript(tup, Constant(i), Load()):
  11573. tup_ty = self.type_check_exp(tup, env)
  11574. i_ty = self.type_check_exp(Constant(i), env)
  11575. check_type_equal(i_ty, int, i)
  11576. match tup_ty:
  11577. case TupleType(ts):
  11578. return ts[i]
  11579. case _:
  11580. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  11581. case _:
  11582. return super().type_check_exp(e, env)
  11583. \end{lstlisting}
  11584. \fi}
  11585. \end{tcolorbox}
  11586. \caption{Type checker for the \LangVec{} language.}
  11587. \label{fig:type-check-Lvec}
  11588. \end{figure}
  11589. \section{Garbage Collection}
  11590. \label{sec:GC}
  11591. Garbage collection is a runtime technique for reclaiming space on the
  11592. heap that will not be used in the future of the running program. We
  11593. use the term \emph{object}\index{subject}{object} to refer to any
  11594. value that is stored in the heap, which for now includes only
  11595. tuples.%
  11596. %
  11597. \footnote{The term \emph{object} as it is used in the context of
  11598. object-oriented programming has a more specific meaning than the
  11599. way in which we use the term here.}
  11600. %
  11601. Unfortunately, it is impossible to know precisely which objects will
  11602. be accessed in the future and which will not. Instead, garbage
  11603. collectors overapproximate the set of objects that will be accessed by
  11604. identifying which objects can possibly be accessed. The running
  11605. program can directly access objects that are in registers and on the
  11606. procedure call stack. It can also transitively access the elements of
  11607. tuples, starting with a tuple whose address is in a register or on the
  11608. procedure call stack. We define the \emph{root
  11609. set}\index{subject}{root set} to be all the tuple addresses that are
  11610. in registers or on the procedure call stack. We define the \emph{live
  11611. objects}\index{subject}{live objects} to be the objects that are
  11612. reachable from the root set. Garbage collectors reclaim the space that
  11613. is allocated to objects that are no longer live. \index{subject}{allocate}
  11614. That means that some objects may not get reclaimed as soon as they could be,
  11615. but at least
  11616. garbage collectors do not reclaim the space dedicated to objects that
  11617. will be accessed in the future! The programmer can influence which
  11618. objects get reclaimed by causing them to become unreachable.
  11619. So the goal of the garbage collector is twofold:
  11620. \begin{enumerate}
  11621. \item to preserve all the live objects, and
  11622. \item to reclaim the memory of everything else, that is, the \emph{garbage}.
  11623. \end{enumerate}
  11624. \subsection{Two-Space Copying Collector}
  11625. Here we study a relatively simple algorithm for garbage collection
  11626. that is the basis of many state-of-the-art garbage
  11627. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  11628. particular, we describe a two-space copying
  11629. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  11630. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  11631. collector} \index{subject}{two-space copying collector}
  11632. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  11633. what happens in a two-space collector, showing two time steps, prior
  11634. to garbage collection (on the top) and after garbage collection (on
  11635. the bottom). In a two-space collector, the heap is divided into two
  11636. parts named the FromSpace\index{subject}{FromSpace} and the
  11637. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  11638. FromSpace until there is not enough room for the next allocation
  11639. request. At that point, the garbage collector goes to work to make
  11640. room for the next allocation.
  11641. A copying collector makes more room by copying all the live objects
  11642. from the FromSpace into the ToSpace and then performs a sleight of
  11643. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  11644. as the new ToSpace. In the example shown in
  11645. figure~\ref{fig:copying-collector}, the root set consists of three
  11646. pointers, one in a register and two on the stack. All the live
  11647. objects have been copied to the ToSpace (the right-hand side of
  11648. figure~\ref{fig:copying-collector}) in a way that preserves the
  11649. pointer relationships. For example, the pointer in the register still
  11650. points to a tuple that in turn points to two other tuples. There are
  11651. four tuples that are not reachable from the root set and therefore do
  11652. not get copied into the ToSpace.
  11653. The exact situation shown in figure~\ref{fig:copying-collector} cannot be
  11654. created by a well-typed program in \LangVec{} because it contains a
  11655. cycle. However, creating cycles will be possible once we get to
  11656. \LangDyn{} (chapter~\ref{ch:Ldyn}). We design the garbage collector
  11657. to deal with cycles to begin with, so we will not need to revisit this
  11658. issue.
  11659. \begin{figure}[tbp]
  11660. \centering
  11661. \begin{tcolorbox}[colback=white]
  11662. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  11663. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  11664. \\[5ex]
  11665. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  11666. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  11667. \end{tcolorbox}
  11668. \caption{A copying collector in action.}
  11669. \label{fig:copying-collector}
  11670. \end{figure}
  11671. \subsection{Graph Copying via Cheney's Algorithm}
  11672. \label{sec:cheney}
  11673. \index{subject}{Cheney's algorithm}
  11674. Let us take a closer look at the copying of the live objects. The
  11675. allocated\index{subject}{allocate} objects and pointers can be viewed
  11676. as a graph, and we need to copy the part of the graph that is
  11677. reachable from the root set. To make sure that we copy all the
  11678. reachable vertices in the graph, we need an exhaustive graph traversal
  11679. algorithm, such as depth-first search or breadth-first
  11680. search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that such algorithms
  11681. take into account the possibility of cycles by marking which vertices
  11682. have already been visited, so to ensure termination of the
  11683. algorithm. These search algorithms also use a data structure such as a
  11684. stack or queue as a to-do list to keep track of the vertices that need
  11685. to be visited. We use breadth-first search and a trick due to
  11686. \citet{Cheney:1970aa} for simultaneously representing the queue and
  11687. copying tuples into the ToSpace.
  11688. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  11689. copy progresses. The queue is represented by a chunk of contiguous
  11690. memory at the beginning of the ToSpace, using two pointers to track
  11691. the front and the back of the queue, called the \emph{free pointer}
  11692. and the \emph{scan pointer}, respectively. The algorithm starts by
  11693. copying all tuples that are immediately reachable from the root set
  11694. into the ToSpace to form the initial queue. When we copy a tuple, we
  11695. mark the old tuple to indicate that it has been visited. We discuss
  11696. how this marking is accomplished in section~\ref{sec:data-rep-gc}. Note
  11697. that any pointers inside the copied tuples in the queue still point
  11698. back to the FromSpace. Once the initial queue has been created, the
  11699. algorithm enters a loop in which it repeatedly processes the tuple at
  11700. the front of the queue and pops it off the queue. To process a tuple,
  11701. the algorithm copies all the objects that are directly reachable from it
  11702. to the ToSpace, placing them at the back of the queue. The algorithm
  11703. then updates the pointers in the popped tuple so that they point to the
  11704. newly copied objects.
  11705. \begin{figure}[tbp]
  11706. \centering
  11707. \begin{tcolorbox}[colback=white]
  11708. \racket{\includegraphics[width=0.8\textwidth]{figs/cheney}}
  11709. \python{\includegraphics[width=0.8\textwidth]{figs/cheney-python}}
  11710. \end{tcolorbox}
  11711. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  11712. \label{fig:cheney}
  11713. \end{figure}
  11714. As shown in figure~\ref{fig:cheney}, in the first step we copy the
  11715. tuple whose second element is $42$ to the back of the queue. The other
  11716. pointer goes to a tuple that has already been copied, so we do not
  11717. need to copy it again, but we do need to update the pointer to the new
  11718. location. This can be accomplished by storing a \emph{forwarding
  11719. pointer}\index{subject}{forwarding pointer} to the new location in the
  11720. old tuple, when we initially copied the tuple into the
  11721. ToSpace. This completes one step of the algorithm. The algorithm
  11722. continues in this way until the queue is empty; that is, when the scan
  11723. pointer catches up with the free pointer.
  11724. \subsection{Data Representation}
  11725. \label{sec:data-rep-gc}
  11726. The garbage collector places some requirements on the data
  11727. representations used by our compiler. First, the garbage collector
  11728. needs to distinguish between pointers and other kinds of data such as
  11729. integers. The following are three ways to accomplish this:
  11730. \begin{enumerate}
  11731. \item Attach a tag to each object that identifies what type of
  11732. object it is~\citep{McCarthy:1960dz}.
  11733. \item Store different types of objects in different
  11734. regions~\citep{Steele:1977ab}.
  11735. \item Use type information from the program to either (a) generate
  11736. type-specific code for collecting, or (b) generate tables that
  11737. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  11738. \end{enumerate}
  11739. Dynamically typed languages, such as \racket{Racket}\python{Python},
  11740. need to tag objects in any case, so option 1 is a natural choice for those
  11741. languages. However, \LangVec{} is a statically typed language, so it
  11742. would be unfortunate to require tags on every object, especially small
  11743. and pervasive objects like integers and Booleans. Option 3 is the
  11744. best-performing choice for statically typed languages, but it comes with
  11745. a relatively high implementation complexity. To keep this chapter
  11746. within a reasonable scope of complexity, we recommend a combination of options
  11747. 1 and 2, using separate strategies for the stack and the heap.
  11748. Regarding the stack, we recommend using a separate stack for pointers,
  11749. which we call the \emph{root stack}\index{subject}{root stack}
  11750. (aka \emph{shadow stack})~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}.
  11751. That is, when a local variable needs to be spilled and is of type
  11752. \racket{\code{Vector}}\python{\code{TupleType}}, we put it on the
  11753. root stack instead of putting it on the procedure call
  11754. stack. Furthermore, we always spill tuple-typed variables if they are
  11755. live during a call to the collector, thereby ensuring that no pointers
  11756. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  11757. reproduces the example shown in figure~\ref{fig:copying-collector} and
  11758. contrasts it with the data layout using a root stack. The root stack
  11759. contains the two pointers from the regular stack and also the pointer
  11760. in the second register.
  11761. \begin{figure}[tbp]
  11762. \centering
  11763. \begin{tcolorbox}[colback=white]
  11764. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  11765. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  11766. \end{tcolorbox}
  11767. \caption{Maintaining a root stack to facilitate garbage collection.}
  11768. \label{fig:shadow-stack}
  11769. \end{figure}
  11770. The problem of distinguishing between pointers and other kinds of data
  11771. also arises inside each tuple on the heap. We solve this problem by
  11772. attaching a tag, an extra 64 bits, to each
  11773. tuple. Figure~\ref{fig:tuple-rep} shows a zoomed-in view of the tags for
  11774. two of the tuples in the example given in figure~\ref{fig:copying-collector}.
  11775. Note that we have drawn the bits in a big-endian way, from right to left,
  11776. with bit location 0 (the least significant bit) on the far right,
  11777. which corresponds to the direction of the x86 shifting instructions
  11778. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  11779. is dedicated to specifying which elements of the tuple are pointers,
  11780. the part labeled \emph{pointer mask}. Within the pointer mask, a 1 bit
  11781. indicates that there is a pointer, and a 0 bit indicates some other kind of
  11782. data. The pointer mask starts at bit location 7. We limit tuples to a
  11783. maximum size of fifty elements, so we need 50 bits for the pointer
  11784. mask.%
  11785. %
  11786. \footnote{A production-quality compiler would handle
  11787. arbitrarily sized tuples and use a more complex approach.}
  11788. %
  11789. The tag also contains two other pieces of information. The length of
  11790. the tuple (number of elements) is stored in bits at locations 1 through
  11791. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  11792. to be copied to the ToSpace. If the bit has value 1, then this tuple
  11793. has not yet been copied. If the bit has value 0, then the entire tag
  11794. is a forwarding pointer. (The lower 3 bits of a pointer are always
  11795. zero in any case, because our tuples are 8-byte aligned.)
  11796. \begin{figure}[tbp]
  11797. \centering
  11798. \begin{tcolorbox}[colback=white]
  11799. \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  11800. \end{tcolorbox}
  11801. \caption{Representation of tuples in the heap.}
  11802. \label{fig:tuple-rep}
  11803. \end{figure}
  11804. \subsection{Implementation of the Garbage Collector}
  11805. \label{sec:organize-gz}
  11806. \index{subject}{prelude}
  11807. An implementation of the copying collector is provided in the
  11808. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  11809. interface to the garbage collector that is used by the compiler. The
  11810. \code{initialize} function creates the FromSpace, ToSpace, and root
  11811. stack and should be called in the prelude of the \code{main}
  11812. function. The arguments of \code{initialize} are the root stack size
  11813. and the heap size. Both need to be multiples of sixty-four, and $16,384$ is a
  11814. good choice for both. The \code{initialize} function puts the address
  11815. of the beginning of the FromSpace into the global variable
  11816. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  11817. the address that is one past the last element of the FromSpace. We use
  11818. half-open intervals to represent chunks of
  11819. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  11820. points to the first element of the root stack.
  11821. As long as there is room left in the FromSpace, your generated code
  11822. can allocate\index{subject}{allocate} tuples simply by moving the
  11823. \code{free\_ptr} forward.
  11824. %
  11825. The amount of room left in the FromSpace is the difference between the
  11826. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  11827. function should be called when there is not enough room left in the
  11828. FromSpace for the next allocation. The \code{collect} function takes
  11829. a pointer to the current top of the root stack (one past the last item
  11830. that was pushed) and the number of bytes that need to be
  11831. allocated. The \code{collect} function performs the copying collection
  11832. and leaves the heap in a state such that there is enough room for the
  11833. next allocation.
  11834. \begin{figure}[tbp]
  11835. \begin{tcolorbox}[colback=white]
  11836. \begin{lstlisting}
  11837. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  11838. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  11839. int64_t* free_ptr;
  11840. int64_t* fromspace_begin;
  11841. int64_t* fromspace_end;
  11842. int64_t** rootstack_begin;
  11843. \end{lstlisting}
  11844. \end{tcolorbox}
  11845. \caption{The compiler's interface to the garbage collector.}
  11846. \label{fig:gc-header}
  11847. \end{figure}
  11848. %% \begin{exercise}
  11849. %% In the file \code{runtime.c} you will find the implementation of
  11850. %% \code{initialize} and a partial implementation of \code{collect}.
  11851. %% The \code{collect} function calls another function, \code{cheney},
  11852. %% to perform the actual copy, and that function is left to the reader
  11853. %% to implement. The following is the prototype for \code{cheney}.
  11854. %% \begin{lstlisting}
  11855. %% static void cheney(int64_t** rootstack_ptr);
  11856. %% \end{lstlisting}
  11857. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  11858. %% rootstack (which is an array of pointers). The \code{cheney} function
  11859. %% also communicates with \code{collect} through the global
  11860. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  11861. %% mentioned in figure~\ref{fig:gc-header} as well as the pointers for
  11862. %% the ToSpace:
  11863. %% \begin{lstlisting}
  11864. %% static int64_t* tospace_begin;
  11865. %% static int64_t* tospace_end;
  11866. %% \end{lstlisting}
  11867. %% The job of the \code{cheney} function is to copy all the live
  11868. %% objects (reachable from the root stack) into the ToSpace, update
  11869. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  11870. %% update the root stack so that it points to the objects in the
  11871. %% ToSpace, and finally to swap the global pointers for the FromSpace
  11872. %% and ToSpace.
  11873. %% \end{exercise}
  11874. The introduction of garbage collection has a nontrivial impact on our
  11875. compiler passes. We introduce a new compiler pass named
  11876. \code{expose\_allocation} that elaborates the code for allocating
  11877. tuples. We also make significant changes to
  11878. \code{select\_instructions}, \code{build\_interference},
  11879. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  11880. make minor changes in several more passes.
  11881. The following program serves as our running example. It creates
  11882. two tuples, one nested inside the other. Both tuples have length
  11883. one. The program accesses the element in the inner tuple.
  11884. % tests/vectors_test_17.rkt
  11885. {\if\edition\racketEd
  11886. \begin{lstlisting}
  11887. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  11888. \end{lstlisting}
  11889. \fi}
  11890. % tests/tuple/get_get.py
  11891. {\if\edition\pythonEd\pythonColor
  11892. \begin{lstlisting}
  11893. v1 = (42,)
  11894. v2 = (v1,)
  11895. print(v2[0][0])
  11896. \end{lstlisting}
  11897. \fi}
  11898. %% {\if\edition\racketEd
  11899. %% \section{Shrink}
  11900. %% \label{sec:shrink-Lvec}
  11901. %% Recall that the \code{shrink} pass translates the primitives operators
  11902. %% into a smaller set of primitives.
  11903. %% %
  11904. %% This pass comes after type checking, and the type checker adds a
  11905. %% \code{HasType} AST node around each \code{vector} AST node, so you'll
  11906. %% need to add a case for \code{HasType} to the \code{shrink} pass.
  11907. %% \fi}
  11908. \section{Expose Allocation}
  11909. \label{sec:expose-allocation}
  11910. The pass \code{expose\_allocation} lowers tuple creation into making a
  11911. conditional call to the collector followed by allocating the
  11912. appropriate amount of memory and initializing it. We choose to place
  11913. the \code{expose\_allocation} pass before
  11914. \code{remove\_complex\_operands} because it generates
  11915. code that contains complex operands.
  11916. The output of \code{expose\_allocation} is a language \LangAlloc{}
  11917. that replaces tuple creation with new lower-level forms that we use in the
  11918. translation of tuple creation.
  11919. %
  11920. {\if\edition\racketEd
  11921. \[
  11922. \begin{array}{lcl}
  11923. \Exp &::=& (\key{collect} \,\itm{int})
  11924. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  11925. \MID (\key{global-value} \,\itm{name})
  11926. \end{array}
  11927. \]
  11928. \fi}
  11929. {\if\edition\pythonEd\pythonColor
  11930. \[
  11931. \begin{array}{lcl}
  11932. \Exp &::=& \cdots\\
  11933. &\MID& \key{collect}(\itm{int})
  11934. \MID \key{allocate}(\itm{int},\itm{type})
  11935. \MID \key{global\_value}(\itm{name}) \\
  11936. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  11937. \end{array}
  11938. \]
  11939. \fi}
  11940. %
  11941. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  11942. make sure that there are $n$ bytes ready to be allocated. During
  11943. instruction selection\index{subject}{instruction selection},
  11944. the \CCOLLECT{$n$} form will become a call to
  11945. the \code{collect} function in \code{runtime.c}.
  11946. %
  11947. The \CALLOCATE{$n$}{$\itm{type}$} form obtains memory for $n$ elements (and
  11948. space at the front for the 64-bit tag), but the elements are not
  11949. initialized. \index{subject}{allocate} The $\itm{type}$ parameter is the type
  11950. of the tuple:
  11951. %
  11952. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  11953. %
  11954. where $\Type_i$ is the type of the $i$th element.
  11955. %
  11956. The \CGLOBALVALUE{\itm{name}} form reads the value of a global
  11957. variable, such as \code{free\_ptr}.
  11958. \racket{
  11959. The type information that you need for \CALLOCATE{$n$}{$\itm{type}$}
  11960. can be obtained by running the
  11961. \code{type-check-Lvec-has-type} type checker immediately before the
  11962. \code{expose\_allocation} pass. This version of the type checker
  11963. places a special AST node of the form $(\key{HasType}~e~\itm{type})$
  11964. around each tuple creation. The concrete syntax
  11965. for \code{HasType} is \code{has-type}.}
  11966. The following shows the transformation of tuple creation into (1) a
  11967. sequence of temporary variable bindings for the initializing
  11968. expressions, (2) a conditional call to \code{collect}, (3) a call to
  11969. \code{allocate}, and (4) the initialization of the tuple. The
  11970. \itm{len} placeholder refers to the length of the tuple, and
  11971. \itm{bytes} is the total number of bytes that need to be allocated for
  11972. the tuple, which is 8 for the tag plus \itm{len} times 8.
  11973. %
  11974. \python{The \itm{type} needed for the second argument of the
  11975. \code{allocate} form can be obtained from the \code{has\_type} field
  11976. of the tuple AST node, which is stored there by running the type
  11977. checker for \LangVec{} immediately before this pass.}
  11978. %
  11979. \begin{center}
  11980. \begin{minipage}{\textwidth}
  11981. {\if\edition\racketEd
  11982. \begin{lstlisting}
  11983. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  11984. |$\Longrightarrow$|
  11985. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  11986. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  11987. (global-value fromspace_end))
  11988. (void)
  11989. (collect |\itm{bytes}|))])
  11990. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  11991. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  11992. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  11993. |$v$|) ... )))) ...)
  11994. \end{lstlisting}
  11995. \fi}
  11996. {\if\edition\pythonEd\pythonColor
  11997. \begin{lstlisting}
  11998. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  11999. |$\Longrightarrow$|
  12000. begin:
  12001. |$x_0$| = |$e_0$|
  12002. |$\vdots$|
  12003. |$x_{n-1}$| = |$e_{n-1}$|
  12004. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  12005. 0
  12006. else:
  12007. collect(|\itm{bytes}|)
  12008. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  12009. |$v$|[0] = |$x_0$|
  12010. |$\vdots$|
  12011. |$v$|[|$n-1$|] = |$x_{n-1}$|
  12012. |$v$|
  12013. \end{lstlisting}
  12014. \fi}
  12015. \end{minipage}
  12016. \end{center}
  12017. %
  12018. \noindent The sequencing of the initializing expressions
  12019. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important because
  12020. they may trigger garbage collection and we cannot have an allocated
  12021. but uninitialized tuple on the heap during a collection.
  12022. Figure~\ref{fig:expose-alloc-output} shows the output of the
  12023. \code{expose\_allocation} pass on our running example.
  12024. \begin{figure}[tbp]
  12025. \begin{tcolorbox}[colback=white]
  12026. % tests/s2_17.rkt
  12027. {\if\edition\racketEd
  12028. \begin{lstlisting}
  12029. (vector-ref
  12030. (vector-ref
  12031. (let ([vecinit6
  12032. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  12033. (global-value fromspace_end))
  12034. (void)
  12035. (collect 16))])
  12036. (let ([alloc2 (allocate 1 (Vector Integer))])
  12037. (let ([_3 (vector-set! alloc2 0 42)])
  12038. alloc2)))])
  12039. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  12040. (global-value fromspace_end))
  12041. (void)
  12042. (collect 16))])
  12043. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  12044. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  12045. alloc5))))
  12046. 0)
  12047. 0)
  12048. \end{lstlisting}
  12049. \fi}
  12050. {\if\edition\pythonEd\pythonColor
  12051. \begin{lstlisting}
  12052. v1 = begin:
  12053. init.514 = 42
  12054. if (free_ptr + 16) < fromspace_end:
  12055. else:
  12056. collect(16)
  12057. alloc.513 = allocate(1,tuple[int])
  12058. alloc.513[0] = init.514
  12059. alloc.513
  12060. v2 = begin:
  12061. init.516 = v1
  12062. if (free_ptr + 16) < fromspace_end:
  12063. else:
  12064. collect(16)
  12065. alloc.515 = allocate(1,tuple[tuple[int]])
  12066. alloc.515[0] = init.516
  12067. alloc.515
  12068. print(v2[0][0])
  12069. \end{lstlisting}
  12070. \fi}
  12071. \end{tcolorbox}
  12072. \caption{Output of the \code{expose\_allocation} pass.}
  12073. \label{fig:expose-alloc-output}
  12074. \end{figure}
  12075. \section{Remove Complex Operands}
  12076. \label{sec:remove-complex-opera-Lvec}
  12077. {\if\edition\racketEd
  12078. %
  12079. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  12080. should be treated as complex operands.
  12081. %
  12082. \fi}
  12083. %
  12084. {\if\edition\pythonEd\pythonColor
  12085. %
  12086. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  12087. and tuple access should be treated as complex operands. The
  12088. subexpressions of tuple access must be atomic.
  12089. %
  12090. \fi}
  12091. %% A new case for
  12092. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  12093. %% handled carefully to prevent the \code{Prim} node from being separated
  12094. %% from its enclosing \code{HasType}.
  12095. Figure~\ref{fig:Lvec-anf-syntax}
  12096. shows the grammar for the output language \LangAllocANF{} of this
  12097. pass, which is \LangAlloc{} in monadic normal form.
  12098. \newcommand{\LtupMonadASTRacket}{
  12099. \begin{array}{rcl}
  12100. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  12101. \MID \GLOBALVALUE{\Var}
  12102. \end{array}
  12103. }
  12104. \newcommand{\LtupMonadASTPython}{
  12105. \begin{array}{rcl}
  12106. \Exp &::=& \GET{\Atm}{\Atm} \\
  12107. &\MID& \LEN{\Atm}\\
  12108. &\MID& \ALLOCATE{\Int}{\Type}
  12109. \MID \GLOBALVALUE{\Var} \\
  12110. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  12111. &\MID& \COLLECT{\Int}
  12112. \end{array}
  12113. }
  12114. \begin{figure}[tp]
  12115. \centering
  12116. \begin{tcolorbox}[colback=white]
  12117. \small
  12118. {\if\edition\racketEd
  12119. \[
  12120. \begin{array}{l}
  12121. \gray{\LvarMonadASTRacket} \\ \hline
  12122. \gray{\LifMonadASTRacket} \\ \hline
  12123. \gray{\LwhileMonadASTRacket} \\ \hline
  12124. \LtupMonadASTRacket \\
  12125. \begin{array}{rcl}
  12126. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  12127. \end{array}
  12128. \end{array}
  12129. \]
  12130. \fi}
  12131. {\if\edition\pythonEd\pythonColor
  12132. \[
  12133. \begin{array}{l}
  12134. \gray{\LvarMonadASTPython} \\ \hline
  12135. \gray{\LifMonadASTPython} \\ \hline
  12136. \gray{\LwhileMonadASTPython} \\ \hline
  12137. \LtupMonadASTPython \\
  12138. \begin{array}{rcl}
  12139. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  12140. \end{array}
  12141. \end{array}
  12142. \]
  12143. \fi}
  12144. \end{tcolorbox}
  12145. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  12146. \label{fig:Lvec-anf-syntax}
  12147. \end{figure}
  12148. \section{Explicate Control and the \LangCVec{} Language}
  12149. \label{sec:explicate-control-r3}
  12150. \newcommand{\CtupASTRacket}{
  12151. \begin{array}{lcl}
  12152. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  12153. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  12154. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12155. &\MID& \VECLEN{\Atm} \\
  12156. &\MID& \GLOBALVALUE{\Var} \\
  12157. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  12158. &\MID& \LP\key{Collect} \,\itm{int}\RP
  12159. \end{array}
  12160. }
  12161. \newcommand{\CtupASTPython}{
  12162. \begin{array}{lcl}
  12163. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  12164. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  12165. \Stmt &::=& \COLLECT{\Int} \\
  12166. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  12167. \end{array}
  12168. }
  12169. \begin{figure}[tp]
  12170. \begin{tcolorbox}[colback=white]
  12171. \small
  12172. {\if\edition\racketEd
  12173. \[
  12174. \begin{array}{l}
  12175. \gray{\CvarASTRacket} \\ \hline
  12176. \gray{\CifASTRacket} \\ \hline
  12177. \gray{\CloopASTRacket} \\ \hline
  12178. \CtupASTRacket \\
  12179. \begin{array}{lcl}
  12180. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12181. \end{array}
  12182. \end{array}
  12183. \]
  12184. \fi}
  12185. {\if\edition\pythonEd\pythonColor
  12186. \[
  12187. \begin{array}{l}
  12188. \gray{\CifASTPython} \\ \hline
  12189. \CtupASTPython \\
  12190. \begin{array}{lcl}
  12191. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}\;\Tail, \ldots \RC}
  12192. \end{array}
  12193. \end{array}
  12194. \]
  12195. \fi}
  12196. \end{tcolorbox}
  12197. \caption{The abstract syntax of \LangCVec{}, extending
  12198. \racket{\LangCLoop{} (figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  12199. (figure~\ref{fig:c1-syntax})}.}
  12200. \label{fig:c2-syntax}
  12201. \end{figure}
  12202. The output of \code{explicate\_control} is a program in the
  12203. intermediate language \LangCVec{}, for which figure~\ref{fig:c2-syntax}
  12204. shows the definition of the abstract syntax.
  12205. %
  12206. %% \racket{(The concrete syntax is defined in
  12207. %% figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  12208. %
  12209. The new expressions of \LangCVec{} include \key{allocate},
  12210. %
  12211. \racket{\key{vector-ref}, and \key{vector-set!},}
  12212. %
  12213. \python{accessing tuple elements,}
  12214. %
  12215. and \key{global\_value}.
  12216. %
  12217. \python{\LangCVec{} also includes the \code{collect} statement and
  12218. assignment to a tuple element.}
  12219. %
  12220. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  12221. %
  12222. The \code{explicate\_control} pass can treat these new forms much like
  12223. the other forms that we've already encountered. The output of the
  12224. \code{explicate\_control} pass on the running example is shown on the
  12225. left side of figure~\ref{fig:select-instr-output-gc} in the next
  12226. section.
  12227. \section{Select Instructions and the \LangXGlobal{} Language}
  12228. \label{sec:select-instructions-gc}
  12229. \index{subject}{select instructions}
  12230. %% void (rep as zero)
  12231. %% allocate
  12232. %% collect (callq collect)
  12233. %% vector-ref
  12234. %% vector-set!
  12235. %% vector-length
  12236. %% global (postpone)
  12237. In this pass we generate x86 code for most of the new operations that
  12238. are needed to compile tuples, including \code{Allocate},
  12239. \code{Collect}, accessing tuple elements, and the \code{Is}
  12240. comparison.
  12241. %
  12242. We compile \code{GlobalValue} to \code{Global} because the latter has a
  12243. different concrete syntax (see figures~\ref{fig:x86-2-concrete} and
  12244. \ref{fig:x86-2}). \index{subject}{x86}
  12245. The tuple read and write forms translate into \code{movq}
  12246. instructions. (The $+1$ in the offset serves to move past the tag at the
  12247. beginning of the tuple representation.)
  12248. %
  12249. \begin{center}
  12250. \begin{minipage}{\textwidth}
  12251. {\if\edition\racketEd
  12252. \begin{lstlisting}
  12253. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  12254. |$\Longrightarrow$|
  12255. movq |$\itm{tup}'$|, %r11
  12256. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12257. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  12258. |$\Longrightarrow$|
  12259. movq |$\itm{tup}'$|, %r11
  12260. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12261. movq $0, |$\itm{lhs'}$|
  12262. \end{lstlisting}
  12263. \fi}
  12264. {\if\edition\pythonEd\pythonColor
  12265. \begin{lstlisting}
  12266. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  12267. |$\Longrightarrow$|
  12268. movq |$\itm{tup}'$|, %r11
  12269. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  12270. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  12271. |$\Longrightarrow$|
  12272. movq |$\itm{tup}'$|, %r11
  12273. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  12274. \end{lstlisting}
  12275. \fi}
  12276. \end{minipage}
  12277. \end{center}
  12278. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  12279. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  12280. are obtained by translating from \LangCVec{} to x86.
  12281. %
  12282. The move of $\itm{tup}'$ to
  12283. register \code{r11} ensures that the offset expression
  12284. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  12285. removing \code{r11} from consideration by the register allocator.
  12286. Why not use \code{rax} instead of \code{r11}? Suppose that we instead used
  12287. \code{rax}. Then the generated code for tuple assignment would be
  12288. \begin{lstlisting}
  12289. movq |$\itm{tup}'$|, %rax
  12290. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  12291. \end{lstlisting}
  12292. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  12293. \code{patch\_instructions} would insert a move through \code{rax}
  12294. as follows:
  12295. \begin{lstlisting}
  12296. movq |$\itm{tup}'$|, %rax
  12297. movq |$\itm{rhs}'$|, %rax
  12298. movq %rax, |$8(n+1)$|(%rax)
  12299. \end{lstlisting}
  12300. However, this sequence of instructions does not work because we're
  12301. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  12302. $\itm{rhs}'$) at the same time!
  12303. The \racket{\code{vector-length}}\python{\code{len}} operation should
  12304. be translated into a sequence of instructions that read the tag of the
  12305. tuple and extract the 6 bits that represent the tuple length, which
  12306. are the bits starting at index 1 and going up to and including bit 6.
  12307. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  12308. (shift right) can be used to accomplish this.
  12309. We compile the \code{allocate} form to operations on the
  12310. \code{free\_ptr}, as shown next. This approach is called
  12311. \emph{inline allocation} because it implements allocation without a
  12312. function call by simply incrementing the allocation pointer. It is much
  12313. more efficient than calling a function for each allocation. The
  12314. address in the \code{free\_ptr} is the next free address in the
  12315. FromSpace, so we copy it into \code{r11} and then move it forward by
  12316. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  12317. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  12318. the tag. We then initialize the \itm{tag} and finally copy the
  12319. address in \code{r11} to the left-hand side. Refer to
  12320. figure~\ref{fig:tuple-rep} to see how the tag is organized.
  12321. %
  12322. \racket{We recommend using the Racket operations
  12323. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  12324. during compilation.}
  12325. %
  12326. \python{We recommend using the bitwise-or operator \code{|} and the
  12327. shift-left operator \code{<<} to compute the tag during
  12328. compilation.}
  12329. %
  12330. The type annotation in the \code{allocate} form is used to determine
  12331. the pointer mask region of the tag.
  12332. %
  12333. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  12334. address of the \code{free\_ptr} global variable using a special
  12335. instruction-pointer-relative addressing mode of the x86-64 processor.
  12336. In particular, the assembler computes the distance $d$ between the
  12337. address of \code{free\_ptr} and where the \code{rip} would be at that
  12338. moment and then changes the \code{free\_ptr(\%rip)} argument to
  12339. \code{$d$(\%rip)}, which at runtime will compute the address of
  12340. \code{free\_ptr}.
  12341. %
  12342. {\if\edition\racketEd
  12343. \begin{lstlisting}
  12344. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  12345. |$\Longrightarrow$|
  12346. movq free_ptr(%rip), %r11
  12347. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12348. movq $|$\itm{tag}$|, 0(%r11)
  12349. movq %r11, |$\itm{lhs}'$|
  12350. \end{lstlisting}
  12351. \fi}
  12352. {\if\edition\pythonEd\pythonColor
  12353. \begin{lstlisting}
  12354. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  12355. |$\Longrightarrow$|
  12356. movq free_ptr(%rip), %r11
  12357. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  12358. movq $|$\itm{tag}$|, 0(%r11)
  12359. movq %r11, |$\itm{lhs}'$|
  12360. \end{lstlisting}
  12361. \fi}
  12362. %
  12363. The \code{collect} form is compiled to a call to the \code{collect}
  12364. function in the runtime. The arguments to \code{collect} are (1) the
  12365. top of the root stack, and (2) the number of bytes that need to be
  12366. allocated. We use another dedicated register, \code{r15}, to store
  12367. the pointer to the top of the root stack. Therefore \code{r15} is not
  12368. available for use by the register allocator.
  12369. %
  12370. {\if\edition\racketEd
  12371. \begin{lstlisting}
  12372. (collect |$\itm{bytes}$|)
  12373. |$\Longrightarrow$|
  12374. movq %r15, %rdi
  12375. movq $|\itm{bytes}|, %rsi
  12376. callq collect
  12377. \end{lstlisting}
  12378. \fi}
  12379. {\if\edition\pythonEd\pythonColor
  12380. \begin{lstlisting}
  12381. collect(|$\itm{bytes}$|)
  12382. |$\Longrightarrow$|
  12383. movq %r15, %rdi
  12384. movq $|\itm{bytes}|, %rsi
  12385. callq collect
  12386. \end{lstlisting}
  12387. \fi}
  12388. {\if\edition\pythonEd\pythonColor
  12389. The \code{is} comparison is compiled similarly to the other comparison
  12390. operators, using the \code{cmpq} instruction. Because the value of a
  12391. tuple is its address, we can translate \code{is} into a simple check
  12392. for equality using the \code{e} condition code. \\
  12393. \begin{tabular}{lll}
  12394. \begin{minipage}{0.4\textwidth}
  12395. $\CASSIGN{\Var}{ \LP\CIS{\Atm_1}{\Atm_2} \RP }$
  12396. \end{minipage}
  12397. &
  12398. $\Rightarrow$
  12399. &
  12400. \begin{minipage}{0.4\textwidth}
  12401. \begin{lstlisting}
  12402. cmpq |$\Arg_2$|, |$\Arg_1$|
  12403. sete %al
  12404. movzbq %al, |$\Var$|
  12405. \end{lstlisting}
  12406. \end{minipage}
  12407. \end{tabular}
  12408. \fi}
  12409. \newcommand{\GrammarXGlobal}{
  12410. \begin{array}{lcl}
  12411. \Arg &::=& \itm{label} \key{(\%rip)}
  12412. \end{array}
  12413. }
  12414. \newcommand{\ASTXGlobalRacket}{
  12415. \begin{array}{lcl}
  12416. \Arg &::=& \GLOBAL{\itm{label}}
  12417. \end{array}
  12418. }
  12419. \begin{figure}[tp]
  12420. \begin{tcolorbox}[colback=white]
  12421. \[
  12422. \begin{array}{l}
  12423. \gray{\GrammarXInt} \\ \hline
  12424. \gray{\GrammarXIf} \\ \hline
  12425. \GrammarXGlobal \\
  12426. \begin{array}{lcl}
  12427. \LangXGlobalM{} &::= & \key{.globl main} \\
  12428. & & \key{main:} \; \Instr^{*}
  12429. \end{array}
  12430. \end{array}
  12431. \]
  12432. \end{tcolorbox}
  12433. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1-concrete}).}
  12434. \label{fig:x86-2-concrete}
  12435. \end{figure}
  12436. \begin{figure}[tp]
  12437. \begin{tcolorbox}[colback=white]
  12438. \small
  12439. {\if\edition\racketEd
  12440. \[
  12441. \begin{array}{l}
  12442. \gray{\ASTXIntRacket} \\ \hline
  12443. \gray{\ASTXIfRacket} \\ \hline
  12444. \ASTXGlobalRacket \\
  12445. \begin{array}{lcl}
  12446. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  12447. \end{array}
  12448. \end{array}
  12449. \]
  12450. \fi}
  12451. {\if\edition\pythonEd\pythonColor
  12452. \[
  12453. \begin{array}{l}
  12454. \gray{\ASTXIntPython} \\ \hline
  12455. \gray{\ASTXIfPython} \\ \hline
  12456. \ASTXGlobalRacket \\
  12457. \begin{array}{lcl}
  12458. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  12459. \end{array}
  12460. \end{array}
  12461. \]
  12462. \fi}
  12463. \end{tcolorbox}
  12464. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} shown in figure~\ref{fig:x86-1}).}
  12465. \label{fig:x86-2}
  12466. \end{figure}
  12467. The definitions of the concrete and abstract syntax of the
  12468. \LangXGlobal{} language are shown in figures~\ref{fig:x86-2-concrete}
  12469. and \ref{fig:x86-2}. It differs from \LangXIf{} only in the addition
  12470. of global variables.
  12471. %
  12472. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  12473. \code{select\_instructions} pass on the running example.
  12474. \begin{figure}[tbp]
  12475. \centering
  12476. \begin{tcolorbox}[colback=white]
  12477. {\if\edition\racketEd
  12478. % tests/s2_17.rkt
  12479. \begin{tabular}{lll}
  12480. \begin{minipage}{0.5\textwidth}
  12481. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12482. start:
  12483. tmp9 = (global-value free_ptr);
  12484. tmp0 = (+ tmp9 16);
  12485. tmp1 = (global-value fromspace_end);
  12486. if (< tmp0 tmp1)
  12487. goto block0;
  12488. else
  12489. goto block1;
  12490. block0:
  12491. _4 = (void);
  12492. goto block9;
  12493. block1:
  12494. (collect 16)
  12495. goto block9;
  12496. block9:
  12497. alloc2 = (allocate 1 (Vector Integer));
  12498. _3 = (vector-set! alloc2 0 42);
  12499. vecinit6 = alloc2;
  12500. tmp2 = (global-value free_ptr);
  12501. tmp3 = (+ tmp2 16);
  12502. tmp4 = (global-value fromspace_end);
  12503. if (< tmp3 tmp4)
  12504. goto block7;
  12505. else
  12506. goto block8;
  12507. block7:
  12508. _8 = (void);
  12509. goto block6;
  12510. block8:
  12511. (collect 16)
  12512. goto block6;
  12513. block6:
  12514. alloc5 = (allocate 1 (Vector (Vector Integer)));
  12515. _7 = (vector-set! alloc5 0 vecinit6);
  12516. tmp5 = (vector-ref alloc5 0);
  12517. return (vector-ref tmp5 0);
  12518. \end{lstlisting}
  12519. \end{minipage}
  12520. &$\Rightarrow$&
  12521. \begin{minipage}{0.4\textwidth}
  12522. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12523. start:
  12524. movq free_ptr(%rip), tmp9
  12525. movq tmp9, tmp0
  12526. addq $16, tmp0
  12527. movq fromspace_end(%rip), tmp1
  12528. cmpq tmp1, tmp0
  12529. jl block0
  12530. jmp block1
  12531. block0:
  12532. movq $0, _4
  12533. jmp block9
  12534. block1:
  12535. movq %r15, %rdi
  12536. movq $16, %rsi
  12537. callq collect
  12538. jmp block9
  12539. block9:
  12540. movq free_ptr(%rip), %r11
  12541. addq $16, free_ptr(%rip)
  12542. movq $3, 0(%r11)
  12543. movq %r11, alloc2
  12544. movq alloc2, %r11
  12545. movq $42, 8(%r11)
  12546. movq $0, _3
  12547. movq alloc2, vecinit6
  12548. movq free_ptr(%rip), tmp2
  12549. movq tmp2, tmp3
  12550. addq $16, tmp3
  12551. movq fromspace_end(%rip), tmp4
  12552. cmpq tmp4, tmp3
  12553. jl block7
  12554. jmp block8
  12555. block7:
  12556. movq $0, _8
  12557. jmp block6
  12558. block8:
  12559. movq %r15, %rdi
  12560. movq $16, %rsi
  12561. callq collect
  12562. jmp block6
  12563. block6:
  12564. movq free_ptr(%rip), %r11
  12565. addq $16, free_ptr(%rip)
  12566. movq $131, 0(%r11)
  12567. movq %r11, alloc5
  12568. movq alloc5, %r11
  12569. movq vecinit6, 8(%r11)
  12570. movq $0, _7
  12571. movq alloc5, %r11
  12572. movq 8(%r11), tmp5
  12573. movq tmp5, %r11
  12574. movq 8(%r11), %rax
  12575. jmp conclusion
  12576. \end{lstlisting}
  12577. \end{minipage}
  12578. \end{tabular}
  12579. \fi}
  12580. {\if\edition\pythonEd
  12581. % tests/tuple/get_get.py
  12582. \begin{tabular}{lll}
  12583. \begin{minipage}{0.5\textwidth}
  12584. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12585. start:
  12586. init.514 = 42
  12587. tmp.517 = free_ptr
  12588. tmp.518 = (tmp.517 + 16)
  12589. tmp.519 = fromspace_end
  12590. if tmp.518 < tmp.519:
  12591. goto block.529
  12592. else:
  12593. goto block.530
  12594. block.529:
  12595. goto block.528
  12596. block.530:
  12597. collect(16)
  12598. goto block.528
  12599. block.528:
  12600. alloc.513 = allocate(1,tuple[int])
  12601. alloc.513:tuple[int][0] = init.514
  12602. v1 = alloc.513
  12603. init.516 = v1
  12604. tmp.520 = free_ptr
  12605. tmp.521 = (tmp.520 + 16)
  12606. tmp.522 = fromspace_end
  12607. if tmp.521 < tmp.522:
  12608. goto block.526
  12609. else:
  12610. goto block.527
  12611. block.526:
  12612. goto block.525
  12613. block.527:
  12614. collect(16)
  12615. goto block.525
  12616. block.525:
  12617. alloc.515 = allocate(1,tuple[tuple[int]])
  12618. alloc.515:tuple[tuple[int]][0] = init.516
  12619. v2 = alloc.515
  12620. tmp.523 = v2[0]
  12621. tmp.524 = tmp.523[0]
  12622. print(tmp.524)
  12623. return 0
  12624. \end{lstlisting}
  12625. \end{minipage}
  12626. &$\Rightarrow$&
  12627. \begin{minipage}{0.4\textwidth}
  12628. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  12629. start:
  12630. movq $42, init.514
  12631. movq free_ptr(%rip), tmp.517
  12632. movq tmp.517, tmp.518
  12633. addq $16, tmp.518
  12634. movq fromspace_end(%rip), tmp.519
  12635. cmpq tmp.519, tmp.518
  12636. jl block.529
  12637. jmp block.530
  12638. block.529:
  12639. jmp block.528
  12640. block.530:
  12641. movq %r15, %rdi
  12642. movq $16, %rsi
  12643. callq collect
  12644. jmp block.528
  12645. block.528:
  12646. movq free_ptr(%rip), %r11
  12647. addq $16, free_ptr(%rip)
  12648. movq $3, 0(%r11)
  12649. movq %r11, alloc.513
  12650. movq alloc.513, %r11
  12651. movq init.514, 8(%r11)
  12652. movq alloc.513, v1
  12653. movq v1, init.516
  12654. movq free_ptr(%rip), tmp.520
  12655. movq tmp.520, tmp.521
  12656. addq $16, tmp.521
  12657. movq fromspace_end(%rip), tmp.522
  12658. cmpq tmp.522, tmp.521
  12659. jl block.526
  12660. jmp block.527
  12661. block.526:
  12662. jmp block.525
  12663. block.527:
  12664. movq %r15, %rdi
  12665. movq $16, %rsi
  12666. callq collect
  12667. jmp block.525
  12668. block.525:
  12669. movq free_ptr(%rip), %r11
  12670. addq $16, free_ptr(%rip)
  12671. movq $131, 0(%r11)
  12672. movq %r11, alloc.515
  12673. movq alloc.515, %r11
  12674. movq init.516, 8(%r11)
  12675. movq alloc.515, v2
  12676. movq v2, %r11
  12677. movq 8(%r11), %r11
  12678. movq %r11, tmp.523
  12679. movq tmp.523, %r11
  12680. movq 8(%r11), %r11
  12681. movq %r11, tmp.524
  12682. movq tmp.524, %rdi
  12683. callq print_int
  12684. movq $0, %rax
  12685. jmp conclusion
  12686. \end{lstlisting}
  12687. \end{minipage}
  12688. \end{tabular}
  12689. \fi}
  12690. \end{tcolorbox}
  12691. \caption{Output of \code{explicate\_control} (\emph{left}) and
  12692. \code{select\_instructions} (\emph{right}) on the running example.}
  12693. \label{fig:select-instr-output-gc}
  12694. \end{figure}
  12695. \clearpage
  12696. \section{Register Allocation}
  12697. \label{sec:reg-alloc-gc}
  12698. \index{subject}{register allocation}
  12699. As discussed previously in this chapter, the garbage collector needs to
  12700. access all the pointers in the root set, that is, all variables that
  12701. are tuples. It will be the responsibility of the register allocator
  12702. to make sure that
  12703. \begin{enumerate}
  12704. \item the root stack is used for spilling tuple-typed variables, and
  12705. \item if a tuple-typed variable is live during a call to the
  12706. collector, it must be spilled to ensure that it is visible to the
  12707. collector.
  12708. \end{enumerate}
  12709. The latter responsibility can be handled during construction of the
  12710. interference graph, by adding interference edges between the call-live
  12711. tuple-typed variables and all the callee-saved registers. (They
  12712. already interfere with the caller-saved registers.)
  12713. %
  12714. \racket{The type information for variables is in the \code{Program}
  12715. form, so we recommend adding another parameter to the
  12716. \code{build\_interference} function to communicate this alist.}
  12717. %
  12718. \python{The type information for variables is generated by the type
  12719. checker for \LangCVec{}, stored in a field named \code{var\_types} in
  12720. the \code{CProgram} AST mode. You'll need to propagate that
  12721. information so that it is available in this pass.}
  12722. The spilling of tuple-typed variables to the root stack can be handled
  12723. after graph coloring, in choosing how to assign the colors
  12724. (integers) to registers and stack locations. The
  12725. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  12726. changes to also record the number of spills to the root stack.
  12727. % build-interference
  12728. %
  12729. % callq
  12730. % extra parameter for var->type assoc. list
  12731. % update 'program' and 'if'
  12732. % allocate-registers
  12733. % allocate spilled vectors to the rootstack
  12734. % don't change color-graph
  12735. % TODO:
  12736. %\section{Patch Instructions}
  12737. %[mention that global variables are memory references]
  12738. \section{Generate Prelude and Conclusion}
  12739. \label{sec:print-x86-gc}
  12740. \label{sec:prelude-conclusion-x86-gc}
  12741. \index{subject}{prelude}\index{subject}{conclusion}
  12742. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  12743. \code{prelude\_and\_conclusion} pass on the running example. In the
  12744. prelude of the \code{main} function, we allocate space
  12745. on the root stack to make room for the spills of tuple-typed
  12746. variables. We do so by incrementing the root stack pointer (\code{r15}),
  12747. taking care that the root stack grows up instead of down. For the
  12748. running example, there was just one spill, so we increment \code{r15}
  12749. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  12750. One issue that deserves special care is that there may be a call to
  12751. \code{collect} prior to the initializing assignments for all the
  12752. variables in the root stack. We do not want the garbage collector to
  12753. mistakenly determine that some uninitialized variable is a pointer that
  12754. needs to be followed. Thus, we zero out all locations on the root
  12755. stack in the prelude of \code{main}. In
  12756. figure~\ref{fig:print-x86-output-gc}, the instruction
  12757. %
  12758. \lstinline{movq $0, 0(%r15)}
  12759. %
  12760. is sufficient to accomplish this task because there is only one spill.
  12761. In general, we have to clear as many words as there are spills of
  12762. tuple-typed variables. The garbage collector tests each root to see
  12763. if it is null prior to dereferencing it.
  12764. \begin{figure}[htbp]
  12765. \begin{tcolorbox}[colback=white]
  12766. {\if\edition\racketEd
  12767. \begin{minipage}[t]{0.5\textwidth}
  12768. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12769. .globl main
  12770. main:
  12771. pushq %rbp
  12772. movq %rsp, %rbp
  12773. subq $0, %rsp
  12774. movq $65536, %rdi
  12775. movq $65536, %rsi
  12776. callq initialize
  12777. movq rootstack_begin(%rip), %r15
  12778. movq $0, 0(%r15)
  12779. addq $8, %r15
  12780. jmp start
  12781. conclusion:
  12782. subq $8, %r15
  12783. addq $0, %rsp
  12784. popq %rbp
  12785. retq
  12786. \end{lstlisting}
  12787. \end{minipage}
  12788. \fi}
  12789. {\if\edition\pythonEd
  12790. \begin{minipage}[t]{0.5\textwidth}
  12791. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12792. .globl main
  12793. main:
  12794. pushq %rbp
  12795. movq %rsp, %rbp
  12796. pushq %rbx
  12797. subq $8, %rsp
  12798. movq $65536, %rdi
  12799. movq $16, %rsi
  12800. callq initialize
  12801. movq rootstack_begin(%rip), %r15
  12802. movq $0, 0(%r15)
  12803. addq $8, %r15
  12804. jmp start
  12805. conclusion:
  12806. subq $8, %r15
  12807. addq $8, %rsp
  12808. popq %rbx
  12809. popq %rbp
  12810. retq
  12811. \end{lstlisting}
  12812. \end{minipage}
  12813. \fi}
  12814. \end{tcolorbox}
  12815. \caption{The prelude and conclusion for the running example.}
  12816. \label{fig:print-x86-output-gc}
  12817. \end{figure}
  12818. \begin{figure}[tbp]
  12819. \begin{tcolorbox}[colback=white]
  12820. {\if\edition\racketEd
  12821. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  12822. \node (Lvec) at (0,2) {\large \LangVec{}};
  12823. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  12824. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  12825. \node (Lvec-4) at (10,2) {\large \LangAlloc{}};
  12826. \node (Lvec-5) at (10,0) {\large \LangAlloc{}};
  12827. \node (Lvec-6) at (5,0) {\large \LangAllocANF{}};
  12828. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12829. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12830. \node (x86-2-1) at (0,-4) {\large \LangXGlobalVar{}};
  12831. \node (x86-2-2) at (4,-4) {\large \LangXGlobalVar{}};
  12832. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12833. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12834. \node (x86-5) at (8,-4) {\large \LangXGlobal{}};
  12835. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12836. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  12837. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-4);
  12838. \path[->,bend left=15] (Lvec-4) edge [right] node
  12839. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  12840. \path[->,bend left=10] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12841. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  12842. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12843. \path[->,bend right=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  12844. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_interference} (x86-2-2);
  12845. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_registers} (x86-3);
  12846. \path[->,bend left=10] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12847. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12848. \end{tikzpicture}
  12849. \fi}
  12850. {\if\edition\pythonEd\pythonColor
  12851. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  12852. \node (Lvec) at (0,2) {\large \LangVec{}};
  12853. \node (Lvec-2) at (4,2) {\large \LangVec{}};
  12854. \node (Lvec-5) at (8,2) {\large \LangAlloc{}};
  12855. \node (Lvec-6) at (12,2) {\large \LangAllocANF{}};
  12856. \node (C2-4) at (0,0) {\large \LangCVec{}};
  12857. \node (x86-2) at (0,-2) {\large \LangXGlobalVar{}};
  12858. \node (x86-3) at (4,-2) {\large \LangXGlobalVar{}};
  12859. \node (x86-4) at (8,-2) {\large \LangXGlobal{}};
  12860. \node (x86-5) at (12,-2) {\large \LangXGlobal{}};
  12861. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  12862. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize expose\_allocation} (Lvec-5);
  12863. \path[->,bend left=15] (Lvec-5) edge [above] node {\ttfamily\footnotesize remove\_complex\_operands} (Lvec-6);
  12864. \path[->,bend left=10] (Lvec-6) edge [right] node {\ttfamily\footnotesize \ \ \ explicate\_control} (C2-4);
  12865. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  12866. \path[->,bend right=15] (x86-2) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  12867. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instructions} (x86-4);
  12868. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  12869. \end{tikzpicture}
  12870. \fi}
  12871. \end{tcolorbox}
  12872. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  12873. \label{fig:Lvec-passes}
  12874. \end{figure}
  12875. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  12876. for the compilation of \LangVec{}.
  12877. \clearpage
  12878. {\if\edition\racketEd
  12879. \section{Challenge: Simple Structures}
  12880. \label{sec:simple-structures}
  12881. \index{subject}{struct}
  12882. \index{subject}{structure}
  12883. The language \LangStruct{} extends \LangVec{} with support for simple
  12884. structures. The definition of its concrete syntax is shown in
  12885. figure~\ref{fig:Lstruct-concrete-syntax}, and the abstract syntax is
  12886. shown in figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct}
  12887. in Typed Racket is a user-defined data type that contains named fields
  12888. and that is heap allocated\index{subject}{heap allocated},
  12889. similarly to a vector. The following is an
  12890. example of a structure definition, in this case the definition of a
  12891. \code{point} type:
  12892. \begin{lstlisting}
  12893. (struct point ([x : Integer] [y : Integer]) #:mutable)
  12894. \end{lstlisting}
  12895. \newcommand{\LstructGrammarRacket}{
  12896. \begin{array}{lcl}
  12897. \Type &::=& \Var \\
  12898. \Exp &::=& (\Var\;\Exp \ldots)\\
  12899. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  12900. \end{array}
  12901. }
  12902. \newcommand{\LstructASTRacket}{
  12903. \begin{array}{lcl}
  12904. \Type &::=& \VAR{\Var} \\
  12905. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  12906. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  12907. \end{array}
  12908. }
  12909. \begin{figure}[tbp]
  12910. \centering
  12911. \begin{tcolorbox}[colback=white]
  12912. \[
  12913. \begin{array}{l}
  12914. \gray{\LintGrammarRacket{}} \\ \hline
  12915. \gray{\LvarGrammarRacket{}} \\ \hline
  12916. \gray{\LifGrammarRacket{}} \\ \hline
  12917. \gray{\LwhileGrammarRacket} \\ \hline
  12918. \gray{\LtupGrammarRacket} \\ \hline
  12919. \LstructGrammarRacket \\
  12920. \begin{array}{lcl}
  12921. \LangStruct{} &::=& \Def \ldots \; \Exp
  12922. \end{array}
  12923. \end{array}
  12924. \]
  12925. \end{tcolorbox}
  12926. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  12927. (figure~\ref{fig:Lvec-concrete-syntax}).}
  12928. \label{fig:Lstruct-concrete-syntax}
  12929. \end{figure}
  12930. \begin{figure}[tbp]
  12931. \centering
  12932. \begin{tcolorbox}[colback=white]
  12933. \small
  12934. \[
  12935. \begin{array}{l}
  12936. \gray{\LintASTRacket{}} \\ \hline
  12937. \gray{\LvarASTRacket{}} \\ \hline
  12938. \gray{\LifASTRacket{}} \\ \hline
  12939. \gray{\LwhileASTRacket} \\ \hline
  12940. \gray{\LtupASTRacket} \\ \hline
  12941. \LstructASTRacket \\
  12942. \begin{array}{lcl}
  12943. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12944. \end{array}
  12945. \end{array}
  12946. \]
  12947. \end{tcolorbox}
  12948. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  12949. (figure~\ref{fig:Lvec-syntax}).}
  12950. \label{fig:Lstruct-syntax}
  12951. \end{figure}
  12952. An instance of a structure is created using function-call syntax, with
  12953. the name of the structure in the function position, as follows:
  12954. \begin{lstlisting}
  12955. (point 7 12)
  12956. \end{lstlisting}
  12957. Function-call syntax is also used to read a field of a structure. The
  12958. function name is formed by the structure name, a dash, and the field
  12959. name. The following example uses \code{point-x} and \code{point-y} to
  12960. access the \code{x} and \code{y} fields of two point instances:
  12961. \begin{center}
  12962. \begin{lstlisting}
  12963. (let ([pt1 (point 7 12)])
  12964. (let ([pt2 (point 4 3)])
  12965. (+ (- (point-x pt1) (point-x pt2))
  12966. (- (point-y pt1) (point-y pt2)))))
  12967. \end{lstlisting}
  12968. \end{center}
  12969. Similarly, to write to a field of a structure, use its set function,
  12970. whose name starts with \code{set-}, followed by the structure name,
  12971. then a dash, then the field name, and finally with an exclamation
  12972. mark. The following example uses \code{set-point-x!} to change the
  12973. \code{x} field from \code{7} to \code{42}:
  12974. \begin{center}
  12975. \begin{lstlisting}
  12976. (let ([pt (point 7 12)])
  12977. (let ([_ (set-point-x! pt 42)])
  12978. (point-x pt)))
  12979. \end{lstlisting}
  12980. \end{center}
  12981. \begin{exercise}\normalfont\normalsize
  12982. Create a type checker for \LangStruct{} by extending the type
  12983. checker for \LangVec{}. Extend your compiler with support for simple
  12984. structures, compiling \LangStruct{} to x86 assembly code. Create
  12985. five new test cases that use structures, and test your compiler.
  12986. \end{exercise}
  12987. % TODO: create an interpreter for L_struct
  12988. \clearpage
  12989. \fi}
  12990. \section{Challenge: Arrays}
  12991. \label{sec:arrays}
  12992. % TODO mention trapped-error
  12993. In this chapter we have studied tuples, that is, heterogeneous
  12994. sequences of elements whose length is determined at compile time. This
  12995. challenge is also about sequences, but this time the length is
  12996. determined at runtime and all the elements have the same type (they
  12997. are homogeneous). We use the traditional term \emph{array} for this
  12998. latter kind of sequence.
  12999. %
  13000. \racket{
  13001. The Racket language does not distinguish between tuples and arrays;
  13002. they are both represented by vectors. However, Typed Racket
  13003. distinguishes between tuples and arrays: the \code{Vector} type is for
  13004. tuples, and the \code{Vectorof} type is for arrays.}%
  13005. \python{Arrays correspond to the \code{list} type in the Python language.}
  13006. Figure~\ref{fig:Lvecof-concrete-syntax} presents the definition of the
  13007. concrete syntax for \LangArray{}, and figure~\ref{fig:Lvecof-syntax}
  13008. presents the definition of the abstract syntax, extending \LangVec{}
  13009. with the \racket{\code{Vectorof}}\python{\code{list}} type and the
  13010. \racket{\code{make-vector} primitive operator for creating an array,
  13011. whose arguments are the length of the array and an initial value for
  13012. all the elements in the array.}%
  13013. \python{bracket notation for creating an array literal.}
  13014. \racket{The \code{vector-length},
  13015. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  13016. for tuples become overloaded for use with arrays.}
  13017. \python{
  13018. The subscript operator becomes overloaded for use with arrays and tuples
  13019. and now may appear on the left-hand side of an assignment.
  13020. Note that the index of the subscript, when applied to an array, may be an
  13021. arbitrary expression and not exclusively a constant integer.
  13022. The \code{len} function is also applicable to arrays.
  13023. }
  13024. %
  13025. We include integer multiplication in \LangArray{} because it is
  13026. useful in many examples involving arrays such as computing the
  13027. inner product of two arrays (figure~\ref{fig:inner_product}).
  13028. \newcommand{\LarrayGrammarRacket}{
  13029. \begin{array}{lcl}
  13030. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13031. \Exp &::=& \CMUL{\Exp}{\Exp}
  13032. \MID \CMAKEVEC{\Exp}{\Exp}
  13033. \end{array}
  13034. }
  13035. \newcommand{\LarrayASTRacket}{
  13036. \begin{array}{lcl}
  13037. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  13038. \Exp &::=& \MUL{\Exp}{\Exp}
  13039. \MID \MAKEVEC{\Exp}{\Exp}
  13040. \end{array}
  13041. }
  13042. \newcommand{\LarrayGrammarPython}{
  13043. \begin{array}{lcl}
  13044. \Type &::=& \key{list}\LS\Type\RS \\
  13045. \Exp &::=& \CMUL{\Exp}{\Exp}
  13046. \MID \CGET{\Exp}{\Exp}
  13047. \MID \LS \Exp \code{,} \ldots \RS \\
  13048. \Stmt &::= & \CGET{\Exp}{\Exp} \mathop{\key{=}}\Exp
  13049. \end{array}
  13050. }
  13051. \newcommand{\LarrayASTPython}{
  13052. \begin{array}{lcl}
  13053. \Type &::=& \key{ListType}\LP\Type\RP \\
  13054. \Exp &::=& \MUL{\Exp}{\Exp}
  13055. \MID \GET{\Exp}{\Exp} \\
  13056. &\MID& \key{List}\LP \Exp \code{,} \ldots \code{, } \code{Load()} \RP \\
  13057. \Stmt &::= & \ASSIGN{ \PUT{\Exp}{\Exp} }{\Exp}
  13058. \end{array}
  13059. }
  13060. \begin{figure}[tp]
  13061. \centering
  13062. \begin{tcolorbox}[colback=white]
  13063. \small
  13064. {\if\edition\racketEd
  13065. \[
  13066. \begin{array}{l}
  13067. \gray{\LintGrammarRacket{}} \\ \hline
  13068. \gray{\LvarGrammarRacket{}} \\ \hline
  13069. \gray{\LifGrammarRacket{}} \\ \hline
  13070. \gray{\LwhileGrammarRacket} \\ \hline
  13071. \gray{\LtupGrammarRacket} \\ \hline
  13072. \LarrayGrammarRacket \\
  13073. \begin{array}{lcl}
  13074. \LangArray{} &::=& \Exp
  13075. \end{array}
  13076. \end{array}
  13077. \]
  13078. \fi}
  13079. {\if\edition\pythonEd\pythonColor
  13080. \[
  13081. \begin{array}{l}
  13082. \gray{\LintGrammarPython{}} \\ \hline
  13083. \gray{\LvarGrammarPython{}} \\ \hline
  13084. \gray{\LifGrammarPython{}} \\ \hline
  13085. \gray{\LwhileGrammarPython} \\ \hline
  13086. \gray{\LtupGrammarPython} \\ \hline
  13087. \LarrayGrammarPython \\
  13088. \begin{array}{rcl}
  13089. \LangArrayM{} &::=& \Stmt^{*}
  13090. \end{array}
  13091. \end{array}
  13092. \]
  13093. \fi}
  13094. \end{tcolorbox}
  13095. \caption{The concrete syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13096. \label{fig:Lvecof-concrete-syntax}
  13097. \end{figure}
  13098. \begin{figure}[tp]
  13099. \centering
  13100. \begin{tcolorbox}[colback=white]
  13101. \small
  13102. {\if\edition\racketEd
  13103. \[
  13104. \begin{array}{l}
  13105. \gray{\LintASTRacket{}} \\ \hline
  13106. \gray{\LvarASTRacket{}} \\ \hline
  13107. \gray{\LifASTRacket{}} \\ \hline
  13108. \gray{\LwhileASTRacket} \\ \hline
  13109. \gray{\LtupASTRacket} \\ \hline
  13110. \LarrayASTRacket \\
  13111. \begin{array}{lcl}
  13112. \LangArray{} &::=& \Exp
  13113. \end{array}
  13114. \end{array}
  13115. \]
  13116. \fi}
  13117. {\if\edition\pythonEd\pythonColor
  13118. \[
  13119. \begin{array}{l}
  13120. \gray{\LintASTPython{}} \\ \hline
  13121. \gray{\LvarASTPython{}} \\ \hline
  13122. \gray{\LifASTPython{}} \\ \hline
  13123. \gray{\LwhileASTPython} \\ \hline
  13124. \gray{\LtupASTPython} \\ \hline
  13125. \LarrayASTPython \\
  13126. \begin{array}{rcl}
  13127. \LangArrayM{} &::=& \Stmt^{*}
  13128. \end{array}
  13129. \end{array}
  13130. \]
  13131. \fi}
  13132. \end{tcolorbox}
  13133. \caption{The abstract syntax of \LangArray{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13134. \label{fig:Lvecof-syntax}
  13135. \end{figure}
  13136. \begin{figure}[tp]
  13137. \begin{tcolorbox}[colback=white]
  13138. {\if\edition\racketEd
  13139. % TODO: remove the function from the following example, like the python version -Jeremy
  13140. \begin{lstlisting}
  13141. (let ([A (make-vector 2 2)])
  13142. (let ([B (make-vector 2 3)])
  13143. (let ([i 0])
  13144. (let ([prod 0])
  13145. (begin
  13146. (while (< i n)
  13147. (begin
  13148. (set! prod (+ prod (* (vector-ref A i)
  13149. (vector-ref B i))))
  13150. (set! i (+ i 1))))
  13151. prod)))))
  13152. \end{lstlisting}
  13153. \fi}
  13154. {\if\edition\pythonEd\pythonColor
  13155. \begin{lstlisting}
  13156. A = [2, 2]
  13157. B = [3, 3]
  13158. i = 0
  13159. prod = 0
  13160. while i != len(A):
  13161. prod = prod + A[i] * B[i]
  13162. i = i + 1
  13163. print(prod)
  13164. \end{lstlisting}
  13165. \fi}
  13166. \end{tcolorbox}
  13167. \caption{Example program that computes the inner product.}
  13168. \label{fig:inner_product}
  13169. \end{figure}
  13170. {\if\edition\racketEd
  13171. %
  13172. Figure~\ref{fig:type-check-Lvecof} shows the definition of the type
  13173. checker for \LangArray{}. The result type of
  13174. \code{make-vector} is \code{(Vectorof T)}, where \code{T} is the type
  13175. of the initializing expression. The length expression is required to
  13176. have type \code{Integer}. The type checking of the operators
  13177. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  13178. updated to handle the situation in which the vector has type
  13179. \code{Vectorof}. In these cases we translate the operators to their
  13180. \code{vectorof} form so that later passes can easily distinguish
  13181. between operations on tuples versus arrays. We override the
  13182. \code{operator-types} method to provide the type signature for
  13183. multiplication: it takes two integers and returns an integer.
  13184. \fi}
  13185. %
  13186. {\if\edition\pythonEd\pythonColor
  13187. %
  13188. The type checker for \LangArray{} is defined in
  13189. figure~\ref{fig:type-check-Lvecof} and
  13190. \ref{fig:type-check-Lvecof-part2}. The result type of a list literal
  13191. is \code{list[T]}, where \code{T} is the type of the initializing
  13192. expressions. The type checking of the \code{len} function and the
  13193. subscript operator are updated to handle lists. The type checker now
  13194. also handles a subscript on the left-hand side of an assignment.
  13195. Regarding multiplication, it takes two integers and returns an
  13196. integer.
  13197. %
  13198. \fi}
  13199. \begin{figure}[tbp]
  13200. \begin{tcolorbox}[colback=white]
  13201. {\if\edition\racketEd
  13202. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13203. (define type-check-Lvecof-class
  13204. (class type-check-Lvec-class
  13205. (super-new)
  13206. (inherit check-type-equal?)
  13207. (define/override (operator-types)
  13208. (append '((* . ((Integer Integer) . Integer)))
  13209. (super operator-types)))
  13210. (define/override (type-check-exp env)
  13211. (lambda (e)
  13212. (define recur (type-check-exp env))
  13213. (match e
  13214. [(Prim 'make-vector (list e1 e2))
  13215. (define-values (e1^ t1) (recur e1))
  13216. (define-values (e2^ elt-type) (recur e2))
  13217. (define vec-type `(Vectorof ,elt-type))
  13218. (values (Prim 'make-vector (list e1^ e2^)) vec-type)]
  13219. [(Prim 'vector-ref (list e1 e2))
  13220. (define-values (e1^ t1) (recur e1))
  13221. (define-values (e2^ t2) (recur e2))
  13222. (match* (t1 t2)
  13223. [(`(Vectorof ,elt-type) 'Integer)
  13224. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  13225. [(other wise) ((super type-check-exp env) e)])]
  13226. [(Prim 'vector-set! (list e1 e2 e3) )
  13227. (define-values (e-vec t-vec) (recur e1))
  13228. (define-values (e2^ t2) (recur e2))
  13229. (define-values (e-arg^ t-arg) (recur e3))
  13230. (match t-vec
  13231. [`(Vectorof ,elt-type)
  13232. (check-type-equal? elt-type t-arg e)
  13233. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  13234. [else ((super type-check-exp env) e)])]
  13235. [(Prim 'vector-length (list e1))
  13236. (define-values (e1^ t1) (recur e1))
  13237. (match t1
  13238. [`(Vectorof ,t)
  13239. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  13240. [else ((super type-check-exp env) e)])]
  13241. [else ((super type-check-exp env) e)])))
  13242. ))
  13243. (define (type-check-Lvecof p)
  13244. (send (new type-check-Lvecof-class) type-check-program p))
  13245. \end{lstlisting}
  13246. \fi}
  13247. {\if\edition\pythonEd\pythonColor
  13248. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13249. class TypeCheckLarray(TypeCheckLtup):
  13250. def type_check_exp(self, e, env):
  13251. match e:
  13252. case ast.List(es, Load()):
  13253. ts = [self.type_check_exp(e, env) for e in es]
  13254. elt_ty = ts[0]
  13255. for (ty, elt) in zip(ts, es):
  13256. self.check_type_equal(elt_ty, ty, elt)
  13257. e.has_type = ListType(elt_ty)
  13258. return e.has_type
  13259. case Call(Name('len'), [tup]):
  13260. tup_t = self.type_check_exp(tup, env)
  13261. tup.has_type = tup_t
  13262. match tup_t:
  13263. case TupleType(ts):
  13264. return IntType()
  13265. case ListType(ty):
  13266. return IntType()
  13267. case _:
  13268. raise Exception('len expected a tuple, not ' + repr(tup_t))
  13269. case Subscript(tup, index, Load()):
  13270. tup_ty = self.type_check_exp(tup, env)
  13271. index_ty = self.type_check_exp(index, env)
  13272. self.check_type_equal(index_ty, IntType(), index)
  13273. match tup_ty:
  13274. case TupleType(ts):
  13275. match index:
  13276. case Constant(i):
  13277. return ts[i]
  13278. case _:
  13279. raise Exception('subscript required constant integer index')
  13280. case ListType(ty):
  13281. return ty
  13282. case _:
  13283. raise Exception('subscript expected a tuple, not ' + repr(tup_ty))
  13284. case BinOp(left, Mult(), right):
  13285. l = self.type_check_exp(left, env)
  13286. self.check_type_equal(l, IntType(), left)
  13287. r = self.type_check_exp(right, env)
  13288. self.check_type_equal(r, IntType(), right)
  13289. return IntType()
  13290. case _:
  13291. return super().type_check_exp(e, env)
  13292. \end{lstlisting}
  13293. \fi}
  13294. \end{tcolorbox}
  13295. \caption{Type checker for the \LangArray{} language\python{, part 1}.}
  13296. \label{fig:type-check-Lvecof}
  13297. \end{figure}
  13298. {\if\edition\pythonEd
  13299. \begin{figure}[tbp]
  13300. \begin{tcolorbox}[colback=white]
  13301. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13302. def type_check_stmts(self, ss, env):
  13303. if len(ss) == 0:
  13304. return VoidType()
  13305. match ss[0]:
  13306. case Assign([Subscript(tup, index, Store())], value):
  13307. tup_t = self.type_check_exp(tup, env)
  13308. value_t = self.type_check_exp(value, env)
  13309. index_ty = self.type_check_exp(index, env)
  13310. self.check_type_equal(index_ty, IntType(), index)
  13311. match tup_t:
  13312. case ListType(ty):
  13313. self.check_type_equal(ty, value_t, ss[0])
  13314. case TupleType(ts):
  13315. return self.type_check_stmts(ss, env)
  13316. case _:
  13317. raise Exception('type_check_stmts: '
  13318. 'expected tuple or list, not ' + repr(tup_t))
  13319. return self.type_check_stmts(ss[1:], env)
  13320. case _:
  13321. return super().type_check_stmts(ss, env)
  13322. \end{lstlisting}
  13323. \end{tcolorbox}
  13324. \caption{Type checker for the \LangArray{} language, part 2.}
  13325. \label{fig:type-check-Lvecof-part2}
  13326. \end{figure}
  13327. \fi}
  13328. The definition of the interpreter for \LangArray{} is shown in
  13329. \racket{figure~\ref{fig:interp-Lvecof}}
  13330. \python{figure~\ref{fig:interp-Lvecof}}.
  13331. \racket{The \code{make-vector} operator is
  13332. interpreted using Racket's \code{make-vector} function,
  13333. and multiplication is interpreted using \code{fx*},
  13334. which is multiplication for \code{fixnum} integers.
  13335. In the \code{resolve} pass (section~\ref{sec:array-resolution})
  13336. we translate array access operations
  13337. into \code{vectorof-ref} and \code{vectorof-set!} operations,
  13338. which we interpret using \code{vector} operations with additional
  13339. bounds checks that signal a \code{trapped-error}.
  13340. }
  13341. %
  13342. \python{We implement array creation with a Python list comprehension,
  13343. and multiplication is implemented with 64-bit multiplication. We
  13344. add a case to handle a subscript on the left-hand side of
  13345. assignment. Other uses of subscript can be handled by the existing
  13346. code for tuples.}
  13347. \begin{figure}[tbp]
  13348. \begin{tcolorbox}[colback=white]
  13349. {\if\edition\racketEd
  13350. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13351. (define interp-Lvecof-class
  13352. (class interp-Lvec-class
  13353. (super-new)
  13354. (define/override (interp-op op)
  13355. (match op
  13356. ['make-vector make-vector]
  13357. ['vectorof-length vector-length]
  13358. ['vectorof-ref
  13359. (lambda (v i)
  13360. (if (< i (vector-length v))
  13361. (vector-ref v i)
  13362. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13363. ['vectorof-set!
  13364. (lambda (v i e)
  13365. (if (< i (vector-length v))
  13366. (vector-set! v i e)
  13367. (error 'trapped-error "index ~a out of bounds\nin ~v" i v)))]
  13368. [else (super interp-op op)]))
  13369. ))
  13370. (define (interp-Lvecof p)
  13371. (send (new interp-Lvecof-class) interp-program p))
  13372. \end{lstlisting}
  13373. \fi}
  13374. {\if\edition\pythonEd\pythonColor
  13375. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13376. class InterpLarray(InterpLtup):
  13377. def interp_exp(self, e, env):
  13378. match e:
  13379. case ast.List(es, Load()):
  13380. return [self.interp_exp(e, env) for e in es]
  13381. case BinOp(left, Mult(), right):
  13382. l = self.interp_exp(left, env)
  13383. r = self.interp_exp(right, env)
  13384. return mul64(l, r)
  13385. case Subscript(tup, index, Load()):
  13386. t = self.interp_exp(tup, env)
  13387. n = self.interp_exp(index, env)
  13388. if n < len(t):
  13389. return t[n]
  13390. else:
  13391. raise TrappedError('array index out of bounds')
  13392. case _:
  13393. return super().interp_exp(e, env)
  13394. def interp_stmt(self, s, env, cont):
  13395. match s:
  13396. case Assign([Subscript(tup, index)], value):
  13397. t = self.interp_exp(tup, env)
  13398. n = self.interp_exp(index, env)
  13399. if n < len(t):
  13400. t[n] = self.interp_exp(value, env)
  13401. else:
  13402. raise TrappedError('array index out of bounds')
  13403. return self.interp_stmts(cont, env)
  13404. case _:
  13405. return super().interp_stmt(s, env, cont)
  13406. \end{lstlisting}
  13407. \fi}
  13408. \end{tcolorbox}
  13409. \caption{Interpreter for \LangArray{}.}
  13410. \label{fig:interp-Lvecof}
  13411. \end{figure}
  13412. \subsection{Data Representation}
  13413. \label{sec:array-rep}
  13414. Just as with tuples, we store arrays on the heap, which means that the
  13415. garbage collector will need to inspect arrays. An immediate thought is
  13416. to use the same representation for arrays that we use for tuples.
  13417. However, we limit tuples to a length of fifty so that their length and
  13418. pointer mask can fit into the 64-bit tag at the beginning of each
  13419. tuple (section~\ref{sec:data-rep-gc}). We intend arrays to allow
  13420. millions of elements, so we need more bits to store the length.
  13421. However, because arrays are homogeneous, we need only 1 bit for the
  13422. pointer mask instead of 1 bit per array element. Finally, the
  13423. garbage collector must be able to distinguish between tuples
  13424. and arrays, so we need to reserve one bit for that purpose. We
  13425. arrive at the following layout for the 64-bit tag at the beginning of
  13426. an array:
  13427. \begin{itemize}
  13428. \item The right-most bit is the forwarding bit, just as in a tuple.
  13429. A $0$ indicates that it is a forwarding pointer, and a $1$ indicates
  13430. that it is not.
  13431. \item The next bit to the left is the pointer mask. A $0$ indicates
  13432. that none of the elements are pointers, and a $1$ indicates that all
  13433. the elements are pointers.
  13434. \item The next $60$ bits store the length of the array.
  13435. \item The bit at position $62$ distinguishes between a tuple ($0$)
  13436. and an array ($1$).
  13437. \item The left-most bit is reserved as explained in
  13438. chapter~\ref{ch:Lgrad}.
  13439. \end{itemize}
  13440. %% Recall that in chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  13441. %% differentiate the kinds of values that have been injected into the
  13442. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  13443. %% to indicate that the value is an array.
  13444. In the following subsections we provide hints regarding how to update
  13445. the passes to handle arrays.
  13446. \subsection{Overload Resolution}
  13447. \label{sec:array-resolution}
  13448. As noted previously, with the addition of arrays, several operators
  13449. have become \emph{overloaded}; that is, they can be applied to values
  13450. of more than one type. In this case, the element access and length
  13451. operators can be applied to both tuples and arrays. This kind of
  13452. overloading is quite common in programming languages, so many
  13453. compilers perform \emph{overload resolution}\index{subject}{overload
  13454. resolution} to handle it. The idea is to translate each overloaded
  13455. operator into different operators for the different types.
  13456. Implement a new pass named \code{resolve}.
  13457. Translate the reading of an array element to
  13458. \racket{\code{vectorof-ref}}\python{\code{array\_load}}
  13459. and the writing of an array element to
  13460. \racket{\code{vectorof-set!}}\python{\code{array\_store}}
  13461. Translate calls to \racket{\code{vector-length}}\python{\code{len}}
  13462. into \racket{\code{vectorof-length}}\python{\code{array\_len}}.
  13463. When these operators are applied to tuples, leave them as is.
  13464. %
  13465. \python{The type checker for \LangArray{} adds a \code{has\_type}
  13466. field, which can be inspected to determine whether the operator
  13467. is applied to a tuple or an array.}
  13468. \subsection{Bounds Checking}
  13469. Recall that the interpreter for \LangArray{} signals a
  13470. \racket{\code{trapped-error}}\python{\code{TrappedError}}
  13471. when there is an array access that is out of
  13472. bounds. Therefore your compiler is obliged to also catch these errors
  13473. during execution and halt, signaling an error. We recommend inserting
  13474. a new pass named \code{check\_bounds} that inserts code around each
  13475. \racket{\code{vectorof-ref} and \code{vectorof-set!}}
  13476. \python{subscript} operation to ensure that the index is greater than
  13477. or equal to zero and less than the array's length. If not, the program
  13478. should halt, for which we recommend using a new primitive operation
  13479. named \code{exit}.
  13480. %% \subsection{Reveal Casts}
  13481. %% The array-access operators \code{vectorof-ref} and
  13482. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  13483. %% \code{any-vector-set!} operators of chapter~\ref{ch:Ldyn} in
  13484. %% that the type checker cannot tell whether the index will be in bounds,
  13485. %% so the bounds check must be performed at run time. Recall that the
  13486. %% \code{reveal-casts} pass (section~\ref{sec:reveal-casts-Rany}) wraps
  13487. %% an \code{If} around a vector reference for update to check whether
  13488. %% the index is less than the length. You should do the same for
  13489. %% \code{vectorof-ref} and \code{vectorof-set!} .
  13490. %% In addition, the handling of the \code{any-vector} operators in
  13491. %% \code{reveal-casts} needs to be updated to account for arrays that are
  13492. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  13493. %% generated code should test whether the tag is for tuples (\code{010})
  13494. %% or arrays (\code{110}) and then dispatch to either
  13495. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  13496. %% we add a case in \code{select\_instructions} to generate the
  13497. %% appropriate instructions for accessing the array length from the
  13498. %% header of an array.
  13499. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  13500. %% the generated code needs to check that the index is less than the
  13501. %% vector length, so like the code for \code{any-vector-length}, check
  13502. %% the tag to determine whether to use \code{any-vector-length} or
  13503. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  13504. %% is complete, the generated code can use \code{any-vector-ref} and
  13505. %% \code{any-vector-set!} for both tuples and arrays because the
  13506. %% instructions used for those operators do not look at the tag at the
  13507. %% front of the tuple or array.
  13508. \subsection{Expose Allocation}
  13509. This pass should translate array creation into lower-level
  13510. operations. In particular, the new AST node \ALLOCARRAY{\Exp}{\Type}
  13511. is analogous to the \code{Allocate} AST node for tuples. The $\Type$
  13512. argument must be \ARRAYTY{T}, where $T$ is the element type for the
  13513. array. The \code{AllocateArray} AST node allocates an array of the
  13514. length specified by the $\Exp$ (of type \INTTY), but does not
  13515. initialize the elements of the array. Generate code in this pass to
  13516. initialize the elements analogous to the case for tuples.
  13517. {\if\edition\racketEd
  13518. \subsection{Uncover \texttt{get!}}
  13519. \label{sec:uncover-get-bang-vecof}
  13520. Add cases for \code{AllocateArray} to \code{collect-set!} and
  13521. \code{uncover-get!-exp}.
  13522. \fi}
  13523. \subsection{Remove Complex Operands}
  13524. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  13525. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  13526. complex, and its subexpression must be atomic.
  13527. \subsection{Explicate Control}
  13528. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  13529. \code{explicate\_assign}.
  13530. \subsection{Select Instructions}
  13531. \index{subject}{select instructions}
  13532. Generate instructions for \code{AllocateArray} similar to those for
  13533. \code{Allocate} given in section~\ref{sec:select-instructions-gc}
  13534. except that the tag at the front of the array should instead use the
  13535. representation discussed in section~\ref{sec:array-rep}.
  13536. Regarding \racket{\code{vectorof-length}}\python{\code{array\_len}},
  13537. extract the length from the tag.
  13538. The instructions generated for accessing an element of an array differ
  13539. from those for a tuple (section~\ref{sec:select-instructions-gc}) in
  13540. that the index is not a constant so you need to generate instructions
  13541. that compute the offset at runtime.
  13542. Compile the \code{exit} primitive into a call to the \code{exit}
  13543. function of the C standard library, with an argument of $255$.
  13544. %% Also, note that assignment to an array element may appear in
  13545. %% as a stand-alone statement, so make sure to handle that situation in
  13546. %% this pass.
  13547. %% Finally, the instructions for \code{any-vectorof-length} should be
  13548. %% similar to those for \code{vectorof-length}, except that one must
  13549. %% first project the array by writing zeroes into the $3$-bit tag
  13550. \begin{exercise}\normalfont\normalsize
  13551. Implement a compiler for the \LangArray{} language by extending your
  13552. compiler for \LangLoop{}. Test your compiler on a half dozen new
  13553. programs, including the one shown in figure~\ref{fig:inner_product}
  13554. and also a program that multiplies two matrices. Note that although
  13555. matrices are two-dimensional arrays, they can be encoded into
  13556. one-dimensional arrays by laying out each row in the array, one after
  13557. the next.
  13558. \end{exercise}
  13559. {\if\edition\racketEd
  13560. \section{Challenge: Generational Collection}
  13561. The copying collector described in section~\ref{sec:GC} can incur
  13562. significant runtime overhead because the call to \code{collect} takes
  13563. time proportional to all the live data. One way to reduce this
  13564. overhead is to reduce how much data is inspected in each call to
  13565. \code{collect}. In particular, researchers have observed that recently
  13566. allocated data is more likely to become garbage then data that has
  13567. survived one or more previous calls to \code{collect}. This insight
  13568. motivated the creation of \emph{generational garbage collectors}
  13569. \index{subject}{generational garbage collector} that
  13570. (1) segregate data according to its age into two or more generations;
  13571. (2) allocate less space for younger generations, so collecting them is
  13572. faster, and more space for the older generations; and (3) perform
  13573. collection on the younger generations more frequently than on older
  13574. generations~\citep{Wilson:1992fk}.
  13575. For this challenge assignment, the goal is to adapt the copying
  13576. collector implemented in \code{runtime.c} to use two generations, one
  13577. for young data and one for old data. Each generation consists of a
  13578. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  13579. \code{collect} function to use the two generations:
  13580. \begin{enumerate}
  13581. \item Copy the young generation's FromSpace to its ToSpace and then
  13582. switch the role of the ToSpace and FromSpace.
  13583. \item If there is enough space for the requested number of bytes in
  13584. the young FromSpace, then return from \code{collect}.
  13585. \item If there is not enough space in the young FromSpace for the
  13586. requested bytes, then move the data from the young generation to the
  13587. old one with the following steps:
  13588. \begin{enumerate}
  13589. \item[a.] If there is enough room in the old FromSpace, copy the young
  13590. FromSpace to the old FromSpace and then return.
  13591. \item[b.] If there is not enough room in the old FromSpace, then collect
  13592. the old generation by copying the old FromSpace to the old ToSpace
  13593. and swap the roles of the old FromSpace and ToSpace.
  13594. \item[c.] If there is enough room now, copy the young FromSpace to the
  13595. old FromSpace and return. Otherwise, allocate a larger FromSpace
  13596. and ToSpace for the old generation. Copy the young FromSpace and
  13597. the old FromSpace into the larger FromSpace for the old
  13598. generation and then return.
  13599. \end{enumerate}
  13600. \end{enumerate}
  13601. We recommend that you generalize the \code{cheney} function so that it
  13602. can be used for all the copies mentioned: between the young FromSpace
  13603. and ToSpace, between the old FromSpace and ToSpace, and between the
  13604. young FromSpace and old FromSpace. This can be accomplished by adding
  13605. parameters to \code{cheney} that replace its use of the global
  13606. variables \code{fromspace\_begin}, \code{fromspace\_end},
  13607. \code{tospace\_begin}, and \code{tospace\_end}.
  13608. Note that the collection of the young generation does not traverse the
  13609. old generation. This introduces a potential problem: there may be
  13610. young data that is reachable only through pointers in the old
  13611. generation. If these pointers are not taken into account, the
  13612. collector could throw away young data that is live! One solution,
  13613. called \emph{pointer recording}, is to maintain a set of all the
  13614. pointers from the old generation into the new generation and consider
  13615. this set as part of the root set. To maintain this set, the compiler
  13616. must insert extra instructions around every \code{vector-set!}. If the
  13617. vector being modified is in the old generation, and if the value being
  13618. written is a pointer into the new generation, then that pointer must
  13619. be added to the set. Also, if the value being overwritten was a
  13620. pointer into the new generation, then that pointer should be removed
  13621. from the set.
  13622. \begin{exercise}\normalfont\normalsize
  13623. Adapt the \code{collect} function in \code{runtime.c} to implement
  13624. generational garbage collection, as outlined in this section.
  13625. Update the code generation for \code{vector-set!} to implement
  13626. pointer recording. Make sure that your new compiler and runtime
  13627. execute without error on your test suite.
  13628. \end{exercise}
  13629. \fi}
  13630. \section{Further Reading}
  13631. \citet{Appel90} describes many data representation approaches
  13632. including the ones used in the compilation of Standard ML.
  13633. There are many alternatives to copying collectors (and their bigger
  13634. siblings, the generational collectors) with regard to garbage
  13635. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  13636. reference counting~\citep{Collins:1960aa}. The strengths of copying
  13637. collectors are that allocation is fast (just a comparison and pointer
  13638. increment), there is no fragmentation, cyclic garbage is collected,
  13639. and the time complexity of collection depends only on the amount of
  13640. live data and not on the amount of garbage~\citep{Wilson:1992fk}. The
  13641. main disadvantages of a two-space copying collector is that it uses a
  13642. lot of extra space and takes a long time to perform the copy, though
  13643. these problems are ameliorated in generational collectors.
  13644. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  13645. small objects and generate a lot of garbage, so copying and
  13646. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  13647. Garbage collection is an active research topic, especially concurrent
  13648. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  13649. developing new techniques and revisiting old
  13650. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  13651. meet every year at the International Symposium on Memory Management to
  13652. present these findings.
  13653. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13654. \chapter{Functions}
  13655. \label{ch:Lfun}
  13656. \index{subject}{function}
  13657. \setcounter{footnote}{0}
  13658. This chapter studies the compilation of a subset of \racket{Typed
  13659. Racket}\python{Python} in which only top-level function definitions
  13660. are allowed. This kind of function appears in the C programming
  13661. language, and it serves as an important stepping-stone to implementing
  13662. lexically scoped functions in the form of \key{lambda}\index{subject}{lambda}
  13663. abstractions, which is the topic of chapter~\ref{ch:Llambda}.
  13664. \section{The \LangFun{} Language}
  13665. The concrete syntax and abstract syntax for function definitions and
  13666. function application are shown in
  13667. figures~\ref{fig:Lfun-concrete-syntax} and \ref{fig:Lfun-syntax}, with
  13668. which we define the \LangFun{} language. Programs in \LangFun{} begin
  13669. with zero or more function definitions. The function names from these
  13670. definitions are in scope for the entire program, including all the
  13671. function definitions, and therefore the ordering of function
  13672. definitions does not matter.
  13673. %
  13674. \python{The abstract syntax for function parameters in
  13675. figure~\ref{fig:Lfun-syntax} is a list of pairs, each of which
  13676. consists of a parameter name and its type. This design differs from
  13677. Python's \code{ast} module, which has a more complex structure for
  13678. function parameters to handle keyword parameters,
  13679. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  13680. complex Python abstract syntax into the simpler syntax shown in
  13681. figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  13682. \code{FunctionDef} constructor are for decorators and a type
  13683. comment, neither of which are used by our compiler. We recommend
  13684. replacing them with \code{None} in the \code{shrink} pass.
  13685. }
  13686. %
  13687. The concrete syntax for function application
  13688. \index{subject}{function application}
  13689. is \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}\racket{$\CAPPLY{\Exp}{\Exp \ldots}$},
  13690. where the first expression
  13691. must evaluate to a function and the remaining expressions are the arguments. The
  13692. abstract syntax for function application is
  13693. $\APPLY{\Exp}{\Exp^*}$.
  13694. %% The syntax for function application does not include an explicit
  13695. %% keyword, which is error prone when using \code{match}. To alleviate
  13696. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  13697. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  13698. Functions are first-class in the sense that a function pointer
  13699. \index{subject}{function pointer} is data and can be stored in memory or passed
  13700. as a parameter to another function. Thus, there is a function
  13701. type, written
  13702. {\if\edition\racketEd
  13703. \begin{lstlisting}
  13704. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  13705. \end{lstlisting}
  13706. \fi}
  13707. {\if\edition\pythonEd\pythonColor
  13708. \begin{lstlisting}
  13709. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  13710. \end{lstlisting}
  13711. \fi}
  13712. %
  13713. \noindent for a function whose $n$ parameters have the types $\Type_1$
  13714. through $\Type_n$ and whose return type is $\Type_R$. The main
  13715. limitation of these functions (with respect to
  13716. \racket{Racket}\python{Python} functions) is that they are not
  13717. lexically scoped. That is, the only external entities that can be
  13718. referenced from inside a function body are other globally defined
  13719. functions. The syntax of \LangFun{} prevents function definitions from
  13720. being nested inside each other.
  13721. \newcommand{\LfunGrammarRacket}{
  13722. \begin{array}{lcl}
  13723. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13724. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  13725. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  13726. \end{array}
  13727. }
  13728. \newcommand{\LfunASTRacket}{
  13729. \begin{array}{lcl}
  13730. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  13731. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  13732. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  13733. \end{array}
  13734. }
  13735. \newcommand{\LfunGrammarPython}{
  13736. \begin{array}{lcl}
  13737. \Type &::=& \key{int}
  13738. \MID \key{bool} \MID \key{void}
  13739. \MID \key{tuple}\LS \Type^+ \RS
  13740. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  13741. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  13742. \Stmt &::=& \CRETURN{\Exp} \\
  13743. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  13744. \end{array}
  13745. }
  13746. \newcommand{\LfunASTPython}{
  13747. \begin{array}{lcl}
  13748. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  13749. \MID \key{TupleType}\LS\Type^+\RS\\
  13750. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  13751. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  13752. \Stmt &::=& \RETURN{\Exp} \\
  13753. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  13754. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  13755. \end{array}
  13756. }
  13757. \begin{figure}[tp]
  13758. \centering
  13759. \begin{tcolorbox}[colback=white]
  13760. \small
  13761. {\if\edition\racketEd
  13762. \[
  13763. \begin{array}{l}
  13764. \gray{\LintGrammarRacket{}} \\ \hline
  13765. \gray{\LvarGrammarRacket{}} \\ \hline
  13766. \gray{\LifGrammarRacket{}} \\ \hline
  13767. \gray{\LwhileGrammarRacket} \\ \hline
  13768. \gray{\LtupGrammarRacket} \\ \hline
  13769. \LfunGrammarRacket \\
  13770. \begin{array}{lcl}
  13771. \LangFunM{} &::=& \Def \ldots \; \Exp
  13772. \end{array}
  13773. \end{array}
  13774. \]
  13775. \fi}
  13776. {\if\edition\pythonEd\pythonColor
  13777. \[
  13778. \begin{array}{l}
  13779. \gray{\LintGrammarPython{}} \\ \hline
  13780. \gray{\LvarGrammarPython{}} \\ \hline
  13781. \gray{\LifGrammarPython{}} \\ \hline
  13782. \gray{\LwhileGrammarPython} \\ \hline
  13783. \gray{\LtupGrammarPython} \\ \hline
  13784. \LfunGrammarPython \\
  13785. \begin{array}{rcl}
  13786. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13787. \end{array}
  13788. \end{array}
  13789. \]
  13790. \fi}
  13791. \end{tcolorbox}
  13792. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  13793. \label{fig:Lfun-concrete-syntax}
  13794. \end{figure}
  13795. \begin{figure}[tp]
  13796. \centering
  13797. \begin{tcolorbox}[colback=white]
  13798. \small
  13799. {\if\edition\racketEd
  13800. \[
  13801. \begin{array}{l}
  13802. \gray{\LintOpAST} \\ \hline
  13803. \gray{\LvarASTRacket{}} \\ \hline
  13804. \gray{\LifASTRacket{}} \\ \hline
  13805. \gray{\LwhileASTRacket{}} \\ \hline
  13806. \gray{\LtupASTRacket{}} \\ \hline
  13807. \LfunASTRacket \\
  13808. \begin{array}{lcl}
  13809. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  13810. \end{array}
  13811. \end{array}
  13812. \]
  13813. \fi}
  13814. {\if\edition\pythonEd\pythonColor
  13815. \[
  13816. \begin{array}{l}
  13817. \gray{\LintASTPython{}} \\ \hline
  13818. \gray{\LvarASTPython{}} \\ \hline
  13819. \gray{\LifASTPython{}} \\ \hline
  13820. \gray{\LwhileASTPython} \\ \hline
  13821. \gray{\LtupASTPython} \\ \hline
  13822. \LfunASTPython \\
  13823. \begin{array}{rcl}
  13824. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13825. \end{array}
  13826. \end{array}
  13827. \]
  13828. \fi}
  13829. \end{tcolorbox}
  13830. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  13831. \label{fig:Lfun-syntax}
  13832. \end{figure}
  13833. The program shown in figure~\ref{fig:Lfun-function-example} is a
  13834. representative example of defining and using functions in \LangFun{}.
  13835. We define a function \code{map} that applies some other function
  13836. \code{f} to both elements of a tuple and returns a new tuple
  13837. containing the results. We also define a function \code{inc}. The
  13838. program applies \code{map} to \code{inc} and
  13839. %
  13840. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  13841. %
  13842. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  13843. %
  13844. from which we return \code{42}.
  13845. \begin{figure}[tbp]
  13846. \begin{tcolorbox}[colback=white]
  13847. {\if\edition\racketEd
  13848. \begin{lstlisting}
  13849. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  13850. : (Vector Integer Integer)
  13851. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  13852. (define (inc [x : Integer]) : Integer
  13853. (+ x 1))
  13854. (vector-ref (map inc (vector 0 41)) 1)
  13855. \end{lstlisting}
  13856. \fi}
  13857. {\if\edition\pythonEd\pythonColor
  13858. \begin{lstlisting}
  13859. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  13860. return f(v[0]), f(v[1])
  13861. def inc(x : int) -> int:
  13862. return x + 1
  13863. print(map(inc, (0, 41))[1])
  13864. \end{lstlisting}
  13865. \fi}
  13866. \end{tcolorbox}
  13867. \caption{Example of using functions in \LangFun{}.}
  13868. \label{fig:Lfun-function-example}
  13869. \end{figure}
  13870. The definitional interpreter for \LangFun{} is shown in
  13871. figure~\ref{fig:interp-Lfun}. The case for the
  13872. %
  13873. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13874. %
  13875. AST is responsible for setting up the mutual recursion between the
  13876. top-level function definitions.
  13877. %
  13878. \racket{We use the classic back-patching
  13879. \index{subject}{back-patching} approach that uses mutable variables
  13880. and makes two passes over the function
  13881. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  13882. top-level environment using a mutable cons cell for each function
  13883. definition. Note that the \code{lambda}\index{subject}{lambda} value
  13884. for each function is incomplete; it does not yet include the environment.
  13885. Once the top-level environment has been constructed, we iterate over it and
  13886. update the \code{lambda} values to use the top-level environment.}
  13887. %
  13888. \python{We create a dictionary named \code{env} and fill it in
  13889. by mapping each function name to a new \code{Function} value,
  13890. each of which stores a reference to the \code{env}.
  13891. (We define the class \code{Function} for this purpose.)}
  13892. %
  13893. To interpret a function \racket{application}\python{call}, we match
  13894. the result of the function expression to obtain a function value. We
  13895. then extend the function's environment with the mapping of parameters to
  13896. argument values. Finally, we interpret the body of the function in
  13897. this extended environment.
  13898. \begin{figure}[tp]
  13899. \begin{tcolorbox}[colback=white]
  13900. {\if\edition\racketEd
  13901. \begin{lstlisting}
  13902. (define interp-Lfun-class
  13903. (class interp-Lvec-class
  13904. (super-new)
  13905. (define/override ((interp-exp env) e)
  13906. (define recur (interp-exp env))
  13907. (match e
  13908. [(Apply fun args)
  13909. (define fun-val (recur fun))
  13910. (define arg-vals (for/list ([e args]) (recur e)))
  13911. (match fun-val
  13912. [`(function (,xs ...) ,body ,fun-env)
  13913. (define params-args (for/list ([x xs] [arg arg-vals])
  13914. (cons x (box arg))))
  13915. (define new-env (append params-args fun-env))
  13916. ((interp-exp new-env) body)]
  13917. [else
  13918. (error 'interp-exp "expected function, not ~a" fun-val)])]
  13919. [else ((super interp-exp env) e)]
  13920. ))
  13921. (define/public (interp-def d)
  13922. (match d
  13923. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  13924. (cons f (box `(function ,xs ,body ())))]))
  13925. (define/override (interp-program p)
  13926. (match p
  13927. [(ProgramDefsExp info ds body)
  13928. (let ([top-level (for/list ([d ds]) (interp-def d))])
  13929. (for/list ([f (in-dict-values top-level)])
  13930. (set-box! f (match (unbox f)
  13931. [`(function ,xs ,body ())
  13932. `(function ,xs ,body ,top-level)])))
  13933. ((interp-exp top-level) body))]))
  13934. ))
  13935. (define (interp-Lfun p)
  13936. (send (new interp-Lfun-class) interp-program p))
  13937. \end{lstlisting}
  13938. \fi}
  13939. {\if\edition\pythonEd\pythonColor
  13940. \begin{lstlisting}
  13941. class InterpLfun(InterpLtup):
  13942. def apply_fun(self, fun, args, e):
  13943. match fun:
  13944. case Function(name, xs, body, env):
  13945. new_env = env.copy().update(zip(xs, args))
  13946. return self.interp_stmts(body, new_env)
  13947. case _:
  13948. raise Exception('apply_fun: unexpected: ' + repr(fun))
  13949. def interp_exp(self, e, env):
  13950. match e:
  13951. case Call(Name('input_int'), []):
  13952. return super().interp_exp(e, env)
  13953. case Call(func, args):
  13954. f = self.interp_exp(func, env)
  13955. vs = [self.interp_exp(arg, env) for arg in args]
  13956. return self.apply_fun(f, vs, e)
  13957. case _:
  13958. return super().interp_exp(e, env)
  13959. def interp_stmt(self, s, env, cont):
  13960. match s:
  13961. case Return(value):
  13962. return self.interp_exp(value, env)
  13963. case FunctionDef(name, params, bod, dl, returns, comment):
  13964. if isinstance(params, ast.arguments):
  13965. ps = [p.arg for p in params.args]
  13966. else:
  13967. ps = [x for (x,t) in params]
  13968. env[name] = Function(name, ps, bod, env)
  13969. return self.interp_stmts(cont, env)
  13970. case _:
  13971. return super().interp_stmt(s, env, cont)
  13972. def interp(self, p):
  13973. match p:
  13974. case Module(ss):
  13975. env = {}
  13976. self.interp_stmts(ss, env)
  13977. if 'main' in env.keys():
  13978. self.apply_fun(env['main'], [], None)
  13979. case _:
  13980. raise Exception('interp: unexpected ' + repr(p))
  13981. \end{lstlisting}
  13982. \fi}
  13983. \end{tcolorbox}
  13984. \caption{Interpreter for the \LangFun{} language.}
  13985. \label{fig:interp-Lfun}
  13986. \end{figure}
  13987. %\margincomment{TODO: explain type checker}
  13988. The type checker for \LangFun{} is shown in
  13989. figure~\ref{fig:type-check-Lfun}.
  13990. %
  13991. \python{(We omit the code that parses function parameters into the
  13992. simpler abstract syntax.)}
  13993. %
  13994. Similarly to the interpreter, the case for the
  13995. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  13996. %
  13997. AST is responsible for setting up the mutual recursion between the
  13998. top-level function definitions. We begin by creating a mapping
  13999. \code{env} from every function name to its type. We then type check
  14000. the program using this mapping.
  14001. %
  14002. \python{To check a function definition, we copy and extend the
  14003. \code{env} with the parameters of the function. We then type check
  14004. the body of the function and obtain the actual return type
  14005. \code{rt}, which is either the type of the expression in a
  14006. \code{return} statement, or the \code{VoidType} if control reaches
  14007. the end of the function without a \code{return} statement. (If
  14008. there are multiple \code{return} statements, the types of their
  14009. expressions must agree.) Finally we check that the actual return
  14010. type \code{rt} is equal to the declared return type \code{returns}.}
  14011. %
  14012. To check a function \racket{application}\python{call}, we match
  14013. the type of the function expression to a function type and check that
  14014. the types of the argument expressions are equal to the function's
  14015. parameter types. The type of the \racket{application}\python{call} as
  14016. a whole is the return type from the function type.
  14017. \begin{figure}[tp]
  14018. \begin{tcolorbox}[colback=white]
  14019. {\if\edition\racketEd
  14020. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14021. (define type-check-Lfun-class
  14022. (class type-check-Lvec-class
  14023. (super-new)
  14024. (inherit check-type-equal?)
  14025. (define/public (type-check-apply env e es)
  14026. (define-values (e^ ty) ((type-check-exp env) e))
  14027. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  14028. ((type-check-exp env) e)))
  14029. (match ty
  14030. [`(,ty^* ... -> ,rt)
  14031. (for ([arg-ty ty*] [param-ty ty^*])
  14032. (check-type-equal? arg-ty param-ty (Apply e es)))
  14033. (values e^ e* rt)]))
  14034. (define/override (type-check-exp env)
  14035. (lambda (e)
  14036. (match e
  14037. [(FunRef f n)
  14038. (values (FunRef f n) (dict-ref env f))]
  14039. [(Apply e es)
  14040. (define-values (e^ es^ rt) (type-check-apply env e es))
  14041. (values (Apply e^ es^) rt)]
  14042. [(Call e es)
  14043. (define-values (e^ es^ rt) (type-check-apply env e es))
  14044. (values (Call e^ es^) rt)]
  14045. [else ((super type-check-exp env) e)])))
  14046. (define/public (type-check-def env)
  14047. (lambda (e)
  14048. (match e
  14049. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  14050. (define new-env (append (map cons xs ps) env))
  14051. (define-values (body^ ty^) ((type-check-exp new-env) body))
  14052. (check-type-equal? ty^ rt body)
  14053. (Def f p:t* rt info body^)])))
  14054. (define/public (fun-def-type d)
  14055. (match d
  14056. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  14057. (define/override (type-check-program e)
  14058. (match e
  14059. [(ProgramDefsExp info ds body)
  14060. (define env (for/list ([d ds])
  14061. (cons (Def-name d) (fun-def-type d))))
  14062. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  14063. (define-values (body^ ty) ((type-check-exp env) body))
  14064. (check-type-equal? ty 'Integer body)
  14065. (ProgramDefsExp info ds^ body^)]))))
  14066. (define (type-check-Lfun p)
  14067. (send (new type-check-Lfun-class) type-check-program p))
  14068. \end{lstlisting}
  14069. \fi}
  14070. {\if\edition\pythonEd\pythonColor
  14071. \begin{lstlisting}
  14072. class TypeCheckLfun(TypeCheckLtup):
  14073. def type_check_exp(self, e, env):
  14074. match e:
  14075. case Call(Name('input_int'), []):
  14076. return super().type_check_exp(e, env)
  14077. case Call(func, args):
  14078. func_t = self.type_check_exp(func, env)
  14079. args_t = [self.type_check_exp(arg, env) for arg in args]
  14080. match func_t:
  14081. case FunctionType(params_t, return_t):
  14082. for (arg_t, param_t) in zip(args_t, params_t):
  14083. check_type_equal(param_t, arg_t, e)
  14084. return return_t
  14085. case _:
  14086. raise Exception('type_check_exp: in call, unexpected ' +
  14087. repr(func_t))
  14088. case _:
  14089. return super().type_check_exp(e, env)
  14090. def type_check_stmts(self, ss, env):
  14091. if len(ss) == 0:
  14092. return VoidType()
  14093. match ss[0]:
  14094. case FunctionDef(name, params, body, dl, returns, comment):
  14095. new_env = env.copy().update(params)
  14096. rt = self.type_check_stmts(body, new_env)
  14097. check_type_equal(returns, rt, ss[0])
  14098. return self.type_check_stmts(ss[1:], env)
  14099. case Return(value):
  14100. return self.type_check_exp(value, env)
  14101. case _:
  14102. return super().type_check_stmts(ss, env)
  14103. def type_check(self, p):
  14104. match p:
  14105. case Module(body):
  14106. env = {}
  14107. for s in body:
  14108. match s:
  14109. case FunctionDef(name, params, bod, dl, returns, comment):
  14110. if name in env:
  14111. raise Exception('type_check: function ' +
  14112. repr(name) + ' defined twice')
  14113. params_t = [t for (x,t) in params]
  14114. env[name] = FunctionType(params_t, returns)
  14115. self.type_check_stmts(body, env)
  14116. case _:
  14117. raise Exception('type_check: unexpected ' + repr(p))
  14118. \end{lstlisting}
  14119. \fi}
  14120. \end{tcolorbox}
  14121. \caption{Type checker for the \LangFun{} language.}
  14122. \label{fig:type-check-Lfun}
  14123. \end{figure}
  14124. \clearpage
  14125. \section{Functions in x86}
  14126. \label{sec:fun-x86}
  14127. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  14128. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  14129. %% \margincomment{\tiny Talk about the return address on the
  14130. %% stack and what callq and retq does.\\ --Jeremy }
  14131. The x86 architecture provides a few features to support the
  14132. implementation of functions. We have already seen that there are
  14133. labels in x86 so that one can refer to the location of an instruction,
  14134. as is needed for jump instructions. Labels can also be used to mark
  14135. the beginning of the instructions for a function. Going further, we
  14136. can obtain the address of a label by using the \key{leaq}
  14137. instruction. For example, the following puts the address of the
  14138. \code{inc} label into the \code{rbx} register:
  14139. \begin{lstlisting}
  14140. leaq inc(%rip), %rbx
  14141. \end{lstlisting}
  14142. Recall from section~\ref{sec:select-instructions-gc} that
  14143. \verb!inc(%rip)! is an example of instruction-pointer-relative
  14144. addressing.
  14145. In section~\ref{sec:x86} we used the \code{callq} instruction to jump
  14146. to functions whose locations were given by a label, such as
  14147. \code{read\_int}. To support function calls in this chapter we instead
  14148. jump to functions whose location are given by an address in
  14149. a register; that is, we use \emph{indirect function calls}. The
  14150. x86 syntax for this is a \code{callq} instruction that requires an asterisk
  14151. before the register name.\index{subject}{indirect function call}
  14152. \begin{lstlisting}
  14153. callq *%rbx
  14154. \end{lstlisting}
  14155. \subsection{Calling Conventions}
  14156. \label{sec:calling-conventions-fun}
  14157. \index{subject}{calling conventions}
  14158. The \code{callq} instruction provides partial support for implementing
  14159. functions: it pushes the return address on the stack and it jumps to
  14160. the target. However, \code{callq} does not handle
  14161. \begin{enumerate}
  14162. \item parameter passing,
  14163. \item pushing frames on the procedure call stack and popping them off,
  14164. or
  14165. \item determining how registers are shared by different functions.
  14166. \end{enumerate}
  14167. Regarding parameter passing, recall that the x86-64 calling
  14168. convention for Unix-based systems uses the following six registers to
  14169. pass arguments to a function, in the given order:
  14170. \begin{lstlisting}
  14171. rdi rsi rdx rcx r8 r9
  14172. \end{lstlisting}
  14173. If there are more than six arguments, then the calling convention
  14174. mandates using space on the frame of the caller for the rest of the
  14175. arguments. However, to ease the implementation of efficient tail calls
  14176. (section~\ref{sec:tail-call}), we arrange never to need more than six
  14177. arguments.
  14178. %
  14179. The return value of the function is stored in register \code{rax}.
  14180. Regarding frames \index{subject}{frame} and the procedure call stack,
  14181. \index{subject}{procedure call stack} recall from
  14182. section~\ref{sec:x86} that the stack grows down and each function call
  14183. uses a chunk of space on the stack called a frame. The caller sets the
  14184. stack pointer, register \code{rsp}, to the last data item in its
  14185. frame. The callee must not change anything in the caller's frame, that
  14186. is, anything that is at or above the stack pointer. The callee is free
  14187. to use locations that are below the stack pointer.
  14188. Recall that we store variables of tuple type on the root stack. So,
  14189. the prelude\index{subject}{prelude} of a function needs to move the
  14190. root stack pointer \code{r15} up according to the number of variables
  14191. of tuple type and the conclusion\index{subject}{conclusion} needs to
  14192. move the root stack pointer back down. Also, the prelude must
  14193. initialize to \code{0} this frame's slots in the root stack to signal
  14194. to the garbage collector that those slots do not yet contain a valid
  14195. pointer. Otherwise the garbage collector will interpret the garbage
  14196. bits in those slots as memory addresses and try to traverse them,
  14197. causing serious mayhem!
  14198. Regarding the sharing of registers between different functions, recall
  14199. from section~\ref{sec:calling-conventions} that the registers are
  14200. divided into two groups, the caller-saved registers and the
  14201. callee-saved registers. The caller should assume that all the
  14202. caller-saved registers are overwritten with arbitrary values by the
  14203. callee. For that reason we recommend in
  14204. section~\ref{sec:calling-conventions} that variables that are live
  14205. during a function call should not be assigned to caller-saved
  14206. registers.
  14207. On the flip side, if the callee wants to use a callee-saved register,
  14208. the callee must save the contents of those registers on their stack
  14209. frame and then put them back prior to returning to the caller. For
  14210. that reason we recommend in section~\ref{sec:calling-conventions} that if
  14211. the register allocator assigns a variable to a callee-saved register,
  14212. then the prelude of the \code{main} function must save that register
  14213. to the stack and the conclusion of \code{main} must restore it. This
  14214. recommendation now generalizes to all functions.
  14215. Recall that the base pointer, register \code{rbp}, is used as a
  14216. point of reference within a frame, so that each local variable can be
  14217. accessed at a fixed offset from the base pointer
  14218. (section~\ref{sec:x86}).
  14219. %
  14220. Figure~\ref{fig:call-frames} shows the layout of the caller and callee
  14221. frames.
  14222. \begin{figure}[tbp]
  14223. \centering
  14224. \begin{tcolorbox}[colback=white]
  14225. \begin{tabular}{r|r|l|l} \hline
  14226. Caller View & Callee View & Contents & Frame \\ \hline
  14227. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  14228. 0(\key{\%rbp}) & & old \key{rbp} \\
  14229. -8(\key{\%rbp}) & & callee-saved $1$ \\
  14230. \ldots & & \ldots \\
  14231. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  14232. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  14233. \ldots & & \ldots \\
  14234. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  14235. %% & & \\
  14236. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  14237. %% & \ldots & \ldots \\
  14238. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  14239. \hline
  14240. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  14241. & 0(\key{\%rbp}) & old \key{rbp} \\
  14242. & -8(\key{\%rbp}) & callee-saved $1$ \\
  14243. & \ldots & \ldots \\
  14244. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  14245. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  14246. & \ldots & \ldots \\
  14247. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  14248. \end{tabular}
  14249. \end{tcolorbox}
  14250. \caption{Memory layout of caller and callee frames.}
  14251. \label{fig:call-frames}
  14252. \end{figure}
  14253. %% Recall from section~\ref{sec:x86} that the stack is also used for
  14254. %% local variables and for storing the values of callee-saved registers
  14255. %% (we shall refer to all of these collectively as ``locals''), and that
  14256. %% at the beginning of a function we move the stack pointer \code{rsp}
  14257. %% down to make room for them.
  14258. %% We recommend storing the local variables
  14259. %% first and then the callee-saved registers, so that the local variables
  14260. %% can be accessed using \code{rbp} the same as before the addition of
  14261. %% functions.
  14262. %% To make additional room for passing arguments, we shall
  14263. %% move the stack pointer even further down. We count how many stack
  14264. %% arguments are needed for each function call that occurs inside the
  14265. %% body of the function and find their maximum. Adding this number to the
  14266. %% number of locals gives us how much the \code{rsp} should be moved at
  14267. %% the beginning of the function. In preparation for a function call, we
  14268. %% offset from \code{rsp} to set up the stack arguments. We put the first
  14269. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  14270. %% so on.
  14271. %% Upon calling the function, the stack arguments are retrieved by the
  14272. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  14273. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  14274. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  14275. %% the layout of the caller and callee frames. Notice how important it is
  14276. %% that we correctly compute the maximum number of arguments needed for
  14277. %% function calls; if that number is too small then the arguments and
  14278. %% local variables will smash into each other!
  14279. \subsection{Efficient Tail Calls}
  14280. \label{sec:tail-call}
  14281. In general, the amount of stack space used by a program is determined
  14282. by the longest chain of nested function calls. That is, if function
  14283. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  14284. amount of stack space is linear in $n$. The depth $n$ can grow quite
  14285. large if functions are recursive. However, in some cases we can
  14286. arrange to use only a constant amount of space for a long chain of
  14287. nested function calls.
  14288. A \emph{tail call}\index{subject}{tail call} is a function call that
  14289. happens as the last action in a function body. For example, in the
  14290. following program, the recursive call to \code{tail\_sum} is a tail
  14291. call:
  14292. \begin{center}
  14293. {\if\edition\racketEd
  14294. \begin{lstlisting}
  14295. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  14296. (if (eq? n 0)
  14297. r
  14298. (tail_sum (- n 1) (+ n r))))
  14299. (+ (tail_sum 3 0) 36)
  14300. \end{lstlisting}
  14301. \fi}
  14302. {\if\edition\pythonEd\pythonColor
  14303. \begin{lstlisting}
  14304. def tail_sum(n : int, r : int) -> int:
  14305. if n == 0:
  14306. return r
  14307. else:
  14308. return tail_sum(n - 1, n + r)
  14309. print(tail_sum(3, 0) + 36)
  14310. \end{lstlisting}
  14311. \fi}
  14312. \end{center}
  14313. At a tail call, the frame of the caller is no longer needed, so we can
  14314. pop the caller's frame before making the tail
  14315. call. \index{subject}{frame} With this approach, a recursive function
  14316. that makes only tail calls ends up using a constant amount of stack
  14317. space. \racket{Functional languages like Racket rely heavily on
  14318. recursive functions, so the definition of Racket \emph{requires}
  14319. that all tail calls be optimized in this way.}
  14320. Some care is needed with regard to argument passing in tail calls. As
  14321. mentioned, for arguments beyond the sixth, the convention is to use
  14322. space in the caller's frame for passing arguments. However, for a
  14323. tail call we pop the caller's frame and can no longer use it. An
  14324. alternative is to use space in the callee's frame for passing
  14325. arguments. However, this option is also problematic because the caller
  14326. and callee's frames overlap in memory. As we begin to copy the
  14327. arguments from their sources in the caller's frame, the target
  14328. locations in the callee's frame might collide with the sources for
  14329. later arguments! We solve this problem by using the heap instead of
  14330. the stack for passing more than six arguments
  14331. (section~\ref{sec:limit-functions-r4}).
  14332. As mentioned, for a tail call we pop the caller's frame prior to
  14333. making the tail call. The instructions for popping a frame are the
  14334. instructions that we usually place in the conclusion of a
  14335. function. Thus, we also need to place such code immediately before
  14336. each tail call. These instructions include restoring the callee-saved
  14337. registers, so it is fortunate that the argument passing registers are
  14338. all caller-saved registers.
  14339. One note remains regarding which instruction to use to make the tail
  14340. call. When the callee is finished, it should not return to the current
  14341. function but instead return to the function that called the current
  14342. one. Thus, the return address that is already on the stack is the
  14343. right one, and we should not use \key{callq} to make the tail call
  14344. because that would overwrite the return address. Instead we simply use
  14345. the \key{jmp} instruction. As with the indirect function call, we write
  14346. an \emph{indirect jump}\index{subject}{indirect jump} with a register
  14347. prefixed with an asterisk. We recommend using \code{rax} to hold the
  14348. jump target because the conclusion can overwrite just about everything
  14349. else.
  14350. \begin{lstlisting}
  14351. jmp *%rax
  14352. \end{lstlisting}
  14353. \section{Shrink \LangFun{}}
  14354. \label{sec:shrink-r4}
  14355. The \code{shrink} pass performs a minor modification to ease the
  14356. later passes. This pass introduces an explicit \code{main} function
  14357. that gobbles up all the top-level statements of the module.
  14358. %
  14359. \racket{It also changes the top \code{ProgramDefsExp} form to
  14360. \code{ProgramDefs}.}
  14361. {\if\edition\racketEd
  14362. \begin{lstlisting}
  14363. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  14364. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  14365. \end{lstlisting}
  14366. where $\itm{mainDef}$ is
  14367. \begin{lstlisting}
  14368. (Def 'main '() 'Integer '() |$\Exp'$|)
  14369. \end{lstlisting}
  14370. \fi}
  14371. {\if\edition\pythonEd\pythonColor
  14372. \begin{lstlisting}
  14373. Module(|$\Def\ldots\Stmt\ldots$|)
  14374. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  14375. \end{lstlisting}
  14376. where $\itm{mainDef}$ is
  14377. \begin{lstlisting}
  14378. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  14379. \end{lstlisting}
  14380. \fi}
  14381. \section{Reveal Functions and the \LangFunRef{} Language}
  14382. \label{sec:reveal-functions-r4}
  14383. The syntax of \LangFun{} is inconvenient for purposes of compilation
  14384. in that it conflates the use of function names and local
  14385. variables. This is a problem because we need to compile the use of a
  14386. function name differently from the use of a local variable. In
  14387. particular, we use \code{leaq} to convert the function name (a label
  14388. in x86) to an address in a register. Thus, we create a new pass that
  14389. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  14390. $n$ is the arity of the function.\python{\footnote{The arity is not
  14391. needed in this chapter but is used in chapter~\ref{ch:Ldyn}.}}
  14392. This pass is named \code{reveal\_functions} and the output language
  14393. is \LangFunRef{}.
  14394. %is defined in figure~\ref{fig:f1-syntax}.
  14395. %% The concrete syntax for a
  14396. %% function reference is $\CFUNREF{f}$.
  14397. %% \begin{figure}[tp]
  14398. %% \centering
  14399. %% \fbox{
  14400. %% \begin{minipage}{0.96\textwidth}
  14401. %% {\if\edition\racketEd
  14402. %% \[
  14403. %% \begin{array}{lcl}
  14404. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  14405. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14406. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  14407. %% \end{array}
  14408. %% \]
  14409. %% \fi}
  14410. %% {\if\edition\pythonEd\pythonColor
  14411. %% \[
  14412. %% \begin{array}{lcl}
  14413. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  14414. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  14415. %% \end{array}
  14416. %% \]
  14417. %% \fi}
  14418. %% \end{minipage}
  14419. %% }
  14420. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  14421. %% (figure~\ref{fig:Lfun-syntax}).}
  14422. %% \label{fig:f1-syntax}
  14423. %% \end{figure}
  14424. %% Distinguishing between calls in tail position and non-tail position
  14425. %% requires the pass to have some notion of context. We recommend using
  14426. %% two mutually recursive functions, one for processing expressions in
  14427. %% tail position and another for the rest.
  14428. \racket{Placing this pass after \code{uniquify} will make sure that
  14429. there are no local variables and functions that share the same
  14430. name.}
  14431. %
  14432. The \code{reveal\_functions} pass should come before the
  14433. \code{remove\_complex\_operands} pass because function references
  14434. should be categorized as complex expressions.
  14435. \section{Limit Functions}
  14436. \label{sec:limit-functions-r4}
  14437. Recall that we wish to limit the number of function parameters to six
  14438. so that we do not need to use the stack for argument passing, which
  14439. makes it easier to implement efficient tail calls. However, because
  14440. the input language \LangFun{} supports arbitrary numbers of function
  14441. arguments, we have some work to do! The \code{limit\_functions} pass
  14442. transforms functions and function calls that involve more than six
  14443. arguments to pass the first five arguments as usual, but it packs the
  14444. rest of the arguments into a tuple and passes it as the sixth
  14445. argument.\footnote{The implementation this pass can be postponed to
  14446. last because you can test the rest of the passes on functions with
  14447. six or fewer parameters.}
  14448. Each function definition with seven or more parameters is transformed as
  14449. follows:
  14450. {\if\edition\racketEd
  14451. \begin{lstlisting}
  14452. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  14453. |$\Rightarrow$|
  14454. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  14455. \end{lstlisting}
  14456. \fi}
  14457. {\if\edition\pythonEd\pythonColor
  14458. \begin{lstlisting}
  14459. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  14460. |$\Rightarrow$|
  14461. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  14462. |$T_r$|, None, |$\itm{body}'$|, None)
  14463. \end{lstlisting}
  14464. \fi}
  14465. %
  14466. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  14467. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  14468. the $k$th element of the tuple, where $k = i - 6$.
  14469. %
  14470. {\if\edition\racketEd
  14471. \begin{lstlisting}
  14472. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  14473. \end{lstlisting}
  14474. \fi}
  14475. {\if\edition\pythonEd\pythonColor
  14476. \begin{lstlisting}
  14477. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  14478. \end{lstlisting}
  14479. \fi}
  14480. For function calls with too many arguments, the \code{limit\_functions}
  14481. pass transforms them in the following way:
  14482. \begin{tabular}{lll}
  14483. \begin{minipage}{0.3\textwidth}
  14484. {\if\edition\racketEd
  14485. \begin{lstlisting}
  14486. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  14487. \end{lstlisting}
  14488. \fi}
  14489. {\if\edition\pythonEd\pythonColor
  14490. \begin{lstlisting}
  14491. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  14492. \end{lstlisting}
  14493. \fi}
  14494. \end{minipage}
  14495. &
  14496. $\Rightarrow$
  14497. &
  14498. \begin{minipage}{0.5\textwidth}
  14499. {\if\edition\racketEd
  14500. \begin{lstlisting}
  14501. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  14502. \end{lstlisting}
  14503. \fi}
  14504. {\if\edition\pythonEd\pythonColor
  14505. \begin{lstlisting}
  14506. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  14507. \end{lstlisting}
  14508. \fi}
  14509. \end{minipage}
  14510. \end{tabular}
  14511. \section{Remove Complex Operands}
  14512. \label{sec:rco-r4}
  14513. The primary decisions to make for this pass are whether to classify
  14514. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  14515. atomic or complex expressions. Recall that an atomic expression
  14516. ends up as an immediate argument of an x86 instruction. Function
  14517. application translates to a sequence of instructions, so
  14518. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  14519. a complex expression. On the other hand, the arguments of
  14520. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  14521. expressions.
  14522. %
  14523. Regarding \code{FunRef}, as discussed previously, the function label
  14524. needs to be converted to an address using the \code{leaq}
  14525. instruction. Thus, even though \code{FunRef} seems rather simple, it
  14526. needs to be classified as a complex expression so that we generate an
  14527. assignment statement with a left-hand side that can serve as the
  14528. target of the \code{leaq}.
  14529. The output of this pass, \LangFunANF{} (figure~\ref{fig:Lfun-anf-syntax}),
  14530. extends \LangAllocANF{} (figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  14531. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions
  14532. and augments programs to include a list of function definitions.
  14533. %
  14534. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  14535. \newcommand{\LfunMonadASTRacket}{
  14536. \begin{array}{lcl}
  14537. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  14538. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14539. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  14540. \end{array}
  14541. }
  14542. \newcommand{\LfunMonadASTPython}{
  14543. \begin{array}{lcl}
  14544. \Type &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  14545. \MID \key{TupleType}\LS\Type^+\RS\\
  14546. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  14547. \Exp &::=& \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}}\\
  14548. \Stmt &::=& \RETURN{\Exp} \\
  14549. \Params &::=& \LP\Var\key{,}\Type\RP^* \\
  14550. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  14551. \end{array}
  14552. }
  14553. \begin{figure}[tp]
  14554. \centering
  14555. \begin{tcolorbox}[colback=white]
  14556. \footnotesize
  14557. {\if\edition\racketEd
  14558. \[
  14559. \begin{array}{l}
  14560. \gray{\LvarMonadASTRacket} \\ \hline
  14561. \gray{\LifMonadASTRacket} \\ \hline
  14562. \gray{\LwhileMonadASTRacket} \\ \hline
  14563. \gray{\LtupMonadASTRacket} \\ \hline
  14564. \LfunMonadASTRacket \\
  14565. \begin{array}{rcl}
  14566. \LangFunANFM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  14567. \end{array}
  14568. \end{array}
  14569. \]
  14570. \fi}
  14571. {\if\edition\pythonEd\pythonColor
  14572. \[
  14573. \begin{array}{l}
  14574. \gray{\LvarMonadASTPython} \\ \hline
  14575. \gray{\LifMonadASTPython} \\ \hline
  14576. \gray{\LwhileMonadASTPython} \\ \hline
  14577. \gray{\LtupMonadASTPython} \\ \hline
  14578. \LfunMonadASTPython \\
  14579. \begin{array}{rcl}
  14580. \LangFunANFM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  14581. \end{array}
  14582. \end{array}
  14583. \]
  14584. \fi}
  14585. \end{tcolorbox}
  14586. \caption{\LangFunANF{} is \LangFunRef{} in monadic normal form.}
  14587. \label{fig:Lfun-anf-syntax}
  14588. \end{figure}
  14589. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  14590. %% \LangFunANF{} of this pass.
  14591. %% \begin{figure}[tp]
  14592. %% \centering
  14593. %% \fbox{
  14594. %% \begin{minipage}{0.96\textwidth}
  14595. %% \small
  14596. %% \[
  14597. %% \begin{array}{rcl}
  14598. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  14599. %% \MID \VOID{} } \\
  14600. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  14601. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  14602. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  14603. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  14604. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  14605. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  14606. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  14607. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  14608. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  14609. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  14610. %% \end{array}
  14611. %% \]
  14612. %% \end{minipage}
  14613. %% }
  14614. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  14615. %% \label{fig:Lfun-anf-syntax}
  14616. %% \end{figure}
  14617. \section{Explicate Control and the \LangCFun{} Language}
  14618. \label{sec:explicate-control-r4}
  14619. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  14620. output of \code{explicate\_control}.
  14621. %
  14622. %% \racket{(The concrete syntax is given in
  14623. %% figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  14624. %
  14625. The auxiliary functions for assignment\racket{ and tail contexts} should
  14626. be updated with cases for
  14627. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  14628. function for predicate context should be updated for
  14629. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  14630. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  14631. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  14632. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  14633. auxiliary function for processing function definitions. This code is
  14634. similar to the case for \code{Program} in \LangVec{}. The top-level
  14635. \code{explicate\_control} function that handles the \code{ProgramDefs}
  14636. form of \LangFun{} can then apply this new function to all the
  14637. function definitions.
  14638. {\if\edition\pythonEd\pythonColor
  14639. The translation of \code{Return} statements requires a new auxiliary
  14640. function to handle expressions in tail context, called
  14641. \code{explicate\_tail}. The function should take an expression and the
  14642. dictionary of basic blocks and produce a list of statements in the
  14643. \LangCFun{} language. The \code{explicate\_tail} function should
  14644. include cases for \code{Begin}, \code{IfExp}, and \code{Call},
  14645. and a default case for other kinds of expressions. The default case
  14646. should produce a \code{Return} statement. The case for \code{Call}
  14647. should change it into \code{TailCall}. The other cases should
  14648. recursively process their subexpressions and statements, choosing the
  14649. appropriate explicate functions for the various contexts.
  14650. \fi}
  14651. \newcommand{\CfunASTRacket}{
  14652. \begin{array}{lcl}
  14653. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  14654. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  14655. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  14656. \end{array}
  14657. }
  14658. \newcommand{\CfunASTPython}{
  14659. \begin{array}{lcl}
  14660. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  14661. \Tail &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  14662. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  14663. \Block &::=& \itm{label}\key{:} \Stmt^{*}\;\Tail \\
  14664. \Def &::=& \DEF{\itm{label}}{\Params}{\LC\Block\code{,}\ldots\RC}{\key{None}}{\Type}{\key{None}}
  14665. \end{array}
  14666. }
  14667. \begin{figure}[tp]
  14668. \begin{tcolorbox}[colback=white]
  14669. \footnotesize
  14670. {\if\edition\racketEd
  14671. \[
  14672. \begin{array}{l}
  14673. \gray{\CvarASTRacket} \\ \hline
  14674. \gray{\CifASTRacket} \\ \hline
  14675. \gray{\CloopASTRacket} \\ \hline
  14676. \gray{\CtupASTRacket} \\ \hline
  14677. \CfunASTRacket \\
  14678. \begin{array}{lcl}
  14679. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14680. \end{array}
  14681. \end{array}
  14682. \]
  14683. \fi}
  14684. {\if\edition\pythonEd\pythonColor
  14685. \[
  14686. \begin{array}{l}
  14687. \gray{\CifASTPython} \\ \hline
  14688. \gray{\CtupASTPython} \\ \hline
  14689. \CfunASTPython \\
  14690. \begin{array}{lcl}
  14691. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14692. \end{array}
  14693. \end{array}
  14694. \]
  14695. \fi}
  14696. \end{tcolorbox}
  14697. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  14698. \label{fig:c3-syntax}
  14699. \end{figure}
  14700. \clearpage
  14701. \section{Select Instructions and the \LangXIndCall{} Language}
  14702. \label{sec:select-r4}
  14703. \index{subject}{select instructions}
  14704. The output of select instructions is a program in the \LangXIndCall{}
  14705. language; the definition of its concrete syntax is shown in
  14706. figure~\ref{fig:x86-3-concrete}, and the definition of its abstract
  14707. syntax is shown in figure~\ref{fig:x86-3}. We use the \code{align}
  14708. directive on the labels of function definitions to make sure the
  14709. bottom three bits are zero, which we put to use in
  14710. chapter~\ref{ch:Ldyn}. We discuss the new instructions as needed in
  14711. this section. \index{subject}{x86}
  14712. \newcommand{\GrammarXIndCall}{
  14713. \begin{array}{lcl}
  14714. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  14715. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  14716. \Block &::= & \Instr^{+} \\
  14717. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  14718. \end{array}
  14719. }
  14720. \newcommand{\ASTXIndCallRacket}{
  14721. \begin{array}{lcl}
  14722. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  14723. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14724. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  14725. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  14726. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  14727. \end{array}
  14728. }
  14729. \begin{figure}[tp]
  14730. \begin{tcolorbox}[colback=white]
  14731. \small
  14732. \[
  14733. \begin{array}{l}
  14734. \gray{\GrammarXInt} \\ \hline
  14735. \gray{\GrammarXIf} \\ \hline
  14736. \gray{\GrammarXGlobal} \\ \hline
  14737. \GrammarXIndCall \\
  14738. \begin{array}{lcl}
  14739. \LangXIndCallM{} &::= & \Def^{*}
  14740. \end{array}
  14741. \end{array}
  14742. \]
  14743. \end{tcolorbox}
  14744. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of figure~\ref{fig:x86-2-concrete}).}
  14745. \label{fig:x86-3-concrete}
  14746. \end{figure}
  14747. \begin{figure}[tp]
  14748. \begin{tcolorbox}[colback=white]
  14749. \small
  14750. {\if\edition\racketEd
  14751. \[\arraycolsep=3pt
  14752. \begin{array}{l}
  14753. \gray{\ASTXIntRacket} \\ \hline
  14754. \gray{\ASTXIfRacket} \\ \hline
  14755. \gray{\ASTXGlobalRacket} \\ \hline
  14756. \ASTXIndCallRacket \\
  14757. \begin{array}{lcl}
  14758. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  14759. \end{array}
  14760. \end{array}
  14761. \]
  14762. \fi}
  14763. {\if\edition\pythonEd\pythonColor
  14764. \[
  14765. \begin{array}{lcl}
  14766. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  14767. \MID \BYTEREG{\Reg} } \\
  14768. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  14769. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  14770. \MID \TAILJMP{\Arg}{\itm{int}}\\
  14771. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  14772. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  14773. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\LC\Block\code{,}\ldots\RC}{\_}{\Type}{\_} \\
  14774. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14775. \end{array}
  14776. \]
  14777. \fi}
  14778. \end{tcolorbox}
  14779. \caption{The abstract syntax of \LangXIndCall{} (extends
  14780. \LangXGlobal{} of figure~\ref{fig:x86-2}).}
  14781. \label{fig:x86-3}
  14782. \end{figure}
  14783. An assignment of a function reference to a variable becomes a
  14784. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  14785. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  14786. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  14787. node, whose concrete syntax is instruction-pointer-relative
  14788. addressing.
  14789. \begin{center}
  14790. \begin{tabular}{lcl}
  14791. \begin{minipage}{0.35\textwidth}
  14792. {\if\edition\racketEd
  14793. \begin{lstlisting}
  14794. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  14795. \end{lstlisting}
  14796. \fi}
  14797. {\if\edition\pythonEd\pythonColor
  14798. \begin{lstlisting}
  14799. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  14800. \end{lstlisting}
  14801. \fi}
  14802. \end{minipage}
  14803. &
  14804. $\Rightarrow$\qquad\qquad
  14805. &
  14806. \begin{minipage}{0.3\textwidth}
  14807. \begin{lstlisting}
  14808. leaq |$f$|(%rip), |$\itm{lhs}'$|
  14809. \end{lstlisting}
  14810. \end{minipage}
  14811. \end{tabular}
  14812. \end{center}
  14813. Regarding function definitions, we need to remove the parameters and
  14814. instead perform parameter passing using the conventions discussed in
  14815. section~\ref{sec:fun-x86}. That is, the arguments are passed in
  14816. registers. We recommend turning the parameters into local variables
  14817. and generating instructions at the beginning of the function to move
  14818. from the argument-passing registers
  14819. (section~\ref{sec:calling-conventions-fun}) to these local variables.
  14820. {\if\edition\racketEd
  14821. \begin{lstlisting}
  14822. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  14823. |$\Rightarrow$|
  14824. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  14825. \end{lstlisting}
  14826. \fi}
  14827. {\if\edition\pythonEd\pythonColor
  14828. \begin{lstlisting}
  14829. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  14830. |$\Rightarrow$|
  14831. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  14832. \end{lstlisting}
  14833. \fi}
  14834. The basic blocks $B'$ are the same as $B$ except that the
  14835. \code{start} block is modified to add the instructions for moving from
  14836. the argument registers to the parameter variables. So the \code{start}
  14837. block of $B$ shown on the left of the following is changed to the code
  14838. on the right:
  14839. \begin{center}
  14840. \begin{minipage}{0.3\textwidth}
  14841. \begin{lstlisting}
  14842. start:
  14843. |$\itm{instr}_1$|
  14844. |$\cdots$|
  14845. |$\itm{instr}_n$|
  14846. \end{lstlisting}
  14847. \end{minipage}
  14848. $\Rightarrow$
  14849. \begin{minipage}{0.3\textwidth}
  14850. \begin{lstlisting}
  14851. |$f$|start:
  14852. movq %rdi, |$x_1$|
  14853. movq %rsi, |$x_2$|
  14854. |$\cdots$|
  14855. |$\itm{instr}_1$|
  14856. |$\cdots$|
  14857. |$\itm{instr}_n$|
  14858. \end{lstlisting}
  14859. \end{minipage}
  14860. \end{center}
  14861. Recall that we use the label \code{start} for the initial block of a
  14862. program, and in section~\ref{sec:select-Lvar} we recommend labeling
  14863. the conclusion of the program with \code{conclusion}, so that
  14864. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  14865. by a jump to \code{conclusion}. With the addition of function
  14866. definitions, there is a start block and conclusion for each function,
  14867. but their labels need to be unique. We recommend prepending the
  14868. function's name to \code{start} and \code{conclusion}, respectively,
  14869. to obtain unique labels.
  14870. \racket{The interpreter for \LangXIndCall{} needs to be given the
  14871. number of parameters the function expects, but the parameters are no
  14872. longer in the syntax of function definitions. Instead, add an entry
  14873. to $\itm{info}$ that maps \code{num-params} to the number of
  14874. parameters to construct $\itm{info}'$.}
  14875. By changing the parameters to local variables, we are giving the
  14876. register allocator control over which registers or stack locations to
  14877. use for them. If you implement the move-biasing challenge
  14878. (section~\ref{sec:move-biasing}), the register allocator will try to
  14879. assign the parameter variables to the corresponding argument register,
  14880. in which case the \code{patch\_instructions} pass will remove the
  14881. \code{movq} instruction. This happens in the example translation given
  14882. in figure~\ref{fig:add-fun} in section~\ref{sec:functions-example}, in
  14883. the \code{add} function.
  14884. %
  14885. Also, note that the register allocator will perform liveness analysis
  14886. on this sequence of move instructions and build the interference
  14887. graph. So, for example, $x_1$ will be marked as interfering with
  14888. \code{rsi}, and that will prevent the mapping of $x_1$ to \code{rsi},
  14889. which is good because otherwise the first \code{movq} would overwrite
  14890. the argument in \code{rsi} that is needed for $x_2$.
  14891. Next, consider the compilation of function calls. In the mirror image
  14892. of the handling of parameters in function definitions, the arguments
  14893. are moved to the argument-passing registers. Note that the function
  14894. is not given as a label, but its address is produced by the argument
  14895. $\itm{arg}_0$. So, we translate the call into an indirect function
  14896. call. The return value from the function is stored in \code{rax}, so
  14897. it needs to be moved into the \itm{lhs}.
  14898. \begin{lstlisting}
  14899. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\python{\LS}\itm{arg}_1~\itm{arg}_2 \ldots\python{\RS}}$|
  14900. |$\Rightarrow$|
  14901. movq |$\itm{arg}_1$|, %rdi
  14902. movq |$\itm{arg}_2$|, %rsi
  14903. |$\vdots$|
  14904. callq *|$\itm{arg}_0$|
  14905. movq %rax, |$\itm{lhs}$|
  14906. \end{lstlisting}
  14907. The \code{IndirectCallq} AST node includes an integer for the arity of
  14908. the function, that is, the number of parameters. That information is
  14909. useful in the \code{uncover\_live} pass for determining which
  14910. argument-passing registers are potentially read during the call.
  14911. For tail calls, the parameter passing is the same as non-tail calls:
  14912. generate instructions to move the arguments into the argument-passing
  14913. registers. After that we need to pop the frame from the procedure
  14914. call stack. However, we do not yet know how big the frame is; that
  14915. gets determined during register allocation. So, instead of generating
  14916. those instructions here, we invent a new instruction that means ``pop
  14917. the frame and then do an indirect jump,'' which we name
  14918. \code{TailJmp}. The abstract syntax for this instruction includes an
  14919. argument that specifies where to jump and an integer that represents
  14920. the arity of the function being called.
  14921. \section{Register Allocation}
  14922. \label{sec:register-allocation-r4}
  14923. The addition of functions requires some changes to all three aspects
  14924. of register allocation, which we discuss in the following subsections.
  14925. \subsection{Liveness Analysis}
  14926. \label{sec:liveness-analysis-r4}
  14927. \index{subject}{liveness analysis}
  14928. %% The rest of the passes need only minor modifications to handle the new
  14929. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  14930. %% \code{leaq}.
  14931. The \code{IndirectCallq} instruction should be treated like
  14932. \code{Callq} regarding its written locations $W$, in that they should
  14933. include all the caller-saved registers. Recall that the reason for
  14934. that is to force variables that are live across a function call to be assigned to callee-saved
  14935. registers or to be spilled to the stack.
  14936. Regarding the set of read locations $R$, the arity fields of
  14937. \code{TailJmp} and \code{IndirectCallq} determine how many of the
  14938. argument-passing registers should be considered as read by those
  14939. instructions. Also, the target field of \code{TailJmp} and
  14940. \code{IndirectCallq} should be included in the set of read locations
  14941. $R$.
  14942. \subsection{Build Interference Graph}
  14943. \label{sec:build-interference-r4}
  14944. With the addition of function definitions, we compute a separate interference
  14945. graph for each function (not just one for the whole program).
  14946. Recall that in section~\ref{sec:reg-alloc-gc} we discussed the need to
  14947. spill tuple-typed variables that are live during a call to
  14948. \code{collect}, the garbage collector. With the addition of functions
  14949. to our language, we need to revisit this issue. Functions that perform
  14950. allocation contain calls to the collector. Thus, we should not only
  14951. spill a tuple-typed variable when it is live during a call to
  14952. \code{collect}, but we should spill the variable if it is live during
  14953. a call to any user-defined function. Thus, in the
  14954. \code{build\_interference} pass, we recommend adding interference
  14955. edges between call-live tuple-typed variables and the callee-saved
  14956. registers (in addition to creating edges between
  14957. call-live variables and the caller-saved registers).
  14958. \subsection{Allocate Registers}
  14959. The primary change to the \code{allocate\_registers} pass is adding an
  14960. auxiliary function for handling definitions (the \Def{} nonterminal
  14961. shown in figure~\ref{fig:x86-3}) with one case for function
  14962. definitions. The logic is the same as described in
  14963. chapter~\ref{ch:register-allocation-Lvar} except that now register
  14964. allocation is performed many times, once for each function definition,
  14965. instead of just once for the whole program.
  14966. \section{Patch Instructions}
  14967. In \code{patch\_instructions}, you should deal with the x86
  14968. idiosyncrasy that the destination argument of \code{leaq} must be a
  14969. register. Additionally, you should ensure that the argument of
  14970. \code{TailJmp} is \itm{rax}, our reserved register---because we
  14971. trample many other registers before the tail call, as explained in the
  14972. next section.
  14973. \section{Generate Prelude and Conclusion}
  14974. Now that register allocation is complete, we can translate the
  14975. \code{TailJmp} into a sequence of instructions. A naive translation of
  14976. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  14977. before the jump we need to pop the current frame to achieve efficient
  14978. tail calls. This sequence of instructions is the same as the code for
  14979. the conclusion of a function, except that the \code{retq} is replaced with
  14980. \code{jmp *$\itm{arg}$}.
  14981. Regarding function definitions, we generate a prelude and conclusion
  14982. for each one. This code is similar to the prelude and conclusion
  14983. generated for the \code{main} function presented in
  14984. chapter~\ref{ch:Lvec}. To review, the prelude of every function should
  14985. carry out the following steps:
  14986. % TODO: .align the functions!
  14987. \begin{enumerate}
  14988. %% \item Start with \code{.global} and \code{.align} directives followed
  14989. %% by the label for the function. (See figure~\ref{fig:add-fun} for an
  14990. %% example.)
  14991. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  14992. pointer.
  14993. \item Push to the stack all the callee-saved registers that were
  14994. used for register allocation.
  14995. \item Move the stack pointer \code{rsp} down to make room for the
  14996. regular spills (aligned to 16 bytes).
  14997. \item Move the root stack pointer \code{r15} up by the size of the
  14998. root-stack frame for this function, which depends on the number of
  14999. spilled tuple-typed variables. \label{root-stack-init}
  15000. \item Initialize to zero all new entries in the root-stack frame.
  15001. \item Jump to the start block.
  15002. \end{enumerate}
  15003. The prelude of the \code{main} function has an additional task: call
  15004. the \code{initialize} function to set up the garbage collector, and
  15005. then move the value of the global \code{rootstack\_begin} in
  15006. \code{r15}. This initialization should happen before step
  15007. \ref{root-stack-init}, which depends on \code{r15}.
  15008. The conclusion of every function should do the following:
  15009. \begin{enumerate}
  15010. \item Move the stack pointer back up past the regular spills.
  15011. \item Restore the callee-saved registers by popping them from the
  15012. stack.
  15013. \item Move the root stack pointer back down by the size of the
  15014. root-stack frame for this function.
  15015. \item Restore \code{rbp} by popping it from the stack.
  15016. \item Return to the caller with the \code{retq} instruction.
  15017. \end{enumerate}
  15018. The output of this pass is \LangXIndCallFlat{}, which differs from
  15019. \LangXIndCall{} in that there is no longer an AST node for function
  15020. definitions. Instead, a program is just
  15021. \racket{an association list}\python{dictionary}
  15022. of basic blocks, as in \LangXGlobal{}. So we have the following grammar rule:
  15023. {\if\edition\racketEd
  15024. \[
  15025. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  15026. \]
  15027. \fi}
  15028. {\if\edition\pythonEd
  15029. \[
  15030. \LangXIndCallFlatM{} ::= \XPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Instr^{*}\code{,}\ldots\RC}
  15031. \]
  15032. \fi}
  15033. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  15034. compiling \LangFun{} to x86.
  15035. \begin{exercise}\normalfont\normalsize
  15036. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  15037. Create eight new programs that use functions including examples that
  15038. pass functions and return functions from other functions, recursive
  15039. functions, functions that create tuples, and functions that make tail
  15040. calls. Test your compiler on these new programs and all your
  15041. previously created test programs.
  15042. \end{exercise}
  15043. \begin{figure}[tbp]
  15044. \begin{tcolorbox}[colback=white]
  15045. {\if\edition\racketEd
  15046. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.90]
  15047. \node (Lfun) at (0,2) {\large \LangFun{}};
  15048. \node (Lfun-1) at (4,2) {\large \LangFun{}};
  15049. \node (Lfun-2) at (7,2) {\large \LangFun{}};
  15050. \node (F1-1) at (11,2) {\large \LangFunRef{}};
  15051. \node (F1-2) at (11,0) {\large \LangFunRef{}};
  15052. \node (F1-3) at (7,0) {\large \LangFunRefAlloc{}};
  15053. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15054. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15055. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15056. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15057. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15058. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15059. \node (x86-5) at (8,-6) {\large \LangXIndCallFlat{}};
  15060. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  15061. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  15062. \path[->,bend left=15] (Lfun) edge [above] node
  15063. {\ttfamily\footnotesize shrink} (Lfun-1);
  15064. \path[->,bend left=15] (Lfun-1) edge [above] node
  15065. {\ttfamily\footnotesize uniquify} (Lfun-2);
  15066. \path[->,bend left=15] (Lfun-2) edge [above] node
  15067. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15068. \path[->,bend left=15] (F1-1) edge [left] node
  15069. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15070. \path[->,bend left=15] (F1-2) edge [below] node
  15071. {\ttfamily\footnotesize expose\_allocation} (F1-3);
  15072. \path[->,bend left=15] (F1-3) edge [below] node
  15073. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  15074. \path[->,bend right=15] (F1-4) edge [above] node
  15075. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15076. \path[->,bend right=15] (F1-5) edge [right] node
  15077. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15078. \path[->,bend right=15] (C3-2) edge [right] node
  15079. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15080. \path[->,bend left=15] (x86-2) edge [right] node
  15081. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  15082. \path[->,bend right=15] (x86-2-1) edge [below] node
  15083. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  15084. \path[->,bend right=15] (x86-2-2) edge [right] node
  15085. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  15086. \path[->,bend left=15] (x86-3) edge [above] node
  15087. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15088. \path[->,bend right=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15089. \end{tikzpicture}
  15090. \fi}
  15091. {\if\edition\pythonEd\pythonColor
  15092. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  15093. \node (Lfun) at (0,2) {\large \LangFun{}};
  15094. \node (Lfun-2) at (4,2) {\large \LangFun{}};
  15095. \node (F1-1) at (8,2) {\large \LangFunRef{}};
  15096. \node (F1-2) at (12,2) {\large \LangFunRef{}};
  15097. \node (F1-4) at (4,0) {\large \LangFunRefAlloc{}};
  15098. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  15099. \node (C3-2) at (0,-2) {\large \LangCFun{}};
  15100. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  15101. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  15102. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  15103. \node (x86-5) at (12,-4) {\large \LangXIndCallFlat{}};
  15104. \path[->,bend left=15] (Lfun) edge [above] node
  15105. {\ttfamily\footnotesize shrink} (Lfun-2);
  15106. \path[->,bend left=15] (Lfun-2) edge [above] node
  15107. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  15108. \path[->,bend left=15] (F1-1) edge [above] node
  15109. {\ttfamily\footnotesize limit\_functions} (F1-2);
  15110. \path[->,bend left=15] (F1-2) edge [right] node
  15111. {\ttfamily\footnotesize \ \ expose\_allocation} (F1-4);
  15112. \path[->,bend right=15] (F1-4) edge [above] node
  15113. {\ttfamily\footnotesize remove\_complex\_operands} (F1-5);
  15114. \path[->,bend right=15] (F1-5) edge [right] node
  15115. {\ttfamily\footnotesize explicate\_control} (C3-2);
  15116. \path[->,bend left=15] (C3-2) edge [right] node
  15117. {\ttfamily\footnotesize select\_instructions} (x86-2);
  15118. \path[->,bend right=15] (x86-2) edge [below] node
  15119. {\ttfamily\footnotesize assign\_homes} (x86-3);
  15120. \path[->,bend left=15] (x86-3) edge [above] node
  15121. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  15122. \path[->,bend right=15] (x86-4) edge [below] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  15123. \end{tikzpicture}
  15124. \fi}
  15125. \end{tcolorbox}
  15126. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  15127. \label{fig:Lfun-passes}
  15128. \end{figure}
  15129. \section{An Example Translation}
  15130. \label{sec:functions-example}
  15131. Figure~\ref{fig:add-fun} shows an example translation of a simple
  15132. function in \LangFun{} to x86. The figure includes the results of
  15133. \code{explicate\_control} and \code{select\_instructions}.
  15134. \begin{figure}[hbtp]
  15135. \begin{tcolorbox}[colback=white]
  15136. \begin{tabular}{ll}
  15137. \begin{minipage}{0.4\textwidth}
  15138. % s3_2.rkt
  15139. {\if\edition\racketEd
  15140. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15141. (define (add [x : Integer]
  15142. [y : Integer])
  15143. : Integer
  15144. (+ x y))
  15145. (add 40 2)
  15146. \end{lstlisting}
  15147. \fi}
  15148. {\if\edition\pythonEd\pythonColor
  15149. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15150. def add(x:int, y:int) -> int:
  15151. return x + y
  15152. print(add(40, 2))
  15153. \end{lstlisting}
  15154. \fi}
  15155. $\Downarrow$
  15156. {\if\edition\racketEd
  15157. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15158. (define (add86 [x87 : Integer]
  15159. [y88 : Integer])
  15160. : Integer
  15161. add86start:
  15162. return (+ x87 y88);
  15163. )
  15164. (define (main) : Integer ()
  15165. mainstart:
  15166. tmp89 = (fun-ref add86 2);
  15167. (tail-call tmp89 40 2)
  15168. )
  15169. \end{lstlisting}
  15170. \fi}
  15171. {\if\edition\pythonEd\pythonColor
  15172. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15173. def add(x:int, y:int) -> int:
  15174. addstart:
  15175. return x + y
  15176. def main() -> int:
  15177. mainstart:
  15178. fun.0 = add
  15179. tmp.1 = fun.0(40, 2)
  15180. print(tmp.1)
  15181. return 0
  15182. \end{lstlisting}
  15183. \fi}
  15184. \end{minipage}
  15185. &
  15186. $\Rightarrow$
  15187. \begin{minipage}{0.5\textwidth}
  15188. {\if\edition\racketEd
  15189. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15190. (define (add86) : Integer
  15191. add86start:
  15192. movq %rdi, x87
  15193. movq %rsi, y88
  15194. movq x87, %rax
  15195. addq y88, %rax
  15196. jmp inc1389conclusion
  15197. )
  15198. (define (main) : Integer
  15199. mainstart:
  15200. leaq (fun-ref add86 2), tmp89
  15201. movq $40, %rdi
  15202. movq $2, %rsi
  15203. tail-jmp tmp89
  15204. )
  15205. \end{lstlisting}
  15206. \fi}
  15207. {\if\edition\pythonEd\pythonColor
  15208. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15209. def add() -> int:
  15210. addstart:
  15211. movq %rdi, x
  15212. movq %rsi, y
  15213. movq x, %rax
  15214. addq y, %rax
  15215. jmp addconclusion
  15216. def main() -> int:
  15217. mainstart:
  15218. leaq add, fun.0
  15219. movq $40, %rdi
  15220. movq $2, %rsi
  15221. callq *fun.0
  15222. movq %rax, tmp.1
  15223. movq tmp.1, %rdi
  15224. callq print_int
  15225. movq $0, %rax
  15226. jmp mainconclusion
  15227. \end{lstlisting}
  15228. \fi}
  15229. $\Downarrow$
  15230. \end{minipage}
  15231. \end{tabular}
  15232. \begin{tabular}{ll}
  15233. \begin{minipage}{0.3\textwidth}
  15234. {\if\edition\racketEd
  15235. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15236. .globl add86
  15237. .align 8
  15238. add86:
  15239. pushq %rbp
  15240. movq %rsp, %rbp
  15241. jmp add86start
  15242. add86start:
  15243. movq %rdi, %rax
  15244. addq %rsi, %rax
  15245. jmp add86conclusion
  15246. add86conclusion:
  15247. popq %rbp
  15248. retq
  15249. \end{lstlisting}
  15250. \fi}
  15251. {\if\edition\pythonEd\pythonColor
  15252. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15253. .align 8
  15254. add:
  15255. pushq %rbp
  15256. movq %rsp, %rbp
  15257. subq $0, %rsp
  15258. jmp addstart
  15259. addstart:
  15260. movq %rdi, %rdx
  15261. movq %rsi, %rcx
  15262. movq %rdx, %rax
  15263. addq %rcx, %rax
  15264. jmp addconclusion
  15265. addconclusion:
  15266. subq $0, %r15
  15267. addq $0, %rsp
  15268. popq %rbp
  15269. retq
  15270. \end{lstlisting}
  15271. \fi}
  15272. \end{minipage}
  15273. &
  15274. \begin{minipage}{0.5\textwidth}
  15275. {\if\edition\racketEd
  15276. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15277. .globl main
  15278. .align 8
  15279. main:
  15280. pushq %rbp
  15281. movq %rsp, %rbp
  15282. movq $16384, %rdi
  15283. movq $16384, %rsi
  15284. callq initialize
  15285. movq rootstack_begin(%rip), %r15
  15286. jmp mainstart
  15287. mainstart:
  15288. leaq add86(%rip), %rcx
  15289. movq $40, %rdi
  15290. movq $2, %rsi
  15291. movq %rcx, %rax
  15292. popq %rbp
  15293. jmp *%rax
  15294. mainconclusion:
  15295. popq %rbp
  15296. retq
  15297. \end{lstlisting}
  15298. \fi}
  15299. {\if\edition\pythonEd\pythonColor
  15300. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15301. .globl main
  15302. .align 8
  15303. main:
  15304. pushq %rbp
  15305. movq %rsp, %rbp
  15306. subq $0, %rsp
  15307. movq $65536, %rdi
  15308. movq $65536, %rsi
  15309. callq initialize
  15310. movq rootstack_begin(%rip), %r15
  15311. jmp mainstart
  15312. mainstart:
  15313. leaq add(%rip), %rcx
  15314. movq $40, %rdi
  15315. movq $2, %rsi
  15316. callq *%rcx
  15317. movq %rax, %rcx
  15318. movq %rcx, %rdi
  15319. callq print_int
  15320. movq $0, %rax
  15321. jmp mainconclusion
  15322. mainconclusion:
  15323. subq $0, %r15
  15324. addq $0, %rsp
  15325. popq %rbp
  15326. retq
  15327. \end{lstlisting}
  15328. \fi}
  15329. \end{minipage}
  15330. \end{tabular}
  15331. \end{tcolorbox}
  15332. \caption{Example compilation of a simple function to x86.}
  15333. \label{fig:add-fun}
  15334. \end{figure}
  15335. % Challenge idea: inlining! (simple version)
  15336. % Further Reading
  15337. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15338. \chapter{Lexically Scoped Functions}
  15339. \label{ch:Llambda}
  15340. \setcounter{footnote}{0}
  15341. This chapter studies lexically scoped functions. Lexical
  15342. scoping\index{subject}{lexical scoping} means that a function's body
  15343. may refer to variables whose binding site is outside of the function,
  15344. in an enclosing scope.
  15345. %
  15346. Consider the example shown in figure~\ref{fig:lexical-scoping} written
  15347. in \LangLam{}, which extends \LangFun{} with the
  15348. \key{lambda}\index{subject}{lambda} form for creating lexically scoped
  15349. functions. The body of the \key{lambda} refers to three variables:
  15350. \code{x}, \code{y}, and \code{z}. The binding sites for \code{x} and
  15351. \code{y} are outside of the \key{lambda}. Variable \code{y} is
  15352. \racket{bound by the enclosing \key{let}}\python{a local variable of
  15353. function \code{f}}, and \code{x} is a parameter of function
  15354. \code{f}. Note that function \code{f} returns the \key{lambda} as its
  15355. result value. The main expression of the program includes two calls to
  15356. \code{f} with different arguments for \code{x}: first \code{5} and
  15357. then \code{3}. The functions returned from \code{f} are bound to
  15358. variables \code{g} and \code{h}. Even though these two functions were
  15359. created by the same \code{lambda}, they are really different functions
  15360. because they use different values for \code{x}. Applying \code{g} to
  15361. \code{11} produces \code{20} whereas applying \code{h} to \code{15}
  15362. produces \code{22}, so the result of the program is \code{42}.
  15363. \begin{figure}[btp]
  15364. \begin{tcolorbox}[colback=white]
  15365. {\if\edition\racketEd
  15366. % lambda_test_21.rkt
  15367. \begin{lstlisting}
  15368. (define (f [x : Integer]) : (Integer -> Integer)
  15369. (let ([y 4])
  15370. (lambda: ([z : Integer]) : Integer
  15371. (+ x (+ y z)))))
  15372. (let ([g (f 5)])
  15373. (let ([h (f 3)])
  15374. (+ (g 11) (h 15))))
  15375. \end{lstlisting}
  15376. \fi}
  15377. {\if\edition\pythonEd\pythonColor
  15378. \begin{lstlisting}
  15379. def f(x : int) -> Callable[[int], int]:
  15380. y = 4
  15381. return lambda z: x + y + z
  15382. g = f(5)
  15383. h = f(3)
  15384. print(g(11) + h(15))
  15385. \end{lstlisting}
  15386. \fi}
  15387. \end{tcolorbox}
  15388. \caption{Example of a lexically scoped function.}
  15389. \label{fig:lexical-scoping}
  15390. \end{figure}
  15391. The approach that we take for implementing lexically scoped functions
  15392. is to compile them into top-level function definitions, translating
  15393. from \LangLam{} into \LangFun{}. However, the compiler must give
  15394. special treatment to variable occurrences such as \code{x} and
  15395. \code{y} in the body of the \code{lambda} shown in
  15396. figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  15397. may not refer to variables defined outside of it. To identify such
  15398. variable occurrences, we review the standard notion of free variable.
  15399. \begin{definition}\normalfont
  15400. A variable is \emph{free in expression} $e$ if the variable occurs
  15401. inside $e$ but does not have an enclosing definition that is also in
  15402. $e$.\index{subject}{free variable}
  15403. \end{definition}
  15404. For example, in the expression
  15405. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  15406. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  15407. only \code{x} and \code{y} are free in the following expression,
  15408. because \code{z} is defined by the \code{lambda}
  15409. {\if\edition\racketEd
  15410. \begin{lstlisting}
  15411. (lambda: ([z : Integer]) : Integer
  15412. (+ x (+ y z)))
  15413. \end{lstlisting}
  15414. \fi}
  15415. {\if\edition\pythonEd\pythonColor
  15416. \begin{lstlisting}
  15417. lambda z: x + y + z
  15418. \end{lstlisting}
  15419. \fi}
  15420. %
  15421. \noindent Thus the free variables of a \code{lambda} are the ones that
  15422. need special treatment. We need to transport at runtime the values
  15423. of those variables from the point where the \code{lambda} was created
  15424. to the point where the \code{lambda} is applied. An efficient solution
  15425. to the problem, due to \citet{Cardelli:1983aa}, is to bundle the
  15426. values of the free variables together with a function pointer into a
  15427. tuple, an arrangement called a \emph{flat closure} (which we shorten
  15428. to just \emph{closure}).\index{subject}{closure}\index{subject}{flat
  15429. closure}
  15430. %
  15431. By design, we have all the ingredients to make closures:
  15432. chapter~\ref{ch:Lvec} gave us tuples, and chapter~\ref{ch:Lfun} gave us
  15433. function pointers. The function pointer resides at index $0$, and the
  15434. values for the free variables fill in the rest of the tuple.
  15435. Let us revisit the example shown in figure~\ref{fig:lexical-scoping}
  15436. to see how closures work. It is a three-step dance. The program calls
  15437. function \code{f}, which creates a closure for the \code{lambda}. The
  15438. closure is a tuple whose first element is a pointer to the top-level
  15439. function that we will generate for the \code{lambda}; the second
  15440. element is the value of \code{x}, which is \code{5}; and the third
  15441. element is \code{4}, the value of \code{y}. The closure does not
  15442. contain an element for \code{z} because \code{z} is not a free
  15443. variable of the \code{lambda}. Creating the closure is step 1 of the
  15444. dance. The closure is returned from \code{f} and bound to \code{g}, as
  15445. shown in figure~\ref{fig:closures}.
  15446. %
  15447. The second call to \code{f} creates another closure, this time with
  15448. \code{3} in the second slot (for \code{x}). This closure is also
  15449. returned from \code{f} but bound to \code{h}, which is also shown in
  15450. figure~\ref{fig:closures}.
  15451. \begin{figure}[tbp]
  15452. \centering
  15453. \begin{minipage}{0.65\textwidth}
  15454. \begin{tcolorbox}[colback=white]
  15455. \includegraphics[width=\textwidth]{figs/closures}
  15456. \end{tcolorbox}
  15457. \end{minipage}
  15458. \caption{Flat closure representations for the two functions
  15459. produced by the \key{lambda} in figure~\ref{fig:lexical-scoping}.}
  15460. \label{fig:closures}
  15461. \end{figure}
  15462. Continuing with the example, consider the application of \code{g} to
  15463. \code{11} shown in figure~\ref{fig:lexical-scoping}. To apply a
  15464. closure, we obtain the function pointer from the first element of the
  15465. closure and call it, passing in the closure itself and then the
  15466. regular arguments, in this case \code{11}. This technique for applying
  15467. a closure is step 2 of the dance.
  15468. %
  15469. But doesn't this \code{lambda} take only one argument, for parameter
  15470. \code{z}? The third and final step of the dance is generating a
  15471. top-level function for a \code{lambda}. We add an additional
  15472. parameter for the closure and insert an initialization at the beginning
  15473. of the function for each free variable, to bind those variables to the
  15474. appropriate elements from the closure parameter.
  15475. %
  15476. This three-step dance is known as \emph{closure
  15477. conversion}\index{subject}{closure conversion}. We discuss the
  15478. details of closure conversion in section~\ref{sec:closure-conversion}
  15479. and show the code generated from the example in
  15480. section~\ref{sec:example-lambda}. First, we define the syntax and
  15481. semantics of \LangLam{} in section~\ref{sec:r5}.
  15482. \section{The \LangLam{} Language}
  15483. \label{sec:r5}
  15484. The definitions of the concrete syntax and abstract syntax for
  15485. \LangLam{}, a language with anonymous functions and lexical scoping,
  15486. are shown in figures~\ref{fig:Llam-concrete-syntax} and
  15487. \ref{fig:Llam-syntax}. They add the \key{lambda} form to the grammar
  15488. for \LangFun{}, which already has syntax for function application.
  15489. %
  15490. \python{The syntax also includes an assignment statement that includes
  15491. a type annotation for the variable on the left-hand side, which
  15492. facilitates the type checking of \code{lambda} expressions that we
  15493. discuss later in this section.}
  15494. %
  15495. \racket{The \code{procedure-arity} operation returns the number of parameters
  15496. of a given function, an operation that we need for the translation
  15497. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.}
  15498. %
  15499. \python{The \code{arity} operation returns the number of parameters of
  15500. a given function, an operation that we need for the translation
  15501. of dynamic typing that is discussed in chapter~\ref{ch:Ldyn}.
  15502. The \code{arity} operation is not in Python, but the same functionality
  15503. is available in a more complex form. We include \code{arity} in the
  15504. \LangLam{} source language to enable testing.}
  15505. \newcommand{\LlambdaGrammarRacket}{
  15506. \begin{array}{lcl}
  15507. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  15508. &\MID& \LP \key{procedure-arity}~\Exp\RP
  15509. \end{array}
  15510. }
  15511. \newcommand{\LlambdaASTRacket}{
  15512. \begin{array}{lcl}
  15513. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  15514. \itm{op} &::=& \code{procedure-arity}
  15515. \end{array}
  15516. }
  15517. \newcommand{\LlambdaGrammarPython}{
  15518. \begin{array}{lcl}
  15519. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  15520. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  15521. \end{array}
  15522. }
  15523. \newcommand{\LlambdaASTPython}{
  15524. \begin{array}{lcl}
  15525. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  15526. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  15527. \end{array}
  15528. }
  15529. % include AnnAssign in ASTPython
  15530. \begin{figure}[tp]
  15531. \centering
  15532. \begin{tcolorbox}[colback=white]
  15533. \small
  15534. {\if\edition\racketEd
  15535. \[
  15536. \begin{array}{l}
  15537. \gray{\LintGrammarRacket{}} \\ \hline
  15538. \gray{\LvarGrammarRacket{}} \\ \hline
  15539. \gray{\LifGrammarRacket{}} \\ \hline
  15540. \gray{\LwhileGrammarRacket} \\ \hline
  15541. \gray{\LtupGrammarRacket} \\ \hline
  15542. \gray{\LfunGrammarRacket} \\ \hline
  15543. \LlambdaGrammarRacket \\
  15544. \begin{array}{lcl}
  15545. \LangLamM{} &::=& \Def\ldots \; \Exp
  15546. \end{array}
  15547. \end{array}
  15548. \]
  15549. \fi}
  15550. {\if\edition\pythonEd\pythonColor
  15551. \[
  15552. \begin{array}{l}
  15553. \gray{\LintGrammarPython{}} \\ \hline
  15554. \gray{\LvarGrammarPython{}} \\ \hline
  15555. \gray{\LifGrammarPython{}} \\ \hline
  15556. \gray{\LwhileGrammarPython} \\ \hline
  15557. \gray{\LtupGrammarPython} \\ \hline
  15558. \gray{\LfunGrammarPython} \\ \hline
  15559. \LlambdaGrammarPython \\
  15560. \begin{array}{lcl}
  15561. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  15562. \end{array}
  15563. \end{array}
  15564. \]
  15565. \fi}
  15566. \end{tcolorbox}
  15567. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-concrete-syntax})
  15568. with \key{lambda}.}
  15569. \label{fig:Llam-concrete-syntax}
  15570. \end{figure}
  15571. \begin{figure}[tp]
  15572. \centering
  15573. \begin{tcolorbox}[colback=white]
  15574. \small
  15575. {\if\edition\racketEd
  15576. \[\arraycolsep=3pt
  15577. \begin{array}{l}
  15578. \gray{\LintOpAST} \\ \hline
  15579. \gray{\LvarASTRacket{}} \\ \hline
  15580. \gray{\LifASTRacket{}} \\ \hline
  15581. \gray{\LwhileASTRacket{}} \\ \hline
  15582. \gray{\LtupASTRacket{}} \\ \hline
  15583. \gray{\LfunASTRacket} \\ \hline
  15584. \LlambdaASTRacket \\
  15585. \begin{array}{lcl}
  15586. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15587. \end{array}
  15588. \end{array}
  15589. \]
  15590. \fi}
  15591. {\if\edition\pythonEd\pythonColor
  15592. \[
  15593. \begin{array}{l}
  15594. \gray{\LintASTPython} \\ \hline
  15595. \gray{\LvarASTPython{}} \\ \hline
  15596. \gray{\LifASTPython{}} \\ \hline
  15597. \gray{\LwhileASTPython{}} \\ \hline
  15598. \gray{\LtupASTPython{}} \\ \hline
  15599. \gray{\LfunASTPython} \\ \hline
  15600. \LlambdaASTPython \\
  15601. \begin{array}{lcl}
  15602. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15603. \end{array}
  15604. \end{array}
  15605. \]
  15606. \fi}
  15607. \end{tcolorbox}
  15608. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (figure~\ref{fig:Lfun-syntax}).}
  15609. \label{fig:Llam-syntax}
  15610. \end{figure}
  15611. Figure~\ref{fig:interp-Llambda} shows the definitional
  15612. interpreter\index{subject}{interpreter} for \LangLam{}. The case for
  15613. \key{Lambda} saves the current environment inside the returned
  15614. function value. Recall that during function application, the
  15615. environment stored in the function value, extended with the mapping of
  15616. parameters to argument values, is used to interpret the body of the
  15617. function.
  15618. \begin{figure}[tbp]
  15619. \begin{tcolorbox}[colback=white]
  15620. {\if\edition\racketEd
  15621. \begin{lstlisting}
  15622. (define interp-Llambda-class
  15623. (class interp-Lfun-class
  15624. (super-new)
  15625. (define/override (interp-op op)
  15626. (match op
  15627. ['procedure-arity
  15628. (lambda (v)
  15629. (match v
  15630. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  15631. [else (error 'interp-op "expected a function, not ~a" v)]))]
  15632. [else (super interp-op op)]))
  15633. (define/override ((interp-exp env) e)
  15634. (define recur (interp-exp env))
  15635. (match e
  15636. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  15637. `(function ,xs ,body ,env)]
  15638. [else ((super interp-exp env) e)]))
  15639. ))
  15640. (define (interp-Llambda p)
  15641. (send (new interp-Llambda-class) interp-program p))
  15642. \end{lstlisting}
  15643. \fi}
  15644. {\if\edition\pythonEd\pythonColor
  15645. \begin{lstlisting}
  15646. class InterpLlambda(InterpLfun):
  15647. def arity(self, v):
  15648. match v:
  15649. case Function(name, params, body, env):
  15650. return len(params)
  15651. case _:
  15652. raise Exception('Llambda arity unexpected ' + repr(v))
  15653. def interp_exp(self, e, env):
  15654. match e:
  15655. case Call(Name('arity'), [fun]):
  15656. f = self.interp_exp(fun, env)
  15657. return self.arity(f)
  15658. case Lambda(params, body):
  15659. return Function('lambda', params, [Return(body)], env)
  15660. case _:
  15661. return super().interp_exp(e, env)
  15662. def interp_stmt(self, s, env, cont):
  15663. match s:
  15664. case AnnAssign(lhs, typ, value, simple):
  15665. env[lhs.id] = self.interp_exp(value, env)
  15666. return self.interp_stmts(cont, env)
  15667. case Pass():
  15668. return self.interp_stmts(cont, env)
  15669. case _:
  15670. return super().interp_stmt(s, env, cont)
  15671. \end{lstlisting}
  15672. \fi}
  15673. \end{tcolorbox}
  15674. \caption{Interpreter for \LangLam{}.}
  15675. \label{fig:interp-Llambda}
  15676. \end{figure}
  15677. {\if\edition\racketEd
  15678. %
  15679. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  15680. \key{lambda} form. The body of the \key{lambda} is checked in an
  15681. environment that includes the current environment (because it is
  15682. lexically scoped) and also includes the \key{lambda}'s parameters. We
  15683. require the body's type to match the declared return type.
  15684. %
  15685. \fi}
  15686. {\if\edition\pythonEd\pythonColor
  15687. %
  15688. Figures~\ref{fig:type-check-Llambda} and
  15689. \ref{fig:type-check-Llambda-part2} define the type checker for
  15690. \LangLam{}, which is more complex than one might expect. The reason
  15691. for the added complexity is that the syntax of \key{lambda} does not
  15692. include type annotations for the parameters or return type. Instead
  15693. they must be inferred. There are many approaches to type inference
  15694. from which to choose, of varying degrees of complexity. We choose one
  15695. of the simpler approaches, bidirectional type
  15696. inference~\citep{Pierce:2000,Dunfield:2021}, because the focus of this
  15697. book is compilation, not type inference.
  15698. The main idea of bidirectional type inference is to add an auxiliary
  15699. function, here named \code{check\_exp}, that takes an expected type
  15700. and checks whether the given expression is of that type. Thus, in
  15701. \code{check\_exp}, type information flows in a top-down manner with
  15702. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  15703. function, where type information flows in a primarily bottom-up
  15704. manner.
  15705. %
  15706. The idea then is to use \code{check\_exp} in all the places where we
  15707. already know what the type of an expression should be, such as in the
  15708. \code{return} statement of a top-level function definition or on the
  15709. right-hand side of an annotated assignment statement.
  15710. With regard to \code{lambda}, it is straightforward to check a
  15711. \code{lambda} inside \code{check\_exp} because the expected type
  15712. provides the parameter types and the return type. On the other hand,
  15713. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  15714. that we do not allow \code{lambda} in contexts in which we don't already
  15715. know its type. This restriction does not incur a loss of
  15716. expressiveness for \LangLam{} because it is straightforward to modify
  15717. a program to sidestep the restriction, for example, by using an
  15718. annotated assignment statement to assign the \code{lambda} to a
  15719. temporary variable.
  15720. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  15721. checker records their type in a \code{has\_type} field. This type
  15722. information is used further on in this chapter.
  15723. %
  15724. \fi}
  15725. \begin{figure}[tbp]
  15726. \begin{tcolorbox}[colback=white]
  15727. {\if\edition\racketEd
  15728. \begin{lstlisting}
  15729. (define (type-check-Llambda env)
  15730. (lambda (e)
  15731. (match e
  15732. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  15733. (define-values (new-body bodyT)
  15734. ((type-check-exp (append (map cons xs Ts) env)) body))
  15735. (define ty `(,@Ts -> ,rT))
  15736. (cond
  15737. [(equal? rT bodyT)
  15738. (values (HasType (Lambda params rT new-body) ty) ty)]
  15739. [else
  15740. (error "mismatch in return type" bodyT rT)])]
  15741. ...
  15742. )))
  15743. \end{lstlisting}
  15744. \fi}
  15745. {\if\edition\pythonEd\pythonColor
  15746. \begin{lstlisting}
  15747. class TypeCheckLlambda(TypeCheckLfun):
  15748. def type_check_exp(self, e, env):
  15749. match e:
  15750. case Name(id):
  15751. e.has_type = env[id]
  15752. return env[id]
  15753. case Lambda(params, body):
  15754. raise Exception('cannot synthesize a type for a lambda')
  15755. case Call(Name('arity'), [func]):
  15756. func_t = self.type_check_exp(func, env)
  15757. match func_t:
  15758. case FunctionType(params_t, return_t):
  15759. return IntType()
  15760. case _:
  15761. raise Exception('in arity, unexpected ' + repr(func_t))
  15762. case _:
  15763. return super().type_check_exp(e, env)
  15764. def check_exp(self, e, ty, env):
  15765. match e:
  15766. case Lambda(params, body):
  15767. e.has_type = ty
  15768. match ty:
  15769. case FunctionType(params_t, return_t):
  15770. new_env = env.copy().update(zip(params, params_t))
  15771. self.check_exp(body, return_t, new_env)
  15772. case _:
  15773. raise Exception('lambda does not have type ' + str(ty))
  15774. case Call(func, args):
  15775. func_t = self.type_check_exp(func, env)
  15776. match func_t:
  15777. case FunctionType(params_t, return_t):
  15778. for (arg, param_t) in zip(args, params_t):
  15779. self.check_exp(arg, param_t, env)
  15780. self.check_type_equal(return_t, ty, e)
  15781. case _:
  15782. raise Exception('type_check_exp: in call, unexpected ' + \
  15783. repr(func_t))
  15784. case _:
  15785. t = self.type_check_exp(e, env)
  15786. self.check_type_equal(t, ty, e)
  15787. \end{lstlisting}
  15788. \fi}
  15789. \end{tcolorbox}
  15790. \caption{Type checking \LangLam{}\python{, part 1}.}
  15791. \label{fig:type-check-Llambda}
  15792. \end{figure}
  15793. {\if\edition\pythonEd\pythonColor
  15794. \begin{figure}[tbp]
  15795. \begin{tcolorbox}[colback=white]
  15796. \begin{lstlisting}
  15797. def check_stmts(self, ss, return_ty, env):
  15798. if len(ss) == 0:
  15799. return
  15800. match ss[0]:
  15801. case FunctionDef(name, params, body, dl, returns, comment):
  15802. new_env = env.copy().update(params)
  15803. rt = self.check_stmts(body, returns, new_env)
  15804. self.check_stmts(ss[1:], return_ty, env)
  15805. case Return(value):
  15806. self.check_exp(value, return_ty, env)
  15807. case Assign([Name(id)], value):
  15808. if id in env:
  15809. self.check_exp(value, env[id], env)
  15810. else:
  15811. env[id] = self.type_check_exp(value, env)
  15812. self.check_stmts(ss[1:], return_ty, env)
  15813. case Assign([Subscript(tup, Constant(index), Store())], value):
  15814. tup_t = self.type_check_exp(tup, env)
  15815. match tup_t:
  15816. case TupleType(ts):
  15817. self.check_exp(value, ts[index], env)
  15818. case _:
  15819. raise Exception('expected a tuple, not ' + repr(tup_t))
  15820. self.check_stmts(ss[1:], return_ty, env)
  15821. case AnnAssign(Name(id), ty_annot, value, simple):
  15822. ss[0].annotation = ty_annot
  15823. if id in env:
  15824. self.check_type_equal(env[id], ty_annot)
  15825. else:
  15826. env[id] = ty_annot
  15827. self.check_exp(value, ty_annot, env)
  15828. self.check_stmts(ss[1:], return_ty, env)
  15829. case _:
  15830. self.type_check_stmts(ss, env)
  15831. def type_check(self, p):
  15832. match p:
  15833. case Module(body):
  15834. env = {}
  15835. for s in body:
  15836. match s:
  15837. case FunctionDef(name, params, bod, dl, returns, comment):
  15838. params_t = [t for (x,t) in params]
  15839. env[name] = FunctionType(params_t, returns)
  15840. self.check_stmts(body, int, env)
  15841. \end{lstlisting}
  15842. \end{tcolorbox}
  15843. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  15844. \label{fig:type-check-Llambda-part2}
  15845. \end{figure}
  15846. \fi}
  15847. \clearpage
  15848. \section{Assignment and Lexically Scoped Functions}
  15849. \label{sec:assignment-scoping}
  15850. The combination of lexically scoped functions and assignment to
  15851. variables raises a challenge with the flat-closure approach to
  15852. implementing lexically scoped functions. Consider the following
  15853. example in which function \code{f} has a free variable \code{x} that
  15854. is changed after \code{f} is created but before the call to \code{f}.
  15855. % loop_test_11.rkt
  15856. {\if\edition\racketEd
  15857. \begin{lstlisting}
  15858. (let ([x 0])
  15859. (let ([y 0])
  15860. (let ([z 20])
  15861. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  15862. (begin
  15863. (set! x 10)
  15864. (set! y 12)
  15865. (f y))))))
  15866. \end{lstlisting}
  15867. \fi}
  15868. {\if\edition\pythonEd\pythonColor
  15869. % box_free_assign.py
  15870. \begin{lstlisting}
  15871. def g(z : int) -> int:
  15872. x = 0
  15873. y = 0
  15874. f : Callable[[int],int] = lambda a: a + x + z
  15875. x = 10
  15876. y = 12
  15877. return f(y)
  15878. print(g(20))
  15879. \end{lstlisting}
  15880. \fi} The correct output for this example is \code{42} because the call
  15881. to \code{f} is required to use the current value of \code{x} (which is
  15882. \code{10}). Unfortunately, the closure conversion pass
  15883. (section~\ref{sec:closure-conversion}) generates code for the
  15884. \code{lambda} that copies the old value of \code{x} into a
  15885. closure. Thus, if we naively applied closure conversion, the output of
  15886. this program would be \code{32}.
  15887. A first attempt at solving this problem would be to save a pointer to
  15888. \code{x} in the closure and change the occurrences of \code{x} inside
  15889. the lambda to dereference the pointer. Of course, this would require
  15890. assigning \code{x} to the stack and not to a register. However, the
  15891. problem goes a bit deeper.
  15892. Consider the following example that returns a function that refers to
  15893. a local variable of the enclosing function:
  15894. \begin{center}
  15895. \begin{minipage}{\textwidth}
  15896. {\if\edition\racketEd
  15897. \begin{lstlisting}
  15898. (define (f) : ( -> Integer)
  15899. (let ([x 0])
  15900. (let ([g (lambda: () : Integer x)])
  15901. (begin
  15902. (set! x 42)
  15903. g))))
  15904. ((f))
  15905. \end{lstlisting}
  15906. \fi}
  15907. {\if\edition\pythonEd\pythonColor
  15908. % counter.py
  15909. \begin{lstlisting}
  15910. def f():
  15911. x = 0
  15912. g = lambda: x
  15913. x = 42
  15914. return g
  15915. print(f()())
  15916. \end{lstlisting}
  15917. \fi}
  15918. \end{minipage}
  15919. \end{center}
  15920. In this example, the lifetime of \code{x} extends beyond the lifetime
  15921. of the call to \code{f}. Thus, if we were to store \code{x} on the
  15922. stack frame for the call to \code{f}, it would be gone by the time we
  15923. called \code{g}, leaving us with dangling pointers for
  15924. \code{x}. This example demonstrates that when a variable occurs free
  15925. inside a function, its lifetime becomes indefinite. Thus, the value of
  15926. the variable needs to live on the heap. The verb
  15927. \emph{box}\index{subject}{box} is often used for allocating a single
  15928. value on the heap, producing a pointer, and
  15929. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  15930. %
  15931. We introduce a new pass named \code{convert\_assignments} to address
  15932. this challenge.
  15933. %
  15934. \python{But before diving into that, we have one more
  15935. problem to discuss.}
  15936. {\if\edition\pythonEd\pythonColor
  15937. \section{Uniquify Variables}
  15938. \label{sec:uniquify-lambda}
  15939. With the addition of \code{lambda} we have a complication to deal
  15940. with: name shadowing. Consider the following program with a function
  15941. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  15942. \code{lambda} expressions. The first \code{lambda} has a parameter
  15943. that is also named \code{x}.
  15944. \begin{lstlisting}
  15945. def f(x:int, y:int) -> Callable[[int], int]:
  15946. g : Callable[[int],int] = (lambda x: x + y)
  15947. h : Callable[[int],int] = (lambda y: x + y)
  15948. x = input_int()
  15949. return g
  15950. print(f(0, 10)(32))
  15951. \end{lstlisting}
  15952. Many of our compiler passes rely on being able to connect variable
  15953. uses with their definitions using just the name of the
  15954. variable. However, in the example above, the name of the variable does
  15955. not uniquely determine its definition. To solve this problem we
  15956. recommend implementing a pass named \code{uniquify} that renames every
  15957. variable in the program to make sure that they are all unique.
  15958. The following shows the result of \code{uniquify} for the example
  15959. above. The \code{x} parameter of function \code{f} is renamed to
  15960. \code{x\_0}, and the \code{x} parameter of the first \code{lambda} is
  15961. renamed to \code{x\_4}.
  15962. \begin{lstlisting}
  15963. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  15964. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  15965. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  15966. x_0 = input_int()
  15967. return g_2
  15968. def main() -> int :
  15969. print(f(0, 10)(32))
  15970. return 0
  15971. \end{lstlisting}
  15972. \fi} % pythonEd
  15973. %% \section{Reveal Functions}
  15974. %% \label{sec:reveal-functions-r5}
  15975. %% \racket{To support the \code{procedure-arity} operator we need to
  15976. %% communicate the arity of a function to the point of closure
  15977. %% creation.}
  15978. %% %
  15979. %% \python{In chapter~\ref{ch:Ldyn} we need to access the arity of a
  15980. %% function at runtime. Thus, we need to communicate the arity of a
  15981. %% function to the point of closure creation.}
  15982. %% %
  15983. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  15984. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  15985. %% \[
  15986. %% \begin{array}{lcl}
  15987. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  15988. %% \end{array}
  15989. %% \]
  15990. \section{Assignment Conversion}
  15991. \label{sec:convert-assignments}
  15992. The purpose of the \code{convert\_assignments} pass is to address the
  15993. challenge regarding the interaction between variable assignments and
  15994. closure conversion. First we identify which variables need to be
  15995. boxed, and then we transform the program to box those variables. In
  15996. general, boxing introduces runtime overhead that we would like to
  15997. avoid, so we should box as few variables as possible. We recommend
  15998. boxing the variables in the intersection of the following two sets of
  15999. variables:
  16000. \begin{enumerate}
  16001. \item The variables that are free in a \code{lambda}.
  16002. \item The variables that appear on the left-hand side of an
  16003. assignment.
  16004. \end{enumerate}
  16005. The first condition is a must but the second condition is
  16006. conservative. It is possible to develop a more liberal condition using
  16007. static program analysis.
  16008. Consider again the first example from
  16009. section~\ref{sec:assignment-scoping}:
  16010. %
  16011. {\if\edition\racketEd
  16012. \begin{lstlisting}
  16013. (let ([x 0])
  16014. (let ([y 0])
  16015. (let ([z 20])
  16016. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  16017. (begin
  16018. (set! x 10)
  16019. (set! y 12)
  16020. (f y))))))
  16021. \end{lstlisting}
  16022. \fi}
  16023. {\if\edition\pythonEd\pythonColor
  16024. \begin{lstlisting}
  16025. def g(z : int) -> int:
  16026. x = 0
  16027. y = 0
  16028. f : Callable[[int],int] = lambda a: a + x + z
  16029. x = 10
  16030. y = 12
  16031. return f(y)
  16032. print(g(20))
  16033. \end{lstlisting}
  16034. \fi}
  16035. %
  16036. \noindent The variables \code{x} and \code{y} appear on the left-hand
  16037. side of assignments. The variables \code{x} and \code{z} occur free
  16038. inside the \code{lambda}. Thus, variable \code{x} needs to be boxed
  16039. but not \code{y} or \code{z}. The boxing of \code{x} consists of
  16040. three transformations: initialize \code{x} with a tuple whose element
  16041. is uninitialized, replace reads from \code{x} with tuple reads, and
  16042. replace each assignment to \code{x} with a tuple write. The output of
  16043. \code{convert\_assignments} for this example is as follows:
  16044. %
  16045. {\if\edition\racketEd
  16046. \begin{lstlisting}
  16047. (define (main) : Integer
  16048. (let ([x0 (vector 0)])
  16049. (let ([y1 0])
  16050. (let ([z2 20])
  16051. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  16052. (+ a3 (+ (vector-ref x0 0) z2)))])
  16053. (begin
  16054. (vector-set! x0 0 10)
  16055. (set! y1 12)
  16056. (f4 y1)))))))
  16057. \end{lstlisting}
  16058. \fi}
  16059. %
  16060. {\if\edition\pythonEd\pythonColor
  16061. \begin{lstlisting}
  16062. def g(z : int)-> int:
  16063. x = (uninitialized(int),)
  16064. x[0] = 0
  16065. y = 0
  16066. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  16067. x[0] = 10
  16068. y = 12
  16069. return f(y)
  16070. def main() -> int:
  16071. print(g(20))
  16072. return 0
  16073. \end{lstlisting}
  16074. \fi}
  16075. To compute the free variables of all the \code{lambda} expressions, we
  16076. recommend defining the following two auxiliary functions:
  16077. \begin{enumerate}
  16078. \item \code{free\_variables} computes the free variables of an expression, and
  16079. \item \code{free\_in\_lambda} collects all the variables that are
  16080. free in any of the \code{lambda} expressions, using
  16081. \code{free\_variables} in the case for each \code{lambda}.
  16082. \end{enumerate}
  16083. {\if\edition\racketEd
  16084. %
  16085. To compute the variables that are assigned to, we recommend updating
  16086. the \code{collect-set!} function that we introduced in
  16087. section~\ref{sec:uncover-get-bang} to include the new AST forms such
  16088. as \code{Lambda}.
  16089. %
  16090. \fi}
  16091. {\if\edition\pythonEd\pythonColor
  16092. %
  16093. To compute the variables that are assigned to, we recommend defining
  16094. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  16095. the set of variables that occur in the left-hand side of an assignment
  16096. statement and otherwise returns the empty set.
  16097. %
  16098. \fi}
  16099. Let $\mathit{AF}$ be the intersection of the set of variables that are
  16100. free in a \code{lambda} and that are assigned to in the enclosing
  16101. function definition.
  16102. Next we discuss the \code{convert\_assignments} pass. In the case for
  16103. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  16104. $\VAR{x}$ to a tuple read.
  16105. %
  16106. {\if\edition\racketEd
  16107. \begin{lstlisting}
  16108. (Var |$x$|)
  16109. |$\Rightarrow$|
  16110. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  16111. \end{lstlisting}
  16112. \fi}
  16113. %
  16114. {\if\edition\pythonEd\pythonColor
  16115. \begin{lstlisting}
  16116. Name(|$x$|)
  16117. |$\Rightarrow$|
  16118. Subscript(Name(|$x$|), Constant(0), Load())
  16119. \end{lstlisting}
  16120. \fi}
  16121. %
  16122. \noindent In the case for assignment, recursively process the
  16123. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  16124. $x$ is in $\mathit{AF}$, translate the assignment into a tuple write
  16125. as follows:
  16126. %
  16127. {\if\edition\racketEd
  16128. \begin{lstlisting}
  16129. (SetBang |$x$| |$\itm{rhs}$|)
  16130. |$\Rightarrow$|
  16131. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  16132. \end{lstlisting}
  16133. \fi}
  16134. {\if\edition\pythonEd\pythonColor
  16135. \begin{lstlisting}
  16136. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  16137. |$\Rightarrow$|
  16138. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  16139. \end{lstlisting}
  16140. \fi}
  16141. %
  16142. {\if\edition\racketEd
  16143. The case for \code{Lambda} is nontrivial, but it is similar to the
  16144. case for function definitions, which we discuss next.
  16145. \fi}
  16146. %
  16147. To translate a function definition, we first compute $\mathit{AF}$,
  16148. the intersection of the variables that are free in a \code{lambda} and
  16149. that are assigned to. We then apply assignment conversion to the body
  16150. of the function definition. Finally, we box the parameters of this
  16151. function definition that are in $\mathit{AF}$. For example,
  16152. the parameter \code{x} of the following function \code{g}
  16153. needs to be boxed:
  16154. {\if\edition\racketEd
  16155. \begin{lstlisting}
  16156. (define (g [x : Integer]) : Integer
  16157. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  16158. (begin
  16159. (set! x 10)
  16160. (f 32))))
  16161. \end{lstlisting}
  16162. \fi}
  16163. %
  16164. {\if\edition\pythonEd\pythonColor
  16165. \begin{lstlisting}
  16166. def g(x : int) -> int:
  16167. f : Callable[[int],int] = lambda a: a + x
  16168. x = 10
  16169. return f(32)
  16170. \end{lstlisting}
  16171. \fi}
  16172. %
  16173. \noindent We box parameter \code{x} by creating a local variable named
  16174. \code{x} that is initialized to a tuple whose contents is the value of
  16175. the parameter, which is renamed to \code{x\_0}.
  16176. %
  16177. {\if\edition\racketEd
  16178. \begin{lstlisting}
  16179. (define (g [x_0 : Integer]) : Integer
  16180. (let ([x (vector x_0)])
  16181. (let ([f (lambda: ([a : Integer]) : Integer
  16182. (+ a (vector-ref x 0)))])
  16183. (begin
  16184. (vector-set! x 0 10)
  16185. (f 32)))))
  16186. \end{lstlisting}
  16187. \fi}
  16188. %
  16189. {\if\edition\pythonEd\pythonColor
  16190. \begin{lstlisting}
  16191. def g(x_0 : int)-> int:
  16192. x = (x_0,)
  16193. f : Callable[[int], int] = (lambda a: a + x[0])
  16194. x[0] = 10
  16195. return f(32)
  16196. \end{lstlisting}
  16197. \fi}
  16198. \section{Closure Conversion}
  16199. \label{sec:closure-conversion}
  16200. \index{subject}{closure conversion}
  16201. The compiling of lexically scoped functions into top-level function
  16202. definitions and flat closures is accomplished in the pass
  16203. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  16204. and before \code{limit\_functions}.
  16205. As usual, we implement the pass as a recursive function over the
  16206. AST. The interesting cases are for \key{lambda} and function
  16207. application. We transform a \key{lambda} expression into an expression
  16208. that creates a closure, that is, a tuple for which the first element
  16209. is a function pointer and the rest of the elements are the values of
  16210. the free variables of the \key{lambda}.
  16211. %
  16212. However, we use the \code{Closure} AST node instead of using a tuple
  16213. so that we can record the arity.
  16214. %
  16215. In the generated code that follows, \itm{fvs} is the list of free
  16216. variables of the lambda and \itm{name} is a unique symbol generated to
  16217. identify the lambda.
  16218. %
  16219. \racket{The \itm{arity} is the number of parameters (the length of
  16220. \itm{ps}).}
  16221. %
  16222. {\if\edition\racketEd
  16223. \begin{lstlisting}
  16224. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  16225. |$\Rightarrow$|
  16226. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  16227. \end{lstlisting}
  16228. \fi}
  16229. %
  16230. {\if\edition\pythonEd\pythonColor
  16231. \begin{lstlisting}
  16232. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  16233. |$\Rightarrow$|
  16234. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |$\itm{fvs}_1$, \ldots, $\itm{fvs}_m$|])
  16235. \end{lstlisting}
  16236. \fi}
  16237. %
  16238. In addition to transforming each \key{Lambda} AST node into a
  16239. tuple, we create a top-level function definition for each
  16240. \key{Lambda}, as shown next.\\
  16241. \begin{minipage}{0.8\textwidth}
  16242. {\if\edition\racketEd
  16243. \begin{lstlisting}
  16244. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  16245. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  16246. ...
  16247. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  16248. |\itm{body'}|)...))
  16249. \end{lstlisting}
  16250. \fi}
  16251. {\if\edition\pythonEd\pythonColor
  16252. \begin{lstlisting}
  16253. def |\itm{name}|(clos : |\itm{closTy}|, |$\itm{x}_1 : T'_1$, \ldots, $\itm{x}_n : T'_n$|) -> |\itm{rt'}|:
  16254. |$\itm{fvs}_1$| = clos[1]
  16255. |$\ldots$|
  16256. |$\itm{fvs}_m$| = clos[|$m$|]
  16257. |\itm{body'}|
  16258. \end{lstlisting}
  16259. \fi}
  16260. \end{minipage}\\
  16261. %
  16262. The \code{clos} parameter refers to the closure. The type
  16263. \itm{closTy} is a tuple type for which the first element type is
  16264. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the
  16265. rest of the element types are the types of the free variables in the
  16266. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  16267. is nontrivial to give a type to the function in the closure's
  16268. type.\footnote{To give an accurate type to a closure, we would need to
  16269. add existential types to the type checker~\citep{Minamide:1996ys}.}
  16270. %
  16271. \racket{Translate the type
  16272. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  16273. the next paragraph, to obtain \itm{ps'} and \itm{rt'}.}%
  16274. \python{The \code{has\_type} field of the \code{Lambda} AST node
  16275. is of the form \code{FunctionType([$x_1:T_1,\ldots, x_n:T_n$], $rt$)}.
  16276. Translate the parameter types $T_1,\ldots,T_n$ and return type $\itm{rt}$
  16277. to obtain $T'_1,\ldots, T'_n$ and $\itm{rt'}$.}
  16278. %% The dummy type is considered to be equal to any other type during type
  16279. %% checking.
  16280. The free variables become local variables that are initialized with
  16281. their values in the closure.
  16282. Closure conversion turns every function into a tuple, so the type
  16283. annotations in the program must also be translated. We recommend
  16284. defining an auxiliary recursive function for this purpose. Function
  16285. types should be translated as follows:
  16286. %
  16287. {\if\edition\racketEd
  16288. \begin{lstlisting}
  16289. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  16290. |$\Rightarrow$|
  16291. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  16292. \end{lstlisting}
  16293. \fi}
  16294. {\if\edition\pythonEd\pythonColor
  16295. \begin{lstlisting}
  16296. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  16297. |$\Rightarrow$|
  16298. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  16299. \end{lstlisting}
  16300. \fi}
  16301. %
  16302. This type indicates that the first thing in the tuple is a
  16303. function. The first parameter of the function is a tuple (a closure)
  16304. and the rest of the parameters are the ones from the original
  16305. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  16306. omits the types of the free variables because (1) those types are not
  16307. available in this context, and (2) we do not need them in the code that
  16308. is generated for function application. So this type describes only the
  16309. first component of the closure tuple. At runtime the tuple may have
  16310. more components, but we ignore them at this point.
  16311. We transform function application into code that retrieves the
  16312. function from the closure and then calls the function, passing the
  16313. closure as the first argument. We place $e'$ in a temporary variable
  16314. to avoid code duplication.
  16315. \begin{center}
  16316. \begin{minipage}{\textwidth}
  16317. {\if\edition\racketEd
  16318. \begin{lstlisting}
  16319. (Apply |$e$| |$\itm{es}$|)
  16320. |$\Rightarrow$|
  16321. (Let |$\itm{tmp}$| |$e'$|
  16322. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  16323. \end{lstlisting}
  16324. \fi}
  16325. %
  16326. {\if\edition\pythonEd\pythonColor
  16327. \begin{lstlisting}
  16328. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  16329. |$\Rightarrow$|
  16330. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16331. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  16332. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  16333. \end{lstlisting}
  16334. \fi}
  16335. \end{minipage}
  16336. \end{center}
  16337. There is also the question of what to do with references to top-level
  16338. function definitions. To maintain a uniform translation of function
  16339. application, we turn function references into closures.
  16340. \begin{tabular}{lll}
  16341. \begin{minipage}{0.2\textwidth}
  16342. {\if\edition\racketEd
  16343. \begin{lstlisting}
  16344. (FunRef |$f$| |$n$|)
  16345. \end{lstlisting}
  16346. \fi}
  16347. {\if\edition\pythonEd\pythonColor
  16348. \begin{lstlisting}
  16349. FunRef(|$f$|, |$n$|)
  16350. \end{lstlisting}
  16351. \fi}
  16352. \end{minipage}
  16353. &
  16354. $\Rightarrow\qquad$
  16355. &
  16356. \begin{minipage}{0.5\textwidth}
  16357. {\if\edition\racketEd
  16358. \begin{lstlisting}
  16359. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  16360. \end{lstlisting}
  16361. \fi}
  16362. {\if\edition\pythonEd\pythonColor
  16363. \begin{lstlisting}
  16364. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  16365. \end{lstlisting}
  16366. \fi}
  16367. \end{minipage}
  16368. \end{tabular} \\
  16369. We no longer need the annotated assignment statement \code{AnnAssign}
  16370. to support the type checking of \code{lambda} expressions, so we
  16371. translate it to a regular \code{Assign} statement.
  16372. The top-level function definitions need to be updated to take an extra
  16373. closure parameter, but that parameter is ignored in the body of those
  16374. functions.
  16375. \subsection{An Example Translation}
  16376. \label{sec:example-lambda}
  16377. Figure~\ref{fig:lexical-functions-example} shows the result of
  16378. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  16379. program demonstrating lexical scoping that we discussed at the
  16380. beginning of this chapter.
  16381. \begin{figure}[tbp]
  16382. \begin{tcolorbox}[colback=white]
  16383. \begin{minipage}{0.8\textwidth}
  16384. {\if\edition\racketEd
  16385. % tests/lambda_test_6.rkt
  16386. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16387. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  16388. (let ([y8 4])
  16389. (lambda: ([z9 : Integer]) : Integer
  16390. (+ x7 (+ y8 z9)))))
  16391. (define (main) : Integer
  16392. (let ([g0 ((fun-ref f6 1) 5)])
  16393. (let ([h1 ((fun-ref f6 1) 3)])
  16394. (+ (g0 11) (h1 15)))))
  16395. \end{lstlisting}
  16396. $\Rightarrow$
  16397. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  16398. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  16399. (let ([y8 4])
  16400. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  16401. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  16402. (let ([x7 (vector-ref fvs3 1)])
  16403. (let ([y8 (vector-ref fvs3 2)])
  16404. (+ x7 (+ y8 z9)))))
  16405. (define (main) : Integer
  16406. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  16407. ((vector-ref clos5 0) clos5 5))])
  16408. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  16409. ((vector-ref clos6 0) clos6 3))])
  16410. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  16411. \end{lstlisting}
  16412. \fi}
  16413. %
  16414. {\if\edition\pythonEd\pythonColor
  16415. % free_var.py
  16416. \begin{lstlisting}
  16417. def f(x: int) -> Callable[[int],int]:
  16418. y = 4
  16419. return lambda z: x + y + z
  16420. g = f(5)
  16421. h = f(3)
  16422. print(g(11) + h(15))
  16423. \end{lstlisting}
  16424. $\Rightarrow$
  16425. \begin{lstlisting}
  16426. def lambda_0(fvs_1: tuple[bot,int,tuple[int]], z: int) -> int:
  16427. x = fvs_1[1]
  16428. y = fvs_1[2]
  16429. return (x + y[0] + z)
  16430. def f(fvs_2: tuple[bot], x: int) -> tuple[Callable[[tuple[],int],int]]:
  16431. y = (uninitialized(int),)
  16432. y[0] = 4
  16433. return closure{1}({lambda_0}, x, y)
  16434. def main() -> int:
  16435. g = (begin: clos_3 = closure{1}({f})
  16436. clos_3[0](clos_3, 5))
  16437. h = (begin: clos_4 = closure{1}({f})
  16438. clos_4[0](clos_4, 3))
  16439. print((begin: clos_5 = g
  16440. clos_5[0](clos_5, 11))
  16441. + (begin: clos_6 = h
  16442. clos_6[0](clos_6, 15)))
  16443. return 0
  16444. \end{lstlisting}
  16445. \fi}
  16446. \end{minipage}
  16447. \end{tcolorbox}
  16448. \caption{Example of closure conversion.}
  16449. \label{fig:lexical-functions-example}
  16450. \end{figure}
  16451. \begin{exercise}\normalfont\normalsize
  16452. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  16453. Create five new programs that use \key{lambda} functions and make use of
  16454. lexical scoping. Test your compiler on these new programs and all
  16455. your previously created test programs.
  16456. \end{exercise}
  16457. \section{Expose Allocation}
  16458. \label{sec:expose-allocation-r5}
  16459. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  16460. that allocates and initializes a tuple, similar to the translation of
  16461. the tuple creation in section~\ref{sec:expose-allocation}.
  16462. The only difference is replacing the use of
  16463. \ALLOC{\itm{len}}{\itm{type}} with
  16464. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  16465. \section{Explicate Control and \LangCLam{}}
  16466. \label{sec:explicate-r5}
  16467. The output language of \code{explicate\_control} is \LangCLam{}; the
  16468. definition of its abstract syntax is shown in
  16469. figure~\ref{fig:Clam-syntax}.
  16470. %
  16471. \racket{The only differences with respect to \LangCFun{} are the
  16472. addition of the \code{AllocateClosure} form to the grammar for
  16473. $\Exp$ and the \code{procedure-arity} operator. The handling of
  16474. \code{AllocateClosure} in the \code{explicate\_control} pass is
  16475. similar to the handling of other expressions such as primitive
  16476. operators.}
  16477. %
  16478. \python{The differences with respect to \LangCFun{} are the
  16479. additions of \code{Uninitialized}, \code{AllocateClosure},
  16480. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  16481. \code{explicate\_control} pass is similar to the handling of other
  16482. expressions such as primitive operators.}
  16483. \newcommand{\ClambdaASTRacket}{
  16484. \begin{array}{lcl}
  16485. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  16486. \itm{op} &::= & \code{procedure-arity}
  16487. \end{array}
  16488. }
  16489. \newcommand{\ClambdaASTPython}{
  16490. \begin{array}{lcl}
  16491. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  16492. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  16493. &\MID& \ARITY{\Atm}
  16494. \end{array}
  16495. }
  16496. \begin{figure}[tp]
  16497. \begin{tcolorbox}[colback=white]
  16498. \small
  16499. {\if\edition\racketEd
  16500. \[
  16501. \begin{array}{l}
  16502. \gray{\CvarASTRacket} \\ \hline
  16503. \gray{\CifASTRacket} \\ \hline
  16504. \gray{\CloopASTRacket} \\ \hline
  16505. \gray{\CtupASTRacket} \\ \hline
  16506. \gray{\CfunASTRacket} \\ \hline
  16507. \ClambdaASTRacket \\
  16508. \begin{array}{lcl}
  16509. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  16510. \end{array}
  16511. \end{array}
  16512. \]
  16513. \fi}
  16514. {\if\edition\pythonEd\pythonColor
  16515. \[
  16516. \begin{array}{l}
  16517. \gray{\CifASTPython} \\ \hline
  16518. \gray{\CtupASTPython} \\ \hline
  16519. \gray{\CfunASTPython} \\ \hline
  16520. \ClambdaASTPython \\
  16521. \begin{array}{lcl}
  16522. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16523. \end{array}
  16524. \end{array}
  16525. \]
  16526. \fi}
  16527. \end{tcolorbox}
  16528. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (figure~\ref{fig:c3-syntax}).}
  16529. \label{fig:Clam-syntax}
  16530. \end{figure}
  16531. \section{Select Instructions}
  16532. \label{sec:select-instructions-Llambda}
  16533. \index{subject}{select instructions}
  16534. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  16535. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  16536. (section~\ref{sec:select-instructions-gc}). The only difference is
  16537. that you should place the \itm{arity} in the tag that is stored at
  16538. position $0$ of the tuple. Recall that in
  16539. section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  16540. was not used. We store the arity in the $5$ bits starting at position
  16541. $58$.
  16542. \racket{Compile the \code{procedure-arity} operator into a sequence of
  16543. instructions that access the tag from position $0$ of the vector and
  16544. extract the $5$ bits starting at position $58$ from the tag.}
  16545. %
  16546. \python{Compile a call to the \code{arity} operator to a sequence of
  16547. instructions that access the tag from position $0$ of the tuple
  16548. (representing a closure) and extract the $5$ bits starting at position
  16549. $58$ from the tag.}
  16550. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  16551. needed for the compilation of \LangLam{}.
  16552. \begin{figure}[bthp]
  16553. \begin{tcolorbox}[colback=white]
  16554. {\if\edition\racketEd
  16555. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16556. \node (Lfun) at (0,2) {\large \LangLam{}};
  16557. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16558. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16559. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16560. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16561. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16562. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16563. \node (F1-4) at (0,0) {\large \LangFunRefAlloc{}};
  16564. \node (F1-5) at (0,-2) {\large \LangFunRefAlloc{}};
  16565. \node (F1-6) at (4,-2) {\large \LangFunANF{}};
  16566. \node (C3-2) at (8,-2) {\large \LangCFun{}};
  16567. \node (x86-2) at (0,-5) {\large \LangXIndCallVar{}};
  16568. \node (x86-2-1) at (0,-7) {\large \LangXIndCallVar{}};
  16569. \node (x86-2-2) at (4,-7) {\large \LangXIndCallVar{}};
  16570. \node (x86-3) at (4,-5) {\large \LangXIndCallVar{}};
  16571. \node (x86-4) at (8,-5) {\large \LangXIndCall{}};
  16572. \node (x86-5) at (8,-7) {\large \LangXIndCall{}};
  16573. \path[->,bend left=15] (Lfun) edge [above] node
  16574. {\ttfamily\footnotesize shrink} (Lfun-2);
  16575. \path[->,bend left=15] (Lfun-2) edge [above] node
  16576. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16577. \path[->,bend left=15] (Lfun-3) edge [above] node
  16578. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16579. \path[->,bend left=15] (F1-0) edge [left] node
  16580. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16581. \path[->,bend left=15] (F1-1) edge [below] node
  16582. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16583. \path[->,bend right=15] (F1-2) edge [above] node
  16584. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16585. \path[->,bend right=15] (F1-3) edge [above] node
  16586. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  16587. \path[->,bend left=15] (F1-4) edge [right] node
  16588. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16589. \path[->,bend right=15] (F1-5) edge [below] node
  16590. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16591. \path[->,bend left=15] (F1-6) edge [above] node
  16592. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16593. \path[->] (C3-2) edge [right] node
  16594. {\ttfamily\footnotesize \ \ select\_instructions} (x86-2);
  16595. \path[->,bend right=15] (x86-2) edge [right] node
  16596. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16597. \path[->,bend right=15] (x86-2-1) edge [below] node
  16598. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  16599. \path[->,bend right=15] (x86-2-2) edge [right] node
  16600. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  16601. \path[->,bend left=15] (x86-3) edge [above] node
  16602. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16603. \path[->,bend left=15] (x86-4) edge [right] node
  16604. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16605. \end{tikzpicture}
  16606. \fi}
  16607. {\if\edition\pythonEd\pythonColor
  16608. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  16609. \node (Lfun) at (0,2) {\large \LangLam{}};
  16610. \node (Lfun-2) at (4,2) {\large \LangLam{}};
  16611. \node (Lfun-3) at (8,2) {\large \LangLam{}};
  16612. \node (F1-0) at (12,2) {\large \LangLamFunRef{}};
  16613. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  16614. \node (F1-2) at (8,0) {\large \LangFunRef{}};
  16615. \node (F1-3) at (4,0) {\large \LangFunRef{}};
  16616. \node (F1-5) at (0,0) {\large \LangFunRefAlloc{}};
  16617. \node (F1-6) at (0,-2) {\large \LangFunANF{}};
  16618. \node (C3-2) at (0,-4) {\large \LangCFun{}};
  16619. \node (x86-2) at (0,-6) {\large \LangXIndCallVar{}};
  16620. \node (x86-3) at (4,-6) {\large \LangXIndCallVar{}};
  16621. \node (x86-4) at (8,-6) {\large \LangXIndCall{}};
  16622. \node (x86-5) at (12,-6) {\large \LangXIndCall{}};
  16623. \path[->,bend left=15] (Lfun) edge [above] node
  16624. {\ttfamily\footnotesize shrink} (Lfun-2);
  16625. \path[->,bend left=15] (Lfun-2) edge [above] node
  16626. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16627. \path[->,bend left=15] (Lfun-3) edge [above] node
  16628. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  16629. \path[->,bend left=15] (F1-0) edge [left] node
  16630. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  16631. \path[->,bend left=15] (F1-1) edge [below] node
  16632. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  16633. \path[->,bend left=15] (F1-2) edge [below] node
  16634. {\ttfamily\footnotesize limit\_functions} (F1-3);
  16635. \path[->,bend right=15] (F1-3) edge [above] node
  16636. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  16637. \path[->,bend right=15] (F1-5) edge [right] node
  16638. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  16639. \path[->,bend left=15] (F1-6) edge [right] node
  16640. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16641. \path[->,bend right=15] (C3-2) edge [right] node
  16642. {\ttfamily\footnotesize select\_instructions} (x86-2);
  16643. \path[->,bend right=15] (x86-2) edge [below] node
  16644. {\ttfamily\footnotesize assign\_homes} (x86-3);
  16645. \path[->,bend right=15] (x86-3) edge [below] node
  16646. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  16647. \path[->,bend left=15] (x86-4) edge [above] node
  16648. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  16649. \end{tikzpicture}
  16650. \fi}
  16651. \end{tcolorbox}
  16652. \caption{Diagram of the passes for \LangLam{}, a language with lexically scoped
  16653. functions.}
  16654. \label{fig:Llambda-passes}
  16655. \end{figure}
  16656. \clearpage
  16657. \section{Challenge: Optimize Closures}
  16658. \label{sec:optimize-closures}
  16659. In this chapter we compile lexically scoped functions into a
  16660. relatively efficient representation: flat closures. However, even this
  16661. representation comes with some overhead. For example, consider the
  16662. following program with a function \code{tail\_sum} that does not have
  16663. any free variables and where all the uses of \code{tail\_sum} are in
  16664. applications in which we know that only \code{tail\_sum} is being applied
  16665. (and not any other functions):
  16666. \begin{center}
  16667. \begin{minipage}{0.95\textwidth}
  16668. {\if\edition\racketEd
  16669. \begin{lstlisting}
  16670. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  16671. (if (eq? n 0)
  16672. s
  16673. (tail_sum (- n 1) (+ n s))))
  16674. (+ (tail_sum 3 0) 36)
  16675. \end{lstlisting}
  16676. \fi}
  16677. {\if\edition\pythonEd\pythonColor
  16678. \begin{lstlisting}
  16679. def tail_sum(n : int, s : int) -> int:
  16680. if n == 0:
  16681. return s
  16682. else:
  16683. return tail_sum(n - 1, n + s)
  16684. print(tail_sum(3, 0) + 36)
  16685. \end{lstlisting}
  16686. \fi}
  16687. \end{minipage}
  16688. \end{center}
  16689. As described in this chapter, we uniformly apply closure conversion to
  16690. all functions, obtaining the following output for this program:
  16691. \begin{center}
  16692. \begin{minipage}{0.95\textwidth}
  16693. {\if\edition\racketEd
  16694. \begin{lstlisting}
  16695. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  16696. (if (eq? n2 0)
  16697. s3
  16698. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  16699. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  16700. (define (main) : Integer
  16701. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  16702. ((vector-ref clos6 0) clos6 3 0)) 27))
  16703. \end{lstlisting}
  16704. \fi}
  16705. {\if\edition\pythonEd\pythonColor
  16706. \begin{lstlisting}
  16707. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  16708. if n_0 == 0:
  16709. return s_1
  16710. else:
  16711. return (begin: clos_2 = (tail_sum,)
  16712. clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  16713. def main() -> int :
  16714. print((begin: clos_4 = (tail_sum,)
  16715. clos_4[0](clos_4, 3, 0)) + 36)
  16716. return 0
  16717. \end{lstlisting}
  16718. \fi}
  16719. \end{minipage}
  16720. \end{center}
  16721. If this program were compiled according to the previous chapter, there
  16722. would be no allocation and the calls to \code{tail\_sum} would be
  16723. direct calls. In contrast, the program presented here allocates memory
  16724. for each closure and the calls to \code{tail\_sum} are indirect. These
  16725. two differences incur considerable overhead in a program such as this,
  16726. in which the allocations and indirect calls occur inside a tight loop.
  16727. One might think that this problem is trivial to solve: can't we just
  16728. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  16729. and compile them to direct calls instead of treating it like a call to
  16730. a closure? We would also drop the new \code{fvs} parameter of
  16731. \code{tail\_sum}.
  16732. %
  16733. However, this problem is not so trivial, because a global function may
  16734. \emph{escape} and become involved in applications that also involve
  16735. closures. Consider the following example in which the application
  16736. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  16737. application because the \code{lambda} may flow into \code{f}, but the
  16738. \code{inc} function might also flow into \code{f}:
  16739. \begin{center}
  16740. \begin{minipage}{\textwidth}
  16741. % lambda_test_30.rkt
  16742. {\if\edition\racketEd
  16743. \begin{lstlisting}
  16744. (define (inc [x : Integer]) : Integer
  16745. (+ x 1))
  16746. (let ([y (read)])
  16747. (let ([f (if (eq? (read) 0)
  16748. inc
  16749. (lambda: ([x : Integer]) : Integer (- x y)))])
  16750. (f 41)))
  16751. \end{lstlisting}
  16752. \fi}
  16753. {\if\edition\pythonEd\pythonColor
  16754. \begin{lstlisting}
  16755. def add1(x : int) -> int:
  16756. return x + 1
  16757. y = input_int()
  16758. g : Callable[[int], int] = lambda x: x - y
  16759. f = add1 if input_int() == 0 else g
  16760. print(f(41))
  16761. \end{lstlisting}
  16762. \fi}
  16763. \end{minipage}
  16764. \end{center}
  16765. If a global function name is used in any way other than as the
  16766. operator in a direct call, then we say that the function
  16767. \emph{escapes}. If a global function does not escape, then we do not
  16768. need to perform closure conversion on the function.
  16769. \begin{exercise}\normalfont\normalsize
  16770. Implement an auxiliary function for detecting which global
  16771. functions escape. Using that function, implement an improved version
  16772. of closure conversion that does not apply closure conversion to
  16773. global functions that do not escape but instead compiles them as
  16774. regular functions. Create several new test cases that check whether
  16775. your compiler properly detects whether global functions escape or not.
  16776. \end{exercise}
  16777. So far we have reduced the overhead of calling global functions, but
  16778. it would also be nice to reduce the overhead of calling a
  16779. \code{lambda} when we can determine at compile time which
  16780. \code{lambda} will be called. We refer to such calls as \emph{known
  16781. calls}. Consider the following example in which a \code{lambda} is
  16782. bound to \code{f} and then applied.
  16783. {\if\edition\racketEd
  16784. % lambda_test_9.rkt
  16785. \begin{lstlisting}
  16786. (let ([y (read)])
  16787. (let ([f (lambda: ([x : Integer]) : Integer
  16788. (+ x y))])
  16789. (f 21)))
  16790. \end{lstlisting}
  16791. \fi}
  16792. {\if\edition\pythonEd\pythonColor
  16793. \begin{lstlisting}
  16794. y = input_int()
  16795. f : Callable[[int],int] = lambda x: x + y
  16796. print(f(21))
  16797. \end{lstlisting}
  16798. \fi}
  16799. %
  16800. \noindent Closure conversion compiles the application
  16801. \CAPPLY{\code{f}}{\code{21}} into an indirect call, as follows:
  16802. %
  16803. {\if\edition\racketEd
  16804. \begin{lstlisting}
  16805. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  16806. (let ([y2 (vector-ref fvs6 1)])
  16807. (+ x3 y2)))
  16808. (define (main) : Integer
  16809. (let ([y2 (read)])
  16810. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16811. ((vector-ref f4 0) f4 21))))
  16812. \end{lstlisting}
  16813. \fi}
  16814. {\if\edition\pythonEd\pythonColor
  16815. \begin{lstlisting}
  16816. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  16817. y_1 = fvs_4[1]
  16818. return x_2 + y_1[0]
  16819. def main() -> int:
  16820. y_1 = (777,)
  16821. y_1[0] = input_int()
  16822. f_0 = (lambda_3, y_1)
  16823. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  16824. return 0
  16825. \end{lstlisting}
  16826. \fi}
  16827. %
  16828. \noindent However, we can instead compile the application
  16829. \CAPPLY{\code{f}}{\code{21}} into a direct call, as follows:
  16830. %
  16831. {\if\edition\racketEd
  16832. \begin{lstlisting}
  16833. (define (main) : Integer
  16834. (let ([y2 (read)])
  16835. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  16836. ((fun-ref lambda5 1) f4 21))))
  16837. \end{lstlisting}
  16838. \fi}
  16839. {\if\edition\pythonEd\pythonColor
  16840. \begin{lstlisting}
  16841. def main() -> int:
  16842. y_1 = (777,)
  16843. y_1[0] = input_int()
  16844. f_0 = (lambda_3, y_1)
  16845. print(lambda_3(f_0, 21))
  16846. return 0
  16847. \end{lstlisting}
  16848. \fi}
  16849. The problem of determining which \code{lambda} will be called from a
  16850. particular application is quite challenging in general and the topic
  16851. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  16852. following exercise we recommend that you compile an application to a
  16853. direct call when the operator is a variable and \racket{the variable
  16854. is \code{let}-bound to a closure}\python{the previous assignment to
  16855. the variable is a closure}. This can be accomplished by maintaining
  16856. an environment that maps variables to function names. Extend the
  16857. environment whenever you encounter a closure on the right-hand side of
  16858. \racket{a \code{let}}\python{an assignment}, mapping the variable to the
  16859. name of the global function for the closure. This pass should come
  16860. after closure conversion.
  16861. \begin{exercise}\normalfont\normalsize
  16862. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  16863. compiles known calls into direct calls. Verify that your compiler is
  16864. successful in this regard on several example programs.
  16865. \end{exercise}
  16866. These exercises only scratch the surface of closure optimization. A
  16867. good next step for the interested reader is to look at the work of
  16868. \citet{Keep:2012ab}.
  16869. \section{Further Reading}
  16870. The notion of lexically scoped functions predates modern computers by
  16871. about a decade. They were invented by \citet{Church:1932aa}, who
  16872. proposed the lambda calculus as a foundation for logic. Anonymous
  16873. functions were included in the LISP~\citep{McCarthy:1960dz}
  16874. programming language but were initially dynamically scoped. The Scheme
  16875. dialect of LISP adopted lexical scoping, and
  16876. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  16877. Scheme programs. However, environments were represented as linked
  16878. lists, so variable look-up was linear in the size of the
  16879. environment. \citet{Appel91} gives a detailed description of several
  16880. closure representations. In this chapter we represent environments
  16881. using flat closures, which were invented by
  16882. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purpose of compiling
  16883. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  16884. closures, variable look-up is constant time but the time to create a
  16885. closure is proportional to the number of its free variables. Flat
  16886. closures were reinvented by \citet{Dybvig:1987ab} in his PhD thesis
  16887. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  16888. % todo: related work on assignment conversion (e.g. orbit and rabbit
  16889. % compilers)
  16890. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16891. \chapter{Dynamic Typing}
  16892. \label{ch:Ldyn}
  16893. \index{subject}{dynamic typing}
  16894. \setcounter{footnote}{0}
  16895. In this chapter we learn how to compile \LangDyn{}, a dynamically
  16896. typed language that is a subset of \racket{Racket}\python{Python}. The
  16897. focus on dynamic typing is in contrast to the previous chapters, which
  16898. have studied the compilation of statically typed languages. In
  16899. dynamically typed languages such as \LangDyn{}, a particular
  16900. expression may produce a value of a different type each time it is
  16901. executed. Consider the following example with a conditional \code{if}
  16902. expression that may return a Boolean or an integer depending on the
  16903. input to the program:
  16904. % part of dynamic_test_25.rkt
  16905. {\if\edition\racketEd
  16906. \begin{lstlisting}
  16907. (not (if (eq? (read) 1) #f 0))
  16908. \end{lstlisting}
  16909. \fi}
  16910. {\if\edition\pythonEd\pythonColor
  16911. \begin{lstlisting}
  16912. not (False if input_int() == 1 else 0)
  16913. \end{lstlisting}
  16914. \fi}
  16915. Languages that allow expressions to produce different kinds of values
  16916. are called \emph{polymorphic}, a word composed of the Greek roots
  16917. \emph{poly}, meaning \emph{many}, and \emph{morph}, meaning \emph{form}.
  16918. There are several kinds of polymorphism in programming languages, such as
  16919. subtype polymorphism\index{subject}{subtype polymorphism} and
  16920. parametric polymorphism\index{subject}{parametric polymorphism}
  16921. (aka generics)~\citep{Cardelli:1985kx}. The kind of polymorphism that we
  16922. study in this chapter does not have a special name; it is the kind
  16923. that arises in dynamically typed languages.
  16924. Another characteristic of dynamically typed languages is that
  16925. their primitive operations, such as \code{not}, are often defined to operate
  16926. on many different types of values. In fact, in
  16927. \racket{Racket}\python{Python}, the \code{not} operator produces a
  16928. result for any kind of value: given \FALSE{} it returns \TRUE{}, and
  16929. given anything else it returns \FALSE{}.
  16930. Furthermore, even when primitive operations restrict their inputs to
  16931. values of a certain type, this restriction is enforced at runtime
  16932. instead of during compilation. For example, the tuple read
  16933. operation \racket{\code{(vector-ref \#t 0)}}\python{\code{True[0]}}
  16934. results in a runtime error because the first argument must
  16935. be a tuple, not a Boolean.
  16936. \section{The \LangDyn{} Language}
  16937. \newcommand{\LdynGrammarRacket}{
  16938. \begin{array}{rcl}
  16939. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  16940. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  16941. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  16942. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  16943. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  16944. \end{array}
  16945. }
  16946. \newcommand{\LdynASTRacket}{
  16947. \begin{array}{lcl}
  16948. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16949. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  16950. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  16951. \end{array}
  16952. }
  16953. \begin{figure}[tp]
  16954. \centering
  16955. \begin{tcolorbox}[colback=white]
  16956. \small
  16957. {\if\edition\racketEd
  16958. \[
  16959. \begin{array}{l}
  16960. \gray{\LintGrammarRacket{}} \\ \hline
  16961. \gray{\LvarGrammarRacket{}} \\ \hline
  16962. \gray{\LifGrammarRacket{}} \\ \hline
  16963. \gray{\LwhileGrammarRacket} \\ \hline
  16964. \gray{\LtupGrammarRacket} \\ \hline
  16965. \LdynGrammarRacket \\
  16966. \begin{array}{rcl}
  16967. \LangDynM{} &::=& \Def\ldots\; \Exp
  16968. \end{array}
  16969. \end{array}
  16970. \]
  16971. \fi}
  16972. {\if\edition\pythonEd\pythonColor
  16973. \[
  16974. \begin{array}{rcl}
  16975. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  16976. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  16977. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  16978. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  16979. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  16980. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  16981. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  16982. \MID \CLEN{\Exp} \\
  16983. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  16984. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  16985. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  16986. \MID \Var\mathop{\key{=}}\Exp \\
  16987. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  16988. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  16989. &\MID& \CRETURN{\Exp} \\
  16990. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  16991. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  16992. \end{array}
  16993. \]
  16994. \fi}
  16995. \end{tcolorbox}
  16996. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  16997. \label{fig:r7-concrete-syntax}
  16998. \end{figure}
  16999. \begin{figure}[tp]
  17000. \centering
  17001. \begin{tcolorbox}[colback=white]
  17002. \small
  17003. {\if\edition\racketEd
  17004. \[
  17005. \begin{array}{l}
  17006. \gray{\LintASTRacket{}} \\ \hline
  17007. \gray{\LvarASTRacket{}} \\ \hline
  17008. \gray{\LifASTRacket{}} \\ \hline
  17009. \gray{\LwhileASTRacket} \\ \hline
  17010. \gray{\LtupASTRacket} \\ \hline
  17011. \LdynASTRacket \\
  17012. \begin{array}{lcl}
  17013. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17014. \end{array}
  17015. \end{array}
  17016. \]
  17017. \fi}
  17018. {\if\edition\pythonEd\pythonColor
  17019. \[
  17020. \begin{array}{rcl}
  17021. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  17022. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  17023. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()}
  17024. \MID \code{Is()} \\
  17025. \itm{bool} &::=& \code{True} \MID \code{False} \\
  17026. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  17027. &\MID& \UNIOP{\key{USub()}}{\Exp}\\
  17028. &\MID& \BINOP{\Exp}{\key{Add()}}{\Exp}
  17029. \MID \BINOP{\Exp}{\key{Sub()}}{\Exp} \\
  17030. &\MID& \VAR{\Var{}}
  17031. \MID \BOOL{\itm{bool}}
  17032. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  17033. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  17034. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  17035. &\MID& \LEN{\Exp} \\
  17036. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  17037. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  17038. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  17039. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  17040. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  17041. &\MID& \RETURN{\Exp} \\
  17042. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  17043. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  17044. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17045. \end{array}
  17046. \]
  17047. \fi}
  17048. \end{tcolorbox}
  17049. \caption{The abstract syntax of \LangDyn{}.}
  17050. \label{fig:r7-syntax}
  17051. \end{figure}
  17052. The definitions of the concrete and abstract syntax of \LangDyn{} are
  17053. shown in figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  17054. %
  17055. There is no type checker for \LangDyn{} because it checks types only
  17056. at runtime.
  17057. The definitional interpreter for \LangDyn{} is presented in
  17058. \racket{figure~\ref{fig:interp-Ldyn}}\python{figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}, and definitions of its auxiliary functions
  17059. are shown in figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  17060. \INT{n}. Instead of simply returning the integer \code{n} (as
  17061. in the interpreter for \LangVar{} in figure~\ref{fig:interp-Lvar}), the
  17062. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  17063. value} that combines an underlying value with a tag that identifies
  17064. what kind of value it is. We define the following \racket{struct}\python{class}
  17065. to represent tagged values:
  17066. %
  17067. {\if\edition\racketEd
  17068. \begin{lstlisting}
  17069. (struct Tagged (value tag) #:transparent)
  17070. \end{lstlisting}
  17071. \fi}
  17072. {\if\edition\pythonEd\pythonColor
  17073. \begin{minipage}{\textwidth}
  17074. \begin{lstlisting}
  17075. @dataclass(eq=True)
  17076. class Tagged(Value):
  17077. value : Value
  17078. tag : str
  17079. def __str__(self):
  17080. return str(self.value)
  17081. \end{lstlisting}
  17082. \end{minipage}
  17083. \fi}
  17084. %
  17085. \racket{The tags are \code{Integer}, \BOOLTY{}, \code{Void},
  17086. \code{Vector}, and \code{Procedure}.}
  17087. %
  17088. \python{The tags are \skey{int}, \skey{bool}, \skey{none},
  17089. \skey{tuple}, and \skey{function}.}
  17090. %
  17091. Tags are closely related to types but do not always capture all the
  17092. information that a type does.
  17093. %
  17094. \racket{For example, a vector of type \code{(Vector Any Any)} is
  17095. tagged with \code{Vector}, and a procedure of type \code{(Any Any ->
  17096. Any)} is tagged with \code{Procedure}.}
  17097. %
  17098. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  17099. is tagged with \skey{tuple} and a function of type
  17100. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  17101. is tagged with \skey{function}.}
  17102. Next consider the match case for accessing the element of a tuple.
  17103. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  17104. (figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  17105. argument is a tuple and the second is an integer.
  17106. \racket{
  17107. If they are not, a \code{trapped-error} is raised. Recall from
  17108. section~\ref{sec:interp_Lint} that when a definition interpreter
  17109. raises a \code{trapped-error} error, the compiled code must also
  17110. signal an error by exiting with return code \code{255}. A
  17111. \code{trapped-error} is also raised if the index is not less than the
  17112. length of the vector.
  17113. }
  17114. %
  17115. \python{If they are not, an exception is raised. The compiled code
  17116. must also signal an error by exiting with return code \code{255}. A
  17117. exception is also raised if the index is not less than the length of the
  17118. tuple or if it is negative.}
  17119. \begin{figure}[tbp]
  17120. \begin{tcolorbox}[colback=white]
  17121. {\if\edition\racketEd
  17122. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17123. (define ((interp-Ldyn-exp env) ast)
  17124. (define recur (interp-Ldyn-exp env))
  17125. (match ast
  17126. [(Var x) (dict-ref env x)]
  17127. [(Int n) (Tagged n 'Integer)]
  17128. [(Bool b) (Tagged b 'Boolean)]
  17129. [(Lambda xs rt body)
  17130. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  17131. [(Prim 'vector es)
  17132. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  17133. [(Prim 'vector-ref (list e1 e2))
  17134. (define vec (recur e1)) (define i (recur e2))
  17135. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17136. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17137. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17138. (vector-ref (Tagged-value vec) (Tagged-value i))]
  17139. [(Prim 'vector-set! (list e1 e2 e3))
  17140. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  17141. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  17142. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  17143. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  17144. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  17145. (Tagged (void) 'Void)]
  17146. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  17147. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  17148. [(Prim 'or (list e1 e2))
  17149. (define v1 (recur e1))
  17150. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  17151. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  17152. [(Prim op (list e1))
  17153. #:when (set-member? type-predicates op)
  17154. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  17155. [(Prim op es)
  17156. (define args (map recur es))
  17157. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  17158. (unless (for/or ([expected-tags (op-tags op)])
  17159. (equal? expected-tags tags))
  17160. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  17161. (tag-value
  17162. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  17163. [(If q t f)
  17164. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  17165. [(Apply f es)
  17166. (define new-f (recur f)) (define args (map recur es))
  17167. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  17168. (match f-val
  17169. [`(function ,xs ,body ,lam-env)
  17170. (unless (eq? (length xs) (length args))
  17171. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  17172. (define new-env (append (map cons xs args) lam-env))
  17173. ((interp-Ldyn-exp new-env) body)]
  17174. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  17175. \end{lstlisting}
  17176. \fi}
  17177. {\if\edition\pythonEd\pythonColor
  17178. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17179. class InterpLdyn(InterpLlambda):
  17180. def interp_exp(self, e, env):
  17181. match e:
  17182. case Constant(n):
  17183. return self.tag(super().interp_exp(e, env))
  17184. case Tuple(es, Load()):
  17185. return self.tag(super().interp_exp(e, env))
  17186. case Lambda(params, body):
  17187. return self.tag(super().interp_exp(e, env))
  17188. case Call(Name('input_int'), []):
  17189. return self.tag(super().interp_exp(e, env))
  17190. case BinOp(left, Add(), right):
  17191. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17192. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  17193. case BinOp(left, Sub(), right):
  17194. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  17195. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  17196. case UnaryOp(USub(), e1):
  17197. v = self.interp_exp(e1, env)
  17198. return self.tag(- self.untag(v, 'int', e))
  17199. case IfExp(test, body, orelse):
  17200. v = self.interp_exp(test, env)
  17201. if self.untag(v, 'bool', e):
  17202. return self.interp_exp(body, env)
  17203. else:
  17204. return self.interp_exp(orelse, env)
  17205. case UnaryOp(Not(), e1):
  17206. v = self.interp_exp(e1, env)
  17207. return self.tag(not self.untag(v, 'bool', e))
  17208. case BoolOp(And(), values):
  17209. left = values[0]; right = values[1]
  17210. l = self.interp_exp(left, env)
  17211. if self.untag(l, 'bool', e):
  17212. return self.interp_exp(right, env)
  17213. else:
  17214. return self.tag(False)
  17215. case BoolOp(Or(), values):
  17216. left = values[0]; right = values[1]
  17217. l = self.interp_exp(left, env)
  17218. if self.untag(l, 'bool', e):
  17219. return self.tag(True)
  17220. else:
  17221. return self.interp_exp(right, env)
  17222. \end{lstlisting}
  17223. \fi}
  17224. \end{tcolorbox}
  17225. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  17226. \label{fig:interp-Ldyn}
  17227. \end{figure}
  17228. {\if\edition\pythonEd\pythonColor
  17229. \begin{figure}[tbp]
  17230. \begin{tcolorbox}[colback=white]
  17231. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17232. # interp_exp continued
  17233. case Compare(left, [cmp], [right]):
  17234. l = self.interp_exp(left, env)
  17235. r = self.interp_exp(right, env)
  17236. if l.tag == r.tag:
  17237. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  17238. else:
  17239. raise Exception('interp Compare unexpected '
  17240. + repr(l) + ' ' + repr(r))
  17241. case Subscript(tup, index, Load()):
  17242. t = self.interp_exp(tup, env)
  17243. n = self.interp_exp(index, env)
  17244. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  17245. case Call(Name('len'), [tup]):
  17246. t = self.interp_exp(tup, env)
  17247. return self.tag(len(self.untag(t, 'tuple', e)))
  17248. case _:
  17249. return self.tag(super().interp_exp(e, env))
  17250. def interp_stmt(self, s, env, cont):
  17251. match s:
  17252. case If(test, body, orelse):
  17253. v = self.interp_exp(test, env)
  17254. match self.untag(v, 'bool', s):
  17255. case True:
  17256. return self.interp_stmts(body + cont, env)
  17257. case False:
  17258. return self.interp_stmts(orelse + cont, env)
  17259. case While(test, body, []):
  17260. v = self.interp_exp(test, env)
  17261. if self.untag(v, 'bool', test):
  17262. self.interp_stmts(body + [s] + cont, env)
  17263. else:
  17264. return self.interp_stmts(cont, env)
  17265. case Assign([Subscript(tup, index)], value):
  17266. tup = self.interp_exp(tup, env)
  17267. index = self.interp_exp(index, env)
  17268. tup_v = self.untag(tup, 'tuple', s)
  17269. index_v = self.untag(index, 'int', s)
  17270. tup_v[index_v] = self.interp_exp(value, env)
  17271. return self.interp_stmts(cont, env)
  17272. case FunctionDef(name, params, bod, dl, returns, comment):
  17273. if isinstance(params, ast.arguments):
  17274. ps = [p.arg for p in params.args]
  17275. else:
  17276. ps = [x for (x,t) in params]
  17277. env[name] = self.tag(Function(name, ps, bod, env))
  17278. return self.interp_stmts(cont, env)
  17279. case _:
  17280. return super().interp_stmt(s, env, cont)
  17281. \end{lstlisting}
  17282. \end{tcolorbox}
  17283. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  17284. \label{fig:interp-Ldyn-2}
  17285. \end{figure}
  17286. \fi}
  17287. \begin{figure}[tbp]
  17288. \begin{tcolorbox}[colback=white]
  17289. {\if\edition\racketEd
  17290. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17291. (define (interp-op op)
  17292. (match op
  17293. ['+ fx+]
  17294. ['- fx-]
  17295. ['read read-fixnum]
  17296. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  17297. ['< (lambda (v1 v2)
  17298. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  17299. ['<= (lambda (v1 v2)
  17300. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  17301. ['> (lambda (v1 v2)
  17302. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  17303. ['>= (lambda (v1 v2)
  17304. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  17305. ['boolean? boolean?]
  17306. ['integer? fixnum?]
  17307. ['void? void?]
  17308. ['vector? vector?]
  17309. ['vector-length vector-length]
  17310. ['procedure? (match-lambda
  17311. [`(functions ,xs ,body ,env) #t] [else #f])]
  17312. [else (error 'interp-op "unknown operator" op)]))
  17313. (define (op-tags op)
  17314. (match op
  17315. ['+ '((Integer Integer))]
  17316. ['- '((Integer Integer) (Integer))]
  17317. ['read '(())]
  17318. ['not '((Boolean))]
  17319. ['< '((Integer Integer))]
  17320. ['<= '((Integer Integer))]
  17321. ['> '((Integer Integer))]
  17322. ['>= '((Integer Integer))]
  17323. ['vector-length '((Vector))]))
  17324. (define type-predicates
  17325. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17326. (define (tag-value v)
  17327. (cond [(boolean? v) (Tagged v 'Boolean)]
  17328. [(fixnum? v) (Tagged v 'Integer)]
  17329. [(procedure? v) (Tagged v 'Procedure)]
  17330. [(vector? v) (Tagged v 'Vector)]
  17331. [(void? v) (Tagged v 'Void)]
  17332. [else (error 'tag-value "unidentified value ~a" v)]))
  17333. (define (check-tag val expected ast)
  17334. (define tag (Tagged-tag val))
  17335. (unless (eq? tag expected)
  17336. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  17337. \end{lstlisting}
  17338. \fi}
  17339. {\if\edition\pythonEd\pythonColor
  17340. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17341. class InterpLdyn(InterpLlambda):
  17342. def tag(self, v):
  17343. if v is True or v is False:
  17344. return Tagged(v, 'bool')
  17345. elif isinstance(v, int):
  17346. return Tagged(v, 'int')
  17347. elif isinstance(v, Function):
  17348. return Tagged(v, 'function')
  17349. elif isinstance(v, tuple):
  17350. return Tagged(v, 'tuple')
  17351. elif isinstance(v, type(None)):
  17352. return Tagged(v, 'none')
  17353. else:
  17354. raise Exception('tag: unexpected ' + repr(v))
  17355. def untag(self, v, expected_tag, ast):
  17356. match v:
  17357. case Tagged(val, tag) if tag == expected_tag:
  17358. return val
  17359. case _:
  17360. raise TrappedError('expected Tagged value with '
  17361. + expected_tag + ', not ' + ' ' + repr(v))
  17362. def apply_fun(self, fun, args, e):
  17363. f = self.untag(fun, 'function', e)
  17364. return super().apply_fun(f, args, e)
  17365. \end{lstlisting}
  17366. \fi}
  17367. \end{tcolorbox}
  17368. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  17369. \label{fig:interp-Ldyn-aux}
  17370. \end{figure}
  17371. %\clearpage
  17372. \section{Representation of Tagged Values}
  17373. The interpreter for \LangDyn{} introduced a new kind of value: the
  17374. tagged value. To compile \LangDyn{} to x86 we must decide how to
  17375. represent tagged values at the bit level. Because almost every
  17376. operation in \LangDyn{} involves manipulating tagged values, the
  17377. representation must be efficient. Recall that all our values are 64
  17378. bits. We shall steal the right-most $3$ bits to encode the tag. We use
  17379. $001$ to identify integers, $100$ for Booleans, $010$ for tuples,
  17380. $011$ for procedures, and $101$ for the void value\python{,
  17381. \key{None}}. We define the following auxiliary function for mapping
  17382. types to tag codes:
  17383. %
  17384. {\if\edition\racketEd
  17385. \begin{align*}
  17386. \itm{tagof}(\key{Integer}) &= 001 \\
  17387. \itm{tagof}(\key{Boolean}) &= 100 \\
  17388. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  17389. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  17390. \itm{tagof}(\key{Void}) &= 101
  17391. \end{align*}
  17392. \fi}
  17393. {\if\edition\pythonEd\pythonColor
  17394. \begin{align*}
  17395. \itm{tagof}(\key{IntType()}) &= 001 \\
  17396. \itm{tagof}(\key{BoolType()}) &= 100 \\
  17397. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  17398. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  17399. \itm{tagof}(\key{type(None)}) &= 101
  17400. \end{align*}
  17401. \fi}
  17402. %
  17403. This stealing of 3 bits comes at some price: integers are now restricted
  17404. to the range $-2^{60}$ to $2^{60}-1$. The stealing does not adversely
  17405. affect tuples and procedures because those values are addresses, and
  17406. our addresses are 8-byte aligned so the rightmost 3 bits are unused;
  17407. they are always $000$. Thus, we do not lose information by overwriting
  17408. the rightmost 3 bits with the tag, and we can simply zero out the tag
  17409. to recover the original address.
  17410. To make tagged values into first-class entities, we can give them a
  17411. type called \racket{\code{Any}}\python{\code{AnyType}} and define
  17412. operations such as \code{Inject} and \code{Project} for creating and
  17413. using them, yielding the statically typed \LangAny{} intermediate
  17414. language. We describe how to compile \LangDyn{} to \LangAny{} in
  17415. section~\ref{sec:compile-r7}; in the next section we describe the
  17416. \LangAny{} language in greater detail.
  17417. \section{The \LangAny{} Language}
  17418. \label{sec:Rany-lang}
  17419. \newcommand{\LanyASTRacket}{
  17420. \begin{array}{lcl}
  17421. \Type &::= & \ANYTY \\
  17422. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  17423. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  17424. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  17425. \itm{op} &::= & \code{any-vector-length}
  17426. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  17427. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  17428. \MID \code{procedure?} \MID \code{void?} \\
  17429. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  17430. \end{array}
  17431. }
  17432. \newcommand{\LanyASTPython}{
  17433. \begin{array}{lcl}
  17434. \Type &::= & \key{AnyType()} \\
  17435. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  17436. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  17437. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  17438. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  17439. &\MID& \CALL{\VAR{\skey{any\_tuple\_load}}}{\LS\Exp\key{, }\Exp\RS}\\
  17440. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS\Exp\RS} \\
  17441. &\MID& \CALL{\VAR{\skey{arity}}}{\LS\Exp\RS} \\
  17442. &\MID& \CALL{\VAR{\skey{make\_any}}}{\LS\Exp\key{, }\INT{\Int}\RS}
  17443. %% &\MID& \CALL{\VAR{\skey{is\_int}}}{\Exp}
  17444. %% \MID \CALL{\VAR{\skey{is\_bool}}}{\Exp} \\
  17445. %% &\MID& \CALL{\VAR{\skey{is\_none}}}{\Exp}
  17446. %% \MID \CALL{\VAR{\skey{is\_tuple}}}{\Exp} \\
  17447. %% &\MID& \CALL{\VAR{\skey{is\_function}}}{\Exp}
  17448. \end{array}
  17449. }
  17450. \begin{figure}[tp]
  17451. \centering
  17452. \begin{tcolorbox}[colback=white]
  17453. \small
  17454. {\if\edition\racketEd
  17455. \[
  17456. \begin{array}{l}
  17457. \gray{\LintOpAST} \\ \hline
  17458. \gray{\LvarASTRacket{}} \\ \hline
  17459. \gray{\LifASTRacket{}} \\ \hline
  17460. \gray{\LwhileASTRacket{}} \\ \hline
  17461. \gray{\LtupASTRacket{}} \\ \hline
  17462. \gray{\LfunASTRacket} \\ \hline
  17463. \gray{\LlambdaASTRacket} \\ \hline
  17464. \LanyASTRacket \\
  17465. \begin{array}{lcl}
  17466. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  17467. \end{array}
  17468. \end{array}
  17469. \]
  17470. \fi}
  17471. {\if\edition\pythonEd\pythonColor
  17472. \[
  17473. \begin{array}{l}
  17474. \gray{\LintASTPython} \\ \hline
  17475. \gray{\LvarASTPython{}} \\ \hline
  17476. \gray{\LifASTPython{}} \\ \hline
  17477. \gray{\LwhileASTPython{}} \\ \hline
  17478. \gray{\LtupASTPython{}} \\ \hline
  17479. \gray{\LfunASTPython} \\ \hline
  17480. \gray{\LlambdaASTPython} \\ \hline
  17481. \LanyASTPython \\
  17482. \begin{array}{lcl}
  17483. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  17484. \end{array}
  17485. \end{array}
  17486. \]
  17487. \fi}
  17488. \end{tcolorbox}
  17489. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (figure~\ref{fig:Llam-syntax}).}
  17490. \label{fig:Lany-syntax}
  17491. \end{figure}
  17492. The definition of the abstract syntax of \LangAny{} is given in
  17493. figure~\ref{fig:Lany-syntax}.
  17494. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  17495. %% figure~\ref{fig:Lany-concrete-syntax}.)}
  17496. The $\INJECT{e}{T}$ form converts the value produced by expression $e$
  17497. of type $T$ into a tagged value. The $\PROJECT{e}{T}$ form either
  17498. converts the tagged value produced by expression $e$ into a value of
  17499. type $T$ or halts the program if the type tag does not match $T$.
  17500. %
  17501. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  17502. restricted to be a flat type (the nonterminal $\FType$) which
  17503. simplifies the implementation and complies with the needs for
  17504. compiling \LangDyn{}.
  17505. The \racket{\code{any-vector}} operators
  17506. \python{\code{any\_tuple\_load} and \code{any\_len}} adapt the tuple
  17507. operations so that they can be applied to a value of type
  17508. \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  17509. tuple operations in that the index is not restricted to a literal
  17510. integer in the grammar but is allowed to be any expression.
  17511. \racket{The type predicates such as
  17512. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  17513. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  17514. the predicate and return {\FALSE} otherwise.}
  17515. The type checker for \LangAny{} is shown in
  17516. figure~\ref{fig:type-check-Lany}
  17517. %
  17518. \racket{ and uses the auxiliary functions presented in
  17519. figure~\ref{fig:type-check-Lany-aux}}.
  17520. %
  17521. The interpreter for \LangAny{} is shown in figure~\ref{fig:interp-Lany} and
  17522. its auxiliary functions are shown in figure~\ref{fig:interp-Lany-aux}.
  17523. \begin{figure}[btp]
  17524. \begin{tcolorbox}[colback=white]
  17525. {\if\edition\racketEd
  17526. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17527. (define type-check-Lany-class
  17528. (class type-check-Llambda-class
  17529. (super-new)
  17530. (inherit check-type-equal?)
  17531. (define/override (type-check-exp env)
  17532. (lambda (e)
  17533. (define recur (type-check-exp env))
  17534. (match e
  17535. [(Inject e1 ty)
  17536. (unless (flat-ty? ty)
  17537. (error 'type-check "may only inject from flat type, not ~a" ty))
  17538. (define-values (new-e1 e-ty) (recur e1))
  17539. (check-type-equal? e-ty ty e)
  17540. (values (Inject new-e1 ty) 'Any)]
  17541. [(Project e1 ty)
  17542. (unless (flat-ty? ty)
  17543. (error 'type-check "may only project to flat type, not ~a" ty))
  17544. (define-values (new-e1 e-ty) (recur e1))
  17545. (check-type-equal? e-ty 'Any e)
  17546. (values (Project new-e1 ty) ty)]
  17547. [(Prim 'any-vector-length (list e1))
  17548. (define-values (e1^ t1) (recur e1))
  17549. (check-type-equal? t1 'Any e)
  17550. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  17551. [(Prim 'any-vector-ref (list e1 e2))
  17552. (define-values (e1^ t1) (recur e1))
  17553. (define-values (e2^ t2) (recur e2))
  17554. (check-type-equal? t1 'Any e)
  17555. (check-type-equal? t2 'Integer e)
  17556. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  17557. [(Prim 'any-vector-set! (list e1 e2 e3))
  17558. (define-values (e1^ t1) (recur e1))
  17559. (define-values (e2^ t2) (recur e2))
  17560. (define-values (e3^ t3) (recur e3))
  17561. (check-type-equal? t1 'Any e)
  17562. (check-type-equal? t2 'Integer e)
  17563. (check-type-equal? t3 'Any e)
  17564. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  17565. [(Prim pred (list e1))
  17566. #:when (set-member? (type-predicates) pred)
  17567. (define-values (new-e1 e-ty) (recur e1))
  17568. (check-type-equal? e-ty 'Any e)
  17569. (values (Prim pred (list new-e1)) 'Boolean)]
  17570. [(Prim 'eq? (list arg1 arg2))
  17571. (define-values (e1 t1) (recur arg1))
  17572. (define-values (e2 t2) (recur arg2))
  17573. (match* (t1 t2)
  17574. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  17575. [(other wise) (check-type-equal? t1 t2 e)])
  17576. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  17577. [else ((super type-check-exp env) e)])))
  17578. ))
  17579. \end{lstlisting}
  17580. \fi}
  17581. {\if\edition\pythonEd\pythonColor
  17582. \begin{lstlisting}
  17583. class TypeCheckLany(TypeCheckLlambda):
  17584. def type_check_exp(self, e, env):
  17585. match e:
  17586. case Inject(value, typ):
  17587. self.check_exp(value, typ, env)
  17588. return AnyType()
  17589. case Project(value, typ):
  17590. self.check_exp(value, AnyType(), env)
  17591. return typ
  17592. case Call(Name('any_tuple_load'), [tup, index]):
  17593. self.check_exp(tup, AnyType(), env)
  17594. self.check_exp(index, IntType(), env)
  17595. return AnyType()
  17596. case Call(Name('any_len'), [tup]):
  17597. self.check_exp(tup, AnyType(), env)
  17598. return IntType()
  17599. case Call(Name('arity'), [fun]):
  17600. ty = self.type_check_exp(fun, env)
  17601. match ty:
  17602. case FunctionType(ps, rt):
  17603. return IntType()
  17604. case TupleType([FunctionType(ps,rs)]):
  17605. return IntType()
  17606. case _:
  17607. raise Exception('type check arity unexpected ' + repr(ty))
  17608. case Call(Name('make_any'), [value, tag]):
  17609. self.type_check_exp(value, env)
  17610. self.check_exp(tag, IntType(), env)
  17611. return AnyType()
  17612. case AnnLambda(params, returns, body):
  17613. new_env = {x:t for (x,t) in env.items()}
  17614. for (x,t) in params:
  17615. new_env[x] = t
  17616. return_t = self.type_check_exp(body, new_env)
  17617. self.check_type_equal(returns, return_t, e)
  17618. return FunctionType([t for (x,t) in params], return_t)
  17619. case _:
  17620. return super().type_check_exp(e, env)
  17621. \end{lstlisting}
  17622. \fi}
  17623. \end{tcolorbox}
  17624. \caption{Type checker for the \LangAny{} language.}
  17625. \label{fig:type-check-Lany}
  17626. \end{figure}
  17627. {\if\edition\racketEd
  17628. \begin{figure}[tbp]
  17629. \begin{tcolorbox}[colback=white]
  17630. \begin{lstlisting}
  17631. (define/override (operator-types)
  17632. (append
  17633. '((integer? . ((Any) . Boolean))
  17634. (vector? . ((Any) . Boolean))
  17635. (procedure? . ((Any) . Boolean))
  17636. (void? . ((Any) . Boolean)))
  17637. (super operator-types)))
  17638. (define/public (type-predicates)
  17639. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  17640. (define/public (flat-ty? ty)
  17641. (match ty
  17642. [(or `Integer `Boolean `Void) #t]
  17643. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  17644. [`(,ts ... -> ,rt)
  17645. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  17646. [else #f]))
  17647. \end{lstlisting}
  17648. \end{tcolorbox}
  17649. \caption{Auxiliary methods for type checking \LangAny{}.}
  17650. \label{fig:type-check-Lany-aux}
  17651. \end{figure}
  17652. \fi}
  17653. \begin{figure}[tbp]
  17654. \begin{tcolorbox}[colback=white]
  17655. {\if\edition\racketEd
  17656. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17657. (define interp-Lany-class
  17658. (class interp-Llambda-class
  17659. (super-new)
  17660. (define/override (interp-op op)
  17661. (match op
  17662. ['boolean? (match-lambda
  17663. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  17664. [else #f])]
  17665. ['integer? (match-lambda
  17666. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  17667. [else #f])]
  17668. ['vector? (match-lambda
  17669. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  17670. [else #f])]
  17671. ['procedure? (match-lambda
  17672. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  17673. [else #f])]
  17674. ['eq? (match-lambda*
  17675. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  17676. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  17677. [ls (apply (super interp-op op) ls)])]
  17678. ['any-vector-ref (lambda (v i)
  17679. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  17680. ['any-vector-set! (lambda (v i a)
  17681. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  17682. ['any-vector-length (lambda (v)
  17683. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  17684. [else (super interp-op op)]))
  17685. (define/override ((interp-exp env) e)
  17686. (define recur (interp-exp env))
  17687. (match e
  17688. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  17689. [(Project e ty2) (apply-project (recur e) ty2)]
  17690. [else ((super interp-exp env) e)]))
  17691. ))
  17692. (define (interp-Lany p)
  17693. (send (new interp-Lany-class) interp-program p))
  17694. \end{lstlisting}
  17695. \fi}
  17696. {\if\edition\pythonEd\pythonColor
  17697. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17698. class InterpLany(InterpLlambda):
  17699. def interp_exp(self, e, env):
  17700. match e:
  17701. case Inject(value, typ):
  17702. return Tagged(self.interp_exp(value, env), self.type_to_tag(typ))
  17703. case Project(value, typ):
  17704. match self.interp_exp(value, env):
  17705. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  17706. return val
  17707. case _:
  17708. raise Exception('failed project to ' + self.type_to_tag(typ))
  17709. case Call(Name('any_tuple_load'), [tup, index]):
  17710. match self.interp_exp(tup, env):
  17711. case Tagged(v, tag):
  17712. return v[self.interp_exp(index, env)]
  17713. case _:
  17714. raise Exception('in any_tuple_load untagged value')
  17715. case Call(Name('any_len'), [value]):
  17716. match self.interp_exp(value, env):
  17717. case Tagged(value, tag):
  17718. return len(value)
  17719. case _:
  17720. raise Exception('interp any_len untagged value')
  17721. case Call(Name('arity'), [fun]):
  17722. return self.arity(self.interp_exp(fun, env))
  17723. case _:
  17724. return super().interp_exp(e, env)
  17725. \end{lstlisting}
  17726. \fi}
  17727. \end{tcolorbox}
  17728. \caption{Interpreter for \LangAny{}.}
  17729. \label{fig:interp-Lany}
  17730. \end{figure}
  17731. \begin{figure}[btp]
  17732. \begin{tcolorbox}[colback=white]
  17733. {\if\edition\racketEd
  17734. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17735. (define/public (apply-inject v tg) (Tagged v tg))
  17736. (define/public (apply-project v ty2)
  17737. (define tag2 (any-tag ty2))
  17738. (match v
  17739. [(Tagged v1 tag1)
  17740. (cond
  17741. [(eq? tag1 tag2)
  17742. (match ty2
  17743. [`(Vector ,ts ...)
  17744. (define l1 ((interp-op 'vector-length) v1))
  17745. (cond
  17746. [(eq? l1 (length ts)) v1]
  17747. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  17748. l1 (length ts))])]
  17749. [`(,ts ... -> ,rt)
  17750. (match v1
  17751. [`(function ,xs ,body ,env)
  17752. (cond [(eq? (length xs) (length ts)) v1]
  17753. [else
  17754. (error 'apply-project "arity mismatch ~a != ~a"
  17755. (length xs) (length ts))])]
  17756. [else (error 'apply-project "expected function not ~a" v1)])]
  17757. [else v1])]
  17758. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  17759. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  17760. \end{lstlisting}
  17761. \fi}
  17762. {\if\edition\pythonEd\pythonColor
  17763. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17764. class InterpLany(InterpLlambda):
  17765. def type_to_tag(self, typ):
  17766. match typ:
  17767. case FunctionType(params, rt):
  17768. return 'function'
  17769. case TupleType(fields):
  17770. return 'tuple'
  17771. case IntType():
  17772. return 'int'
  17773. case BoolType():
  17774. return 'bool'
  17775. case _:
  17776. raise Exception('type_to_tag unexpected ' + repr(typ))
  17777. def arity(self, v):
  17778. match v:
  17779. case Function(name, params, body, env):
  17780. return len(params)
  17781. case _:
  17782. raise Exception('Lany arity unexpected ' + repr(v))
  17783. \end{lstlisting}
  17784. \fi}
  17785. \end{tcolorbox}
  17786. \caption{Auxiliary functions for interpreting \LangAny{}.}
  17787. \label{fig:interp-Lany-aux}
  17788. \end{figure}
  17789. \clearpage
  17790. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  17791. \label{sec:compile-r7}
  17792. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  17793. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  17794. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  17795. is that given any subexpression $e$ in the \LangDyn{} program, the
  17796. pass will produce an expression $e'$ in \LangAny{} that has type
  17797. \ANYTY{}. For example, the first row in
  17798. figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  17799. \TRUE{}, which must be injected to produce an expression of type
  17800. \ANYTY{}.
  17801. %
  17802. The compilation of addition is shown in the second row of
  17803. figure~\ref{fig:compile-r7-Lany}. The compilation of addition is
  17804. representative of many primitive operations: the arguments have type
  17805. \ANYTY{} and must be projected to \INTTYPE{} before the addition can
  17806. be performed.
  17807. The compilation of \key{lambda} (third row of
  17808. figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  17809. produce type annotations: we simply use \ANYTY{}.
  17810. %
  17811. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  17812. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  17813. this pass has to account for some differences in behavior between
  17814. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  17815. permissive than \LangAny{} regarding what kind of values can be used
  17816. in various places. For example, the condition of an \key{if} does
  17817. not have to be a Boolean. For \key{eq?}, the arguments need not be
  17818. of the same type (in that case the result is \code{\#f}).}
  17819. \begin{figure}[btp]
  17820. \centering
  17821. \begin{tcolorbox}[colback=white]
  17822. {\if\edition\racketEd
  17823. \begin{tabular}{lll}
  17824. \begin{minipage}{0.27\textwidth}
  17825. \begin{lstlisting}
  17826. #t
  17827. \end{lstlisting}
  17828. \end{minipage}
  17829. &
  17830. $\Rightarrow$
  17831. &
  17832. \begin{minipage}{0.65\textwidth}
  17833. \begin{lstlisting}
  17834. (inject #t Boolean)
  17835. \end{lstlisting}
  17836. \end{minipage}
  17837. \\[2ex]\hline
  17838. \begin{minipage}{0.27\textwidth}
  17839. \begin{lstlisting}
  17840. (+ |$e_1$| |$e_2$|)
  17841. \end{lstlisting}
  17842. \end{minipage}
  17843. &
  17844. $\Rightarrow$
  17845. &
  17846. \begin{minipage}{0.65\textwidth}
  17847. \begin{lstlisting}
  17848. (inject
  17849. (+ (project |$e'_1$| Integer)
  17850. (project |$e'_2$| Integer))
  17851. Integer)
  17852. \end{lstlisting}
  17853. \end{minipage}
  17854. \\[2ex]\hline
  17855. \begin{minipage}{0.27\textwidth}
  17856. \begin{lstlisting}
  17857. (lambda (|$x_1 \ldots$|) |$e$|)
  17858. \end{lstlisting}
  17859. \end{minipage}
  17860. &
  17861. $\Rightarrow$
  17862. &
  17863. \begin{minipage}{0.65\textwidth}
  17864. \begin{lstlisting}
  17865. (inject
  17866. (lambda: ([|$x_1$|:Any]|$\ldots$|):Any |$e'$|)
  17867. (Any|$\ldots$|Any -> Any))
  17868. \end{lstlisting}
  17869. \end{minipage}
  17870. \\[2ex]\hline
  17871. \begin{minipage}{0.27\textwidth}
  17872. \begin{lstlisting}
  17873. (|$e_0$| |$e_1 \ldots e_n$|)
  17874. \end{lstlisting}
  17875. \end{minipage}
  17876. &
  17877. $\Rightarrow$
  17878. &
  17879. \begin{minipage}{0.65\textwidth}
  17880. \begin{lstlisting}
  17881. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  17882. \end{lstlisting}
  17883. \end{minipage}
  17884. \\[2ex]\hline
  17885. \begin{minipage}{0.27\textwidth}
  17886. \begin{lstlisting}
  17887. (vector-ref |$e_1$| |$e_2$|)
  17888. \end{lstlisting}
  17889. \end{minipage}
  17890. &
  17891. $\Rightarrow$
  17892. &
  17893. \begin{minipage}{0.65\textwidth}
  17894. \begin{lstlisting}
  17895. (any-vector-ref |$e_1'$| (project |$e'_2$| Integer))
  17896. \end{lstlisting}
  17897. \end{minipage}
  17898. \\[2ex]\hline
  17899. \begin{minipage}{0.27\textwidth}
  17900. \begin{lstlisting}
  17901. (if |$e_1$| |$e_2$| |$e_3$|)
  17902. \end{lstlisting}
  17903. \end{minipage}
  17904. &
  17905. $\Rightarrow$
  17906. &
  17907. \begin{minipage}{0.65\textwidth}
  17908. \begin{lstlisting}
  17909. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  17910. \end{lstlisting}
  17911. \end{minipage}
  17912. \\[2ex]\hline
  17913. \begin{minipage}{0.27\textwidth}
  17914. \begin{lstlisting}
  17915. (eq? |$e_1$| |$e_2$|)
  17916. \end{lstlisting}
  17917. \end{minipage}
  17918. &
  17919. $\Rightarrow$
  17920. &
  17921. \begin{minipage}{0.65\textwidth}
  17922. \begin{lstlisting}
  17923. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  17924. \end{lstlisting}
  17925. \end{minipage}
  17926. \\[2ex]\hline
  17927. \begin{minipage}{0.27\textwidth}
  17928. \begin{lstlisting}
  17929. (not |$e_1$|)
  17930. \end{lstlisting}
  17931. \end{minipage}
  17932. &
  17933. $\Rightarrow$
  17934. &
  17935. \begin{minipage}{0.65\textwidth}
  17936. \begin{lstlisting}
  17937. (if (eq? |$e'_1$| (inject #f Boolean))
  17938. (inject #t Boolean) (inject #f Boolean))
  17939. \end{lstlisting}
  17940. \end{minipage}
  17941. \end{tabular}
  17942. \fi}
  17943. {\if\edition\pythonEd\pythonColor
  17944. \hspace{-0.8em}\begin{tabular}{|lll|} \hline
  17945. \begin{minipage}{0.23\textwidth}
  17946. \begin{lstlisting}
  17947. True
  17948. \end{lstlisting}
  17949. \end{minipage}
  17950. &
  17951. $\Rightarrow$
  17952. &
  17953. \begin{minipage}{0.7\textwidth}
  17954. \begin{lstlisting}
  17955. Inject(True, BoolType())
  17956. \end{lstlisting}
  17957. \end{minipage}
  17958. \\[2ex]\hline
  17959. \begin{minipage}{0.23\textwidth}
  17960. \begin{lstlisting}
  17961. |$e_1$| + |$e_2$|
  17962. \end{lstlisting}
  17963. \end{minipage}
  17964. &
  17965. $\Rightarrow$
  17966. &
  17967. \begin{minipage}{0.7\textwidth}
  17968. \begin{lstlisting}
  17969. Inject(Project(|$e'_1$|, IntType())
  17970. + Project(|$e'_2$|, IntType()),
  17971. IntType())
  17972. \end{lstlisting}
  17973. \end{minipage}
  17974. \\[2ex]\hline
  17975. \begin{minipage}{0.23\textwidth}
  17976. \begin{lstlisting}
  17977. lambda |$x_1 \ldots$|: |$e$|
  17978. \end{lstlisting}
  17979. \end{minipage}
  17980. &
  17981. $\Rightarrow$
  17982. &
  17983. \begin{minipage}{0.7\textwidth}
  17984. \begin{lstlisting}
  17985. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|], |$e'$|)
  17986. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  17987. \end{lstlisting}
  17988. \end{minipage}
  17989. \\[2ex]\hline
  17990. \begin{minipage}{0.23\textwidth}
  17991. \begin{lstlisting}
  17992. |$e_0$|(|$e_1 \ldots e_n$|)
  17993. \end{lstlisting}
  17994. \end{minipage}
  17995. &
  17996. $\Rightarrow$
  17997. &
  17998. \begin{minipage}{0.7\textwidth}
  17999. \begin{lstlisting}
  18000. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  18001. AnyType())), |$e'_1, \ldots, e'_n$|)
  18002. \end{lstlisting}
  18003. \end{minipage}
  18004. \\[2ex]\hline
  18005. \begin{minipage}{0.23\textwidth}
  18006. \begin{lstlisting}
  18007. |$e_1$|[|$e_2$|]
  18008. \end{lstlisting}
  18009. \end{minipage}
  18010. &
  18011. $\Rightarrow$
  18012. &
  18013. \begin{minipage}{0.7\textwidth}
  18014. \begin{lstlisting}
  18015. Call(Name('any_tuple_load'),
  18016. [|$e_1'$|, Project(|$e_2'$|, IntType())])
  18017. \end{lstlisting}
  18018. \end{minipage}
  18019. %% \begin{minipage}{0.23\textwidth}
  18020. %% \begin{lstlisting}
  18021. %% |$e_2$| if |$e_1$| else |$e_3$|
  18022. %% \end{lstlisting}
  18023. %% \end{minipage}
  18024. %% &
  18025. %% $\Rightarrow$
  18026. %% &
  18027. %% \begin{minipage}{0.7\textwidth}
  18028. %% \begin{lstlisting}
  18029. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  18030. %% \end{lstlisting}
  18031. %% \end{minipage}
  18032. %% \\[2ex]\hline
  18033. %% \begin{minipage}{0.23\textwidth}
  18034. %% \begin{lstlisting}
  18035. %% (eq? |$e_1$| |$e_2$|)
  18036. %% \end{lstlisting}
  18037. %% \end{minipage}
  18038. %% &
  18039. %% $\Rightarrow$
  18040. %% &
  18041. %% \begin{minipage}{0.7\textwidth}
  18042. %% \begin{lstlisting}
  18043. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  18044. %% \end{lstlisting}
  18045. %% \end{minipage}
  18046. %% \\[2ex]\hline
  18047. %% \begin{minipage}{0.23\textwidth}
  18048. %% \begin{lstlisting}
  18049. %% (not |$e_1$|)
  18050. %% \end{lstlisting}
  18051. %% \end{minipage}
  18052. %% &
  18053. %% $\Rightarrow$
  18054. %% &
  18055. %% \begin{minipage}{0.7\textwidth}
  18056. %% \begin{lstlisting}
  18057. %% (if (eq? |$e'_1$| (inject #f Boolean))
  18058. %% (inject #t Boolean) (inject #f Boolean))
  18059. %% \end{lstlisting}
  18060. %% \end{minipage}
  18061. %% \\[2ex]\hline
  18062. \\\hline
  18063. \end{tabular}
  18064. \fi}
  18065. \end{tcolorbox}
  18066. \caption{Cast insertion.}
  18067. \label{fig:compile-r7-Lany}
  18068. \end{figure}
  18069. \section{Reveal Casts}
  18070. \label{sec:reveal-casts-Lany}
  18071. % TODO: define R'_6
  18072. In the \code{reveal\_casts} pass, we recommend compiling
  18073. \code{Project} into a conditional expression that checks whether the
  18074. value's tag matches the target type; if it does, the value is
  18075. converted to a value of the target type by removing the tag; if it
  18076. does not, the program exits.
  18077. %
  18078. {\if\edition\racketEd
  18079. %
  18080. To perform these actions we need a new primitive operation,
  18081. \code{tag-of-any}, and a new form, \code{ValueOf}.
  18082. The \code{tag-of-any} operation retrieves the type tag from a tagged
  18083. value of type \code{Any}. The \code{ValueOf} form retrieves the
  18084. underlying value from a tagged value. The \code{ValueOf} form
  18085. includes the type for the underlying value that is used by the type
  18086. checker.
  18087. %
  18088. \fi}
  18089. %
  18090. {\if\edition\pythonEd\pythonColor
  18091. %
  18092. To perform these actions we need two new AST classes: \code{TagOf} and
  18093. \code{ValueOf}. The \code{TagOf} operation retrieves the type tag from a
  18094. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  18095. the underlying value from a tagged value. The \code{ValueOf}
  18096. operation includes the type for the underlying value that is used by
  18097. the type checker.
  18098. %
  18099. \fi}
  18100. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  18101. \code{Project} can be translated as follows:
  18102. \begin{center}
  18103. \begin{minipage}{1.0\textwidth}
  18104. {\if\edition\racketEd
  18105. \begin{lstlisting}
  18106. (Project |$e$| |$\FType$|)
  18107. |$\Rightarrow$|
  18108. (Let |$\itm{tmp}$| |$e'$|
  18109. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  18110. (Int |$\itm{tagof}(\FType)$|)))
  18111. (ValueOf |$\itm{tmp}$| |$\FType$|)
  18112. (Exit)))
  18113. \end{lstlisting}
  18114. \fi}
  18115. {\if\edition\pythonEd\pythonColor
  18116. \begin{lstlisting}
  18117. Project(|$e$|, |$\FType$|)
  18118. |$\Rightarrow$|
  18119. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  18120. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  18121. [Constant(|$\itm{tagof}(\FType)$|)]),
  18122. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  18123. Call(Name('exit'), [])))
  18124. \end{lstlisting}
  18125. \fi}
  18126. \end{minipage}
  18127. \end{center}
  18128. If the target type of the projection is a tuple or function type, then
  18129. there is a bit more work to do. For tuples, check that the length of
  18130. the tuple type matches the length of the tuple. For functions, check
  18131. that the number of parameters in the function type matches the
  18132. function's arity.
  18133. Regarding \code{Inject}, we recommend compiling it to a slightly
  18134. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  18135. takes a tag instead of a type.
  18136. \begin{center}
  18137. \begin{minipage}{1.0\textwidth}
  18138. {\if\edition\racketEd
  18139. \begin{lstlisting}
  18140. (Inject |$e$| |$\FType$|)
  18141. |$\Rightarrow$|
  18142. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  18143. \end{lstlisting}
  18144. \fi}
  18145. {\if\edition\pythonEd\pythonColor
  18146. \begin{lstlisting}
  18147. Inject(|$e$|, |$\FType$|)
  18148. |$\Rightarrow$|
  18149. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  18150. \end{lstlisting}
  18151. \fi}
  18152. \end{minipage}
  18153. \end{center}
  18154. {\if\edition\pythonEd\pythonColor
  18155. %
  18156. The introduction of \code{make\_any} makes it difficult to use
  18157. bidirectional type checking because we no longer have an expected type
  18158. to use for type checking the expression $e'$. Thus, we run into
  18159. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  18160. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  18161. annotated lambda) that contains its return type and the types of its
  18162. parameters.
  18163. %
  18164. \fi}
  18165. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  18166. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  18167. translation of \code{Project}.}
  18168. {\if\edition\racketEd
  18169. The \code{any-vector-ref} and \code{any-vector-set!} operations
  18170. combine the projection action with the vector operation. Also, the
  18171. read and write operations allow arbitrary expressions for the index, so
  18172. the type checker for \LangAny{} (figure~\ref{fig:type-check-Lany})
  18173. cannot guarantee that the index is within bounds. Thus, we insert code
  18174. to perform bounds checking at runtime. The translation for
  18175. \code{any-vector-ref} is as follows, and the other two operations are
  18176. translated in a similar way:
  18177. \begin{center}
  18178. \begin{minipage}{0.95\textwidth}
  18179. \begin{lstlisting}
  18180. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  18181. |$\Rightarrow$|
  18182. (Let |$v$| |$e'_1$|
  18183. (Let |$i$| |$e'_2$|
  18184. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  18185. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  18186. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  18187. (Exit))
  18188. (Exit))))
  18189. \end{lstlisting}
  18190. \end{minipage}
  18191. \end{center}
  18192. \fi}
  18193. %
  18194. {\if\edition\pythonEd\pythonColor
  18195. %
  18196. The \code{any\_tuple\_load} operation combines the projection action
  18197. with the load operation. Also, the load operation allows arbitrary
  18198. expressions for the index, so the type checker for \LangAny{}
  18199. (figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  18200. within bounds. Thus, we insert code to perform bounds checking at
  18201. runtime. The translation for \code{any\_tuple\_load} is as follows.
  18202. \begin{lstlisting}
  18203. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  18204. |$\Rightarrow$|
  18205. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  18206. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  18207. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  18208. Call(Name('any_tuple_load_unsafe'), [|$t$|, |$i$|]),
  18209. Call(Name('exit'), [])),
  18210. Call(Name('exit'), [])))
  18211. \end{lstlisting}
  18212. \fi}
  18213. {\if\edition\pythonEd\pythonColor
  18214. \section{Assignment Conversion}
  18215. \label{sec:convert-assignments-Lany}
  18216. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18217. \code{AnnLambda} AST classes.
  18218. \section{Closure Conversion}
  18219. \label{sec:closure-conversion-Lany}
  18220. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  18221. \code{AnnLambda} AST classes.
  18222. \fi}
  18223. \section{Remove Complex Operands}
  18224. \label{sec:rco-Lany}
  18225. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  18226. expressions. The subexpression of \code{ValueOf} must be atomic.}
  18227. %
  18228. \python{The \code{ValueOf} and \code{TagOf} operations are both
  18229. complex expressions. Their subexpressions must be atomic.}
  18230. \section{Explicate Control and \LangCAny{}}
  18231. \label{sec:explicate-Lany}
  18232. The output of \code{explicate\_control} is the \LangCAny{} language,
  18233. whose syntax definition is shown in figure~\ref{fig:c5-syntax}.
  18234. %
  18235. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  18236. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  18237. note that the index argument of \code{vector-ref} and
  18238. \code{vector-set!} is an $\Atm$, instead of an integer as it was in
  18239. \LangCVec{} (figure~\ref{fig:c2-syntax}).}
  18240. %
  18241. \python{Update the auxiliary functions \code{explicate\_tail},
  18242. \code{explicate\_effect}, and \code{explicate\_pred} as
  18243. appropriate to handle the new expressions in \LangCAny{}. }
  18244. \newcommand{\CanyASTPython}{
  18245. \begin{array}{lcl}
  18246. \Exp &::=& \CALL{\VAR{\skey{make\_any}}}{\LS \Atm,\Atm \RS}\\
  18247. &\MID& \key{TagOf}\LP \Atm \RP
  18248. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  18249. &\MID& \CALL{\VAR{\skey{any\_tuple\_load\_unsafe}}}{\LS \Atm,\Atm \RS}\\
  18250. &\MID& \CALL{\VAR{\skey{any\_len}}}{\LS \Atm \RS} \\
  18251. &\MID& \CALL{\VAR{\skey{exit}}}{\LS\RS}
  18252. \end{array}
  18253. }
  18254. \newcommand{\CanyASTRacket}{
  18255. \begin{array}{lcl}
  18256. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  18257. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  18258. &\MID& \VALUEOF{\Atm}{\FType} \\
  18259. \Tail &::= & \LP\key{Exit}\RP
  18260. \end{array}
  18261. }
  18262. \begin{figure}[tp]
  18263. \begin{tcolorbox}[colback=white]
  18264. \small
  18265. {\if\edition\racketEd
  18266. \[
  18267. \begin{array}{l}
  18268. \gray{\CvarASTRacket} \\ \hline
  18269. \gray{\CifASTRacket} \\ \hline
  18270. \gray{\CloopASTRacket} \\ \hline
  18271. \gray{\CtupASTRacket} \\ \hline
  18272. \gray{\CfunASTRacket} \\ \hline
  18273. \gray{\ClambdaASTRacket} \\ \hline
  18274. \CanyASTRacket \\
  18275. \begin{array}{lcl}
  18276. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  18277. \end{array}
  18278. \end{array}
  18279. \]
  18280. \fi}
  18281. {\if\edition\pythonEd\pythonColor
  18282. \[
  18283. \begin{array}{l}
  18284. \gray{\CifASTPython} \\ \hline
  18285. \gray{\CtupASTPython} \\ \hline
  18286. \gray{\CfunASTPython} \\ \hline
  18287. \gray{\ClambdaASTPython} \\ \hline
  18288. \CanyASTPython \\
  18289. \begin{array}{lcl}
  18290. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  18291. \end{array}
  18292. \end{array}
  18293. \]
  18294. \fi}
  18295. \end{tcolorbox}
  18296. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (figure~\ref{fig:Clam-syntax}).}
  18297. \label{fig:c5-syntax}
  18298. \end{figure}
  18299. \section{Select Instructions}
  18300. \label{sec:select-Lany}
  18301. \index{subject}{select instructions}
  18302. In the \code{select\_instructions} pass, we translate the primitive
  18303. operations on the \ANYTY{} type to x86 instructions that manipulate
  18304. the three tag bits of the tagged value. In the following descriptions,
  18305. given an atom $e$ we use a primed variable $e'$ to refer to the result
  18306. of translating $e$ into an x86 argument:
  18307. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  18308. We recommend compiling the
  18309. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  18310. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  18311. shifts the destination to the left by the number of bits specified by its
  18312. source argument (in this case three, the length of the tag), and it
  18313. preserves the sign of the integer. We use the \key{orq} instruction to
  18314. combine the tag and the value to form the tagged value.
  18315. {\if\edition\racketEd
  18316. \begin{lstlisting}
  18317. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18318. |$\Rightarrow$|
  18319. movq |$e'$|, |\itm{lhs'}|
  18320. salq $3, |\itm{lhs'}|
  18321. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18322. \end{lstlisting}
  18323. \fi}
  18324. %
  18325. {\if\edition\pythonEd\pythonColor
  18326. \begin{lstlisting}
  18327. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18328. |$\Rightarrow$|
  18329. movq |$e'$|, |\itm{lhs'}|
  18330. salq $3, |\itm{lhs'}|
  18331. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18332. \end{lstlisting}
  18333. \fi}
  18334. %
  18335. The instruction selection\index{subject}{instruction selection} for
  18336. tuples and procedures is different because there is no need to shift
  18337. them to the left. The rightmost 3 bits are already zeros, so we simply
  18338. combine the value and the tag using \key{orq}. \\
  18339. %
  18340. {\if\edition\racketEd
  18341. \begin{center}
  18342. \begin{minipage}{\textwidth}
  18343. \begin{lstlisting}
  18344. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  18345. |$\Rightarrow$|
  18346. movq |$e'$|, |\itm{lhs'}|
  18347. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18348. \end{lstlisting}
  18349. \end{minipage}
  18350. \end{center}
  18351. \fi}
  18352. %
  18353. {\if\edition\pythonEd\pythonColor
  18354. \begin{lstlisting}
  18355. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  18356. |$\Rightarrow$|
  18357. movq |$e'$|, |\itm{lhs'}|
  18358. orq $|$\itm{tag}$|, |\itm{lhs'}|
  18359. \end{lstlisting}
  18360. \fi}
  18361. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  18362. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  18363. operation extracts the type tag from a value of type \ANYTY{}. The
  18364. type tag is the bottom $3$ bits, so we obtain the tag by taking the
  18365. bitwise-and of the value with $111$ ($7$ decimal).
  18366. %
  18367. {\if\edition\racketEd
  18368. \begin{lstlisting}
  18369. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  18370. |$\Rightarrow$|
  18371. movq |$e'$|, |\itm{lhs'}|
  18372. andq $7, |\itm{lhs'}|
  18373. \end{lstlisting}
  18374. \fi}
  18375. %
  18376. {\if\edition\pythonEd\pythonColor
  18377. \begin{lstlisting}
  18378. Assign([|\itm{lhs}|], TagOf(|$e$|))
  18379. |$\Rightarrow$|
  18380. movq |$e'$|, |\itm{lhs'}|
  18381. andq $7, |\itm{lhs'}|
  18382. \end{lstlisting}
  18383. \fi}
  18384. \paragraph{\code{ValueOf}}
  18385. The instructions for \key{ValueOf} also differ, depending on whether
  18386. the type $T$ is a pointer (tuple or function) or not (integer or
  18387. Boolean). The following shows the instruction
  18388. selection for integers and
  18389. Booleans, in which we produce an untagged value by shifting it to the
  18390. right by 3 bits:
  18391. %
  18392. {\if\edition\racketEd
  18393. \begin{lstlisting}
  18394. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18395. |$\Rightarrow$|
  18396. movq |$e'$|, |\itm{lhs'}|
  18397. sarq $3, |\itm{lhs'}|
  18398. \end{lstlisting}
  18399. \fi}
  18400. %
  18401. {\if\edition\pythonEd\pythonColor
  18402. \begin{lstlisting}
  18403. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18404. |$\Rightarrow$|
  18405. movq |$e'$|, |\itm{lhs'}|
  18406. sarq $3, |\itm{lhs'}|
  18407. \end{lstlisting}
  18408. \fi}
  18409. %
  18410. In the case for tuples and procedures, we zero out the rightmost 3
  18411. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  18412. ($7$ decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  18413. decimal), which we \code{movq} into the destination $\itm{lhs'}$.
  18414. Finally, we apply \code{andq} with the tagged value to get the desired
  18415. result.
  18416. %
  18417. {\if\edition\racketEd
  18418. \begin{lstlisting}
  18419. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  18420. |$\Rightarrow$|
  18421. movq $|$-8$|, |\itm{lhs'}|
  18422. andq |$e'$|, |\itm{lhs'}|
  18423. \end{lstlisting}
  18424. \fi}
  18425. %
  18426. {\if\edition\pythonEd\pythonColor
  18427. \begin{lstlisting}
  18428. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  18429. |$\Rightarrow$|
  18430. movq $|$-8$|, |\itm{lhs'}|
  18431. andq |$e'$|, |\itm{lhs'}|
  18432. \end{lstlisting}
  18433. \fi}
  18434. %% \paragraph{Type Predicates} We leave it to the reader to
  18435. %% devise a sequence of instructions to implement the type predicates
  18436. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  18437. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  18438. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  18439. operation combines the effect of \code{ValueOf} with accessing the
  18440. length of a tuple from the tag stored at the zero index of the tuple.
  18441. {\if\edition\racketEd
  18442. \begin{lstlisting}
  18443. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  18444. |$\Longrightarrow$|
  18445. movq $|$-8$|, %r11
  18446. andq |$e_1'$|, %r11
  18447. movq 0(%r11), %r11
  18448. andq $126, %r11
  18449. sarq $1, %r11
  18450. movq %r11, |$\itm{lhs'}$|
  18451. \end{lstlisting}
  18452. \fi}
  18453. {\if\edition\pythonEd\pythonColor
  18454. \begin{lstlisting}
  18455. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  18456. |$\Longrightarrow$|
  18457. movq $|$-8$|, %r11
  18458. andq |$e_1'$|, %r11
  18459. movq 0(%r11), %r11
  18460. andq $126, %r11
  18461. sarq $1, %r11
  18462. movq %r11, |$\itm{lhs'}$|
  18463. \end{lstlisting}
  18464. \fi}
  18465. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load\_unsafe}}}}
  18466. This operation combines the effect of \code{ValueOf} with reading an
  18467. element of the tuple (see
  18468. section~\ref{sec:select-instructions-gc}). However, the index may be
  18469. an arbitrary atom, so instead of computing the offset at compile time,
  18470. we must generate instructions to compute the offset at runtime as
  18471. follows. Note the use of the new instruction \code{imulq}.
  18472. \begin{center}
  18473. \begin{minipage}{0.96\textwidth}
  18474. {\if\edition\racketEd
  18475. \begin{lstlisting}
  18476. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  18477. |$\Longrightarrow$|
  18478. movq |$\neg 111$|, %r11
  18479. andq |$e_1'$|, %r11
  18480. movq |$e_2'$|, %rax
  18481. addq $1, %rax
  18482. imulq $8, %rax
  18483. addq %rax, %r11
  18484. movq 0(%r11) |$\itm{lhs'}$|
  18485. \end{lstlisting}
  18486. \fi}
  18487. %
  18488. {\if\edition\pythonEd\pythonColor
  18489. \begin{lstlisting}
  18490. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load_unsafe'), [|$e_1$|,|$e_2$|]))
  18491. |$\Longrightarrow$|
  18492. movq $|$-8$|, %r11
  18493. andq |$e_1'$|, %r11
  18494. movq |$e_2'$|, %rax
  18495. addq $1, %rax
  18496. imulq $8, %rax
  18497. addq %rax, %r11
  18498. movq 0(%r11) |$\itm{lhs'}$|
  18499. \end{lstlisting}
  18500. \fi}
  18501. \end{minipage}
  18502. \end{center}
  18503. % $ pacify font lock
  18504. %% \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  18505. %% The code generation for
  18506. %% \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  18507. %% analogous to the above translation for reading from a tuple.
  18508. \section{Register Allocation for \LangAny{} }
  18509. \label{sec:register-allocation-Lany}
  18510. \index{subject}{register allocation}
  18511. There is an interesting interaction between tagged values and garbage
  18512. collection that has an impact on register allocation. A variable of
  18513. type \ANYTY{} might refer to a tuple, and therefore it might be a root
  18514. that needs to be inspected and copied during garbage collection. Thus,
  18515. we need to treat variables of type \ANYTY{} in a similar way to
  18516. variables of tuple type for purposes of register allocation,
  18517. with particular attention to the following:
  18518. \begin{itemize}
  18519. \item If a variable of type \ANYTY{} is live during a function call,
  18520. then it must be spilled. This can be accomplished by changing
  18521. \code{build\_interference} to mark all variables of type \ANYTY{}
  18522. that are live after a \code{callq} to be interfering with all the
  18523. registers.
  18524. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  18525. the root stack instead of the normal procedure call stack.
  18526. \end{itemize}
  18527. Another concern regarding the root stack is that the garbage collector
  18528. needs to differentiate among (1) plain old pointers to tuples, (2) a
  18529. tagged value that points to a tuple, and (3) a tagged value that is
  18530. not a tuple. We enable this differentiation by choosing not to use the
  18531. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  18532. reserved for identifying plain old pointers to tuples. That way, if
  18533. one of the first three bits is set, then we have a tagged value and
  18534. inspecting the tag can differentiate between tuples ($010$) and the
  18535. other kinds of values.
  18536. %% \begin{exercise}\normalfont
  18537. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  18538. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  18539. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  18540. %% compiler on these new programs and all of your previously created test
  18541. %% programs.
  18542. %% \end{exercise}
  18543. \begin{exercise}\normalfont\normalsize
  18544. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  18545. Create tests for \LangDyn{} by adapting ten of your previous test programs
  18546. by removing type annotations. Add five more test programs that
  18547. specifically rely on the language being dynamically typed. That is,
  18548. they should not be legal programs in a statically typed language, but
  18549. nevertheless they should be valid \LangDyn{} programs that run to
  18550. completion without error.
  18551. \end{exercise}
  18552. Figure~\ref{fig:Ldyn-passes} gives an overview of the passes needed
  18553. for the compilation of \LangDyn{}.
  18554. \begin{figure}[bthp]
  18555. \begin{tcolorbox}[colback=white]
  18556. {\if\edition\racketEd
  18557. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18558. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18559. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18560. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18561. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18562. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18563. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18564. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18565. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18566. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18567. \node (F1-4) at (4,0) {\large \LangAnyAlloc{}};
  18568. \node (F1-5) at (8,0) {\large \LangAnyAlloc{}};
  18569. \node (F1-6) at (12,0) {\large \LangAnyAlloc{}};
  18570. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18571. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18572. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  18573. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  18574. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18575. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18576. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  18577. \path[->,bend left=15] (Lfun) edge [above] node
  18578. {\ttfamily\footnotesize shrink} (Lfun-2);
  18579. \path[->,bend left=15] (Lfun-2) edge [above] node
  18580. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18581. \path[->,bend left=15] (Lfun-3) edge [above] node
  18582. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18583. \path[->,bend left=15] (Lfun-4) edge [left] node
  18584. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18585. \path[->,bend left=15] (Lfun-5) edge [below] node
  18586. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18587. \path[->,bend left=15] (Lfun-6) edge [below] node
  18588. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18589. \path[->,bend right=15] (Lfun-7) edge [above] node
  18590. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18591. \path[->,bend right=15] (F1-2) edge [right] node
  18592. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18593. \path[->,bend right=15] (F1-3) edge [below] node
  18594. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  18595. \path[->,bend right=15] (F1-4) edge [below] node
  18596. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18597. \path[->,bend left=15] (F1-5) edge [above] node
  18598. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18599. \path[->,bend left=10] (F1-6) edge [below] node
  18600. {\ttfamily\footnotesize \ \ \ \ \ explicate\_control} (C3-2);
  18601. \path[->,bend left=15] (C3-2) edge [right] node
  18602. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18603. \path[->,bend right=15] (x86-2) edge [right] node
  18604. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18605. \path[->,bend right=15] (x86-2-1) edge [below] node
  18606. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  18607. \path[->,bend right=15] (x86-2-2) edge [right] node
  18608. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  18609. \path[->,bend left=15] (x86-3) edge [above] node
  18610. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18611. \path[->,bend left=15] (x86-4) edge [right] node
  18612. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18613. \end{tikzpicture}
  18614. \fi}
  18615. {\if\edition\pythonEd\pythonColor
  18616. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  18617. \node (Lfun) at (0,4) {\large \LangDyn{}};
  18618. \node (Lfun-2) at (4,4) {\large \LangDyn{}};
  18619. \node (Lfun-3) at (8,4) {\large \LangDyn{}};
  18620. \node (Lfun-4) at (12,4) {\large \LangDynFunRef{}};
  18621. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  18622. \node (Lfun-6) at (8,2) {\large \LangAnyFunRef{}};
  18623. \node (Lfun-7) at (4,2) {\large \LangAnyFunRef{}};
  18624. \node (F1-2) at (0,2) {\large \LangAnyFunRef{}};
  18625. \node (F1-3) at (0,0) {\large \LangAnyFunRef{}};
  18626. \node (F1-5) at (4,0) {\large \LangAnyAlloc{}};
  18627. \node (F1-6) at (8,0) {\large \LangAnyAlloc{}};
  18628. \node (C3-2) at (0,-2) {\large \LangCAny{}};
  18629. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  18630. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  18631. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  18632. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  18633. \path[->,bend left=15] (Lfun) edge [above] node
  18634. {\ttfamily\footnotesize shrink} (Lfun-2);
  18635. \path[->,bend left=15] (Lfun-2) edge [above] node
  18636. {\ttfamily\footnotesize uniquify} (Lfun-3);
  18637. \path[->,bend left=15] (Lfun-3) edge [above] node
  18638. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  18639. \path[->,bend left=15] (Lfun-4) edge [left] node
  18640. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  18641. \path[->,bend left=15] (Lfun-5) edge [below] node
  18642. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  18643. \path[->,bend right=15] (Lfun-6) edge [above] node
  18644. {\ttfamily\footnotesize convert\_assignments} (Lfun-7);
  18645. \path[->,bend right=15] (Lfun-7) edge [above] node
  18646. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  18647. \path[->,bend right=15] (F1-2) edge [right] node
  18648. {\ttfamily\footnotesize limit\_functions} (F1-3);
  18649. \path[->,bend right=15] (F1-3) edge [below] node
  18650. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  18651. \path[->,bend left=15] (F1-5) edge [above] node
  18652. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  18653. \path[->,bend left=10] (F1-6) edge [below] node
  18654. {\ttfamily\footnotesize \ \ \ \ \ \ \ \ explicate\_control} (C3-2);
  18655. \path[->,bend right=15] (C3-2) edge [right] node
  18656. {\ttfamily\footnotesize select\_instructions} (x86-2);
  18657. \path[->,bend right=15] (x86-2) edge [below] node
  18658. {\ttfamily\footnotesize assign\_homes} (x86-3);
  18659. \path[->,bend right=15] (x86-3) edge [below] node
  18660. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  18661. \path[->,bend left=15] (x86-4) edge [above] node
  18662. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  18663. \end{tikzpicture}
  18664. \fi}
  18665. \end{tcolorbox}
  18666. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  18667. \label{fig:Ldyn-passes}
  18668. \end{figure}
  18669. % Further Reading
  18670. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18671. %% {\if\edition\pythonEd\pythonColor
  18672. %% \chapter{Objects}
  18673. %% \label{ch:Lobject}
  18674. %% \index{subject}{objects}
  18675. %% \index{subject}{classes}
  18676. %% \setcounter{footnote}{0}
  18677. %% \fi}
  18678. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18679. \chapter{Gradual Typing}
  18680. \label{ch:Lgrad}
  18681. \index{subject}{gradual typing}
  18682. \setcounter{footnote}{0}
  18683. This chapter studies the language \LangGrad{}, in which the programmer
  18684. can choose between static and dynamic type checking in different parts
  18685. of a program, thereby mixing the statically typed \LangLam{} language
  18686. with the dynamically typed \LangDyn{}. There are several approaches to
  18687. mixing static and dynamic typing, including multilanguage
  18688. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  18689. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  18690. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  18691. programmer controls the amount of static versus dynamic checking by
  18692. adding or removing type annotations on parameters and
  18693. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  18694. The definition of the concrete syntax of \LangGrad{} is shown in
  18695. figure~\ref{fig:Lgrad-concrete-syntax}, and the definition of its
  18696. abstract syntax is shown in figure~\ref{fig:Lgrad-syntax}. The main
  18697. syntactic difference between \LangLam{} and \LangGrad{} is that type
  18698. annotations are optional, which is specified in the grammar using the
  18699. \Param{} and \itm{ret} nonterminals. In the abstract syntax, type
  18700. annotations are not optional, but we use the \CANYTY{} type when a type
  18701. annotation is absent.
  18702. %
  18703. Both the type checker and the interpreter for \LangGrad{} require some
  18704. interesting changes to enable gradual typing, which we discuss in the
  18705. next two sections.
  18706. \newcommand{\LgradGrammarRacket}{
  18707. \begin{array}{lcl}
  18708. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18709. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18710. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  18711. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  18712. \MID \CGLAMBDA{\LP\Param\ldots\RP}{\itm{ret}}{\Exp} \\
  18713. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  18714. \Def &::=& \CGDEF{\Var}{\Param\ldots}{\itm{ret}}{\Exp}
  18715. \end{array}
  18716. }
  18717. \newcommand{\LgradASTRacket}{
  18718. \begin{array}{lcl}
  18719. \Type &::=& \LP\Type \ldots \; \key{->}\; \Type\RP \\
  18720. \Param &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  18721. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  18722. \MID \LAMBDA{\LP\Param\ldots\RP}{\Type}{\Exp} \\
  18723. \itm{op} &::=& \code{procedure-arity} \\
  18724. \Def &::=& \FUNDEF{\Var}{\LP\Param\ldots\RP}{\Type}{\code{'()}}{\Exp}
  18725. \end{array}
  18726. }
  18727. \newcommand{\LgradGrammarPython}{
  18728. \begin{array}{lcl}
  18729. \Type &::=& \key{Any}
  18730. \MID \key{int}
  18731. \MID \key{bool}
  18732. \MID \key{tuple}\LS \Type \code{, } \ldots \RS
  18733. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  18734. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  18735. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}
  18736. \MID \CARITY{\Exp} \\
  18737. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp} \MID \CRETURN{\Exp} \\
  18738. \Param &::=& \Var \MID \Var \key{:} \Type \\
  18739. \itm{ret} &::=& \epsilon \MID \key{->}~\Type \\
  18740. \Def &::=& \CGDEF{\Var}{\Param\key{, }\ldots}{\itm{ret}}{\Stmt^{+}}
  18741. \end{array}
  18742. }
  18743. \newcommand{\LgradASTPython}{
  18744. \begin{array}{lcl}
  18745. \Type &::=& \key{AnyType()} \MID \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}\\
  18746. &\MID& \key{TupleType}\LP\Type^{*}\RP
  18747. \MID \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  18748. \Exp &::=& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp}\\
  18749. &\MID& \ARITY{\Exp} \\
  18750. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  18751. \MID \RETURN{\Exp} \\
  18752. \Param &::=& \LP\Var\key{,}\Type\RP \\
  18753. \Def &::=& \FUNDEF{\Var}{\Param^{*}}{\Type}{}{\Stmt^{+}}
  18754. \end{array}
  18755. }
  18756. \begin{figure}[tbp]
  18757. \centering
  18758. \begin{tcolorbox}[colback=white]
  18759. \vspace{-5pt}
  18760. \small
  18761. {\if\edition\racketEd
  18762. \[
  18763. \begin{array}{l}
  18764. \gray{\LintGrammarRacket{}} \\ \hline
  18765. \gray{\LvarGrammarRacket{}} \\ \hline
  18766. \gray{\LifGrammarRacket{}} \\ \hline
  18767. \gray{\LwhileGrammarRacket} \\ \hline
  18768. \gray{\LtupGrammarRacket} \\ \hline
  18769. \LgradGrammarRacket \\
  18770. \begin{array}{lcl}
  18771. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  18772. \end{array}
  18773. \end{array}
  18774. \]
  18775. \fi}
  18776. {\if\edition\pythonEd\pythonColor
  18777. \[
  18778. \begin{array}{l}
  18779. \gray{\LintGrammarPython{}} \\ \hline
  18780. \gray{\LvarGrammarPython{}} \\ \hline
  18781. \gray{\LifGrammarPython{}} \\ \hline
  18782. \gray{\LwhileGrammarPython} \\ \hline
  18783. \gray{\LtupGrammarPython} \\ \hline
  18784. \LgradGrammarPython \\
  18785. \begin{array}{lcl}
  18786. \LangGradM{} &::=& \Def\ldots \Stmt\ldots
  18787. \end{array}
  18788. \end{array}
  18789. \]
  18790. \fi}
  18791. \end{tcolorbox}
  18792. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-concrete-syntax}).}
  18793. \label{fig:Lgrad-concrete-syntax}
  18794. \end{figure}
  18795. \begin{figure}[tbp]
  18796. \centering
  18797. \begin{tcolorbox}[colback=white]
  18798. \small
  18799. {\if\edition\racketEd
  18800. \[
  18801. \begin{array}{l}
  18802. \gray{\LintOpAST} \\ \hline
  18803. \gray{\LvarASTRacket{}} \\ \hline
  18804. \gray{\LifASTRacket{}} \\ \hline
  18805. \gray{\LwhileASTRacket{}} \\ \hline
  18806. \gray{\LtupASTRacket{}} \\ \hline
  18807. \LgradASTRacket \\
  18808. \begin{array}{lcl}
  18809. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18810. \end{array}
  18811. \end{array}
  18812. \]
  18813. \fi}
  18814. {\if\edition\pythonEd\pythonColor
  18815. \[
  18816. \begin{array}{l}
  18817. \gray{\LintASTPython{}} \\ \hline
  18818. \gray{\LvarASTPython{}} \\ \hline
  18819. \gray{\LifASTPython{}} \\ \hline
  18820. \gray{\LwhileASTPython} \\ \hline
  18821. \gray{\LtupASTPython} \\ \hline
  18822. \LgradASTPython \\
  18823. \begin{array}{lcl}
  18824. \LangGradM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  18825. \end{array}
  18826. \end{array}
  18827. \]
  18828. \fi}
  18829. \end{tcolorbox}
  18830. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (figure~\ref{fig:Lvec-syntax}).}
  18831. \label{fig:Lgrad-syntax}
  18832. \end{figure}
  18833. % TODO: more road map -Jeremy
  18834. %\clearpage
  18835. \section{Type Checking \LangGrad{}}
  18836. \label{sec:gradual-type-check}
  18837. We begin by discussing the type checking of a partially typed variant
  18838. of the \code{map} example from chapter~\ref{ch:Lfun}, shown in
  18839. figure~\ref{fig:gradual-map}. The \code{map} function itself is
  18840. statically typed, so there is nothing special happening there with
  18841. respect to type checking. On the other hand, the \code{inc} function
  18842. does not have type annotations, so the type checker assigns the type
  18843. \CANYTY{} to parameter \code{x} and the return type. Now consider the
  18844. \code{+} operator inside \code{inc}. It expects both arguments to have
  18845. type \INTTY{}, but its first argument \code{x} has type \CANYTY{}. In
  18846. a gradually typed language, such differences are allowed so long as
  18847. the types are \emph{consistent}; that is, they are equal except in
  18848. places where there is an \CANYTY{} type. That is, the type \CANYTY{}
  18849. is consistent with every other type. Figure~\ref{fig:consistent}
  18850. shows the definition of the
  18851. \racket{\code{consistent?}}\python{\code{consistent}} method.
  18852. %
  18853. So the type checker allows the \code{+} operator to be applied
  18854. to \code{x} because \CANYTY{} is consistent with \INTTY{}.
  18855. %
  18856. Next consider the call to the \code{map} function shown in
  18857. figure~\ref{fig:gradual-map} with the arguments \code{inc} and a
  18858. tuple. The \code{inc} function has type
  18859. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}},
  18860. but parameter \code{f} of \code{map} has type
  18861. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18862. The type checker for \LangGrad{} accepts this call because the two types are
  18863. consistent.
  18864. \begin{figure}[hbtp]
  18865. % gradual_test_9.rkt
  18866. \begin{tcolorbox}[colback=white]
  18867. {\if\edition\racketEd
  18868. \begin{lstlisting}
  18869. (define (map [f : (Integer -> Integer)]
  18870. [v : (Vector Integer Integer)])
  18871. : (Vector Integer Integer)
  18872. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18873. (define (inc x) (+ x 1))
  18874. (vector-ref (map inc (vector 0 41)) 1)
  18875. \end{lstlisting}
  18876. \fi}
  18877. {\if\edition\pythonEd\pythonColor
  18878. \begin{lstlisting}
  18879. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18880. return f(v[0]), f(v[1])
  18881. def inc(x):
  18882. return x + 1
  18883. t = map(inc, (0, 41))
  18884. print(t[1])
  18885. \end{lstlisting}
  18886. \fi}
  18887. \end{tcolorbox}
  18888. \caption{A partially typed version of the \code{map} example.}
  18889. \label{fig:gradual-map}
  18890. \end{figure}
  18891. \begin{figure}[tbp]
  18892. \begin{tcolorbox}[colback=white]
  18893. {\if\edition\racketEd
  18894. \begin{lstlisting}
  18895. (define/public (consistent? t1 t2)
  18896. (match* (t1 t2)
  18897. [('Integer 'Integer) #t]
  18898. [('Boolean 'Boolean) #t]
  18899. [('Void 'Void) #t]
  18900. [('Any t2) #t]
  18901. [(t1 'Any) #t]
  18902. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  18903. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  18904. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  18905. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  18906. (consistent? rt1 rt2))]
  18907. [(other wise) #f]))
  18908. \end{lstlisting}
  18909. \fi}
  18910. {\if\edition\pythonEd\pythonColor
  18911. \begin{lstlisting}
  18912. def consistent(self, t1, t2):
  18913. match (t1, t2):
  18914. case (AnyType(), _):
  18915. return True
  18916. case (_, AnyType()):
  18917. return True
  18918. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  18919. return all(map(self.consistent, ps1, ps2)) and consistent(rt1, rt2)
  18920. case (TupleType(ts1), TupleType(ts2)):
  18921. return all(map(self.consistent, ts1, ts2))
  18922. case (_, _):
  18923. return t1 == t2
  18924. \end{lstlisting}
  18925. \fi}
  18926. \vspace{-5pt}
  18927. \end{tcolorbox}
  18928. \caption{The consistency method on types.}
  18929. \label{fig:consistent}
  18930. \end{figure}
  18931. It is also helpful to consider how gradual typing handles programs with an
  18932. error, such as applying \code{map} to a function that sometimes
  18933. returns a Boolean, as shown in figure~\ref{fig:map-maybe_inc}. The
  18934. type checker for \LangGrad{} accepts this program because the type of
  18935. \code{maybe\_inc} is consistent with the type of parameter \code{f} of
  18936. \code{map}; that is,
  18937. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any],Any]}}
  18938. is consistent with
  18939. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  18940. One might say that a gradual type checker is optimistic in that it
  18941. accepts programs that might execute without a runtime type error.
  18942. %
  18943. The definition of the type checker for \LangGrad{} is shown in
  18944. figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  18945. and \ref{fig:type-check-Lgradual-3}.
  18946. %% \begin{figure}[tp]
  18947. %% \centering
  18948. %% \fbox{
  18949. %% \begin{minipage}{0.96\textwidth}
  18950. %% \small
  18951. %% \[
  18952. %% \begin{array}{lcl}
  18953. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  18954. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18955. %% \end{array}
  18956. %% \]
  18957. %% \end{minipage}
  18958. %% }
  18959. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (figure~\ref{fig:Lwhile-syntax}).}
  18960. %% \label{fig:Lgrad-prime-syntax}
  18961. %% \end{figure}
  18962. \begin{figure}[tbp]
  18963. \begin{tcolorbox}[colback=white]
  18964. {\if\edition\racketEd
  18965. \begin{lstlisting}
  18966. (define (map [f : (Integer -> Integer)]
  18967. [v : (Vector Integer Integer)])
  18968. : (Vector Integer Integer)
  18969. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18970. (define (inc x) (+ x 1))
  18971. (define (true) #t)
  18972. (define (maybe_inc x) (if (eq? 0 (read)) (inc x) (true)))
  18973. (vector-ref (map maybe_inc (vector 0 41)) 0)
  18974. \end{lstlisting}
  18975. \fi}
  18976. {\if\edition\pythonEd\pythonColor
  18977. \begin{lstlisting}
  18978. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  18979. return f(v[0]), f(v[1])
  18980. def inc(x):
  18981. return x + 1
  18982. def true():
  18983. return True
  18984. def maybe_inc(x):
  18985. return inc(x) if input_int() == 0 else true()
  18986. t = map(maybe_inc, (0, 41))
  18987. print(t[1])
  18988. \end{lstlisting}
  18989. \fi}
  18990. \vspace{-5pt}
  18991. \end{tcolorbox}
  18992. \caption{A variant of the \code{map} example with an error.}
  18993. \label{fig:map-maybe_inc}
  18994. \end{figure}
  18995. Running this program with input \code{1} triggers an
  18996. error when the \code{maybe\_inc} function returns
  18997. \racket{\code{\#t}}\python{\code{True}}. The \LangGrad{} language
  18998. performs checking at runtime to ensure the integrity of the static
  18999. types, such as the
  19000. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}
  19001. annotation on
  19002. parameter \code{f} of \code{map}.
  19003. Here we give a preview of how the runtime checking is accomplished;
  19004. the following sections provide the details.
  19005. The runtime checking is carried out by a new \code{Cast} AST node that
  19006. is generated in a new pass named \code{cast\_insert}. The output of
  19007. \code{cast\_insert} is a program in the \LangCast{} language, which
  19008. simply adds \code{Cast} and \CANYTY{} to \LangLam{}.
  19009. %
  19010. Figure~\ref{fig:map-cast} shows the output of \code{cast\_insert} for
  19011. \code{map} and \code{maybe\_inc}. The idea is that \code{Cast} is
  19012. inserted every time the type checker encounters two types that are
  19013. consistent but not equal. In the \code{inc} function, \code{x} is
  19014. cast to \INTTY{} and the result of the \code{+} is cast to
  19015. \CANYTY{}. In the call to \code{map}, the \code{inc} argument
  19016. is cast from
  19017. \racket{\code{(Any -> Any)}}
  19018. \python{\code{Callable[[Any], Any]}}
  19019. to
  19020. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int],int]}}.
  19021. %
  19022. In the next section we see how to interpret the \code{Cast} node.
  19023. \begin{figure}[btp]
  19024. \begin{tcolorbox}[colback=white]
  19025. {\if\edition\racketEd
  19026. \begin{lstlisting}
  19027. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  19028. : (Vector Integer Integer)
  19029. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19030. (define (inc [x : Any]) : Any
  19031. (cast (+ (cast x Any Integer) 1) Integer Any))
  19032. (define (true) : Any (cast #t Boolean Any))
  19033. (define (maybe_inc [x : Any]) : Any
  19034. (if (eq? 0 (read)) (inc x) (true)))
  19035. (vector-ref (map (cast maybe_inc (Any -> Any) (Integer -> Integer))
  19036. (vector 0 41)) 0)
  19037. \end{lstlisting}
  19038. \fi}
  19039. {\if\edition\pythonEd\pythonColor
  19040. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19041. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19042. return f(v[0]), f(v[1])
  19043. def inc(x : Any) -> Any:
  19044. return Cast(Cast(x, Any, int) + 1, int, Any)
  19045. def true() -> Any:
  19046. return Cast(True, bool, Any)
  19047. def maybe_inc(x : Any) -> Any:
  19048. return inc(x) if input_int() == 0 else true()
  19049. t = map(Cast(maybe_inc, Callable[[Any], Any], Callable[[int], int]),
  19050. (0, 41))
  19051. print(t[1])
  19052. \end{lstlisting}
  19053. \fi}
  19054. \vspace{-5pt}
  19055. \end{tcolorbox}
  19056. \caption{Output of the \code{cast\_insert} pass for the \code{map}
  19057. and \code{maybe\_inc} example.}
  19058. \label{fig:map-cast}
  19059. \end{figure}
  19060. {\if\edition\pythonEd\pythonColor
  19061. \begin{figure}[tbp]
  19062. \begin{tcolorbox}[colback=white]
  19063. \begin{lstlisting}
  19064. class TypeCheckLgrad(TypeCheckLlambda):
  19065. def type_check_exp(self, e, env) -> Type:
  19066. match e:
  19067. case Name(id):
  19068. return env[id]
  19069. case Constant(value) if isinstance(value, bool):
  19070. return BoolType()
  19071. case Constant(value) if isinstance(value, int):
  19072. return IntType()
  19073. case Call(Name('input_int'), []):
  19074. return IntType()
  19075. case BinOp(left, op, right):
  19076. left_type = self.type_check_exp(left, env)
  19077. self.check_consistent(left_type, IntType(), left)
  19078. right_type = self.type_check_exp(right, env)
  19079. self.check_consistent(right_type, IntType(), right)
  19080. return IntType()
  19081. case IfExp(test, body, orelse):
  19082. test_t = self.type_check_exp(test, env)
  19083. self.check_consistent(test_t, BoolType(), test)
  19084. body_t = self.type_check_exp(body, env)
  19085. orelse_t = self.type_check_exp(orelse, env)
  19086. self.check_consistent(body_t, orelse_t, e)
  19087. return self.join_types(body_t, orelse_t)
  19088. case Call(func, args):
  19089. func_t = self.type_check_exp(func, env)
  19090. args_t = [self.type_check_exp(arg, env) for arg in args]
  19091. match func_t:
  19092. case FunctionType(params_t, return_t) \
  19093. if len(params_t) == len(args_t):
  19094. for (arg_t, param_t) in zip(args_t, params_t):
  19095. self.check_consistent(param_t, arg_t, e)
  19096. return return_t
  19097. case AnyType():
  19098. return AnyType()
  19099. case _:
  19100. raise Exception('type_check_exp: in call, unexpected '
  19101. + repr(func_t))
  19102. ...
  19103. case _:
  19104. raise Exception('type_check_exp: unexpected ' + repr(e))
  19105. \end{lstlisting}
  19106. \end{tcolorbox}
  19107. \caption{Type checking expressions in the \LangGrad{} language.}
  19108. \label{fig:type-check-Lgradual-1}
  19109. \end{figure}
  19110. \begin{figure}[tbp]
  19111. \begin{tcolorbox}[colback=white]
  19112. \begin{lstlisting}
  19113. def check_exp(self, e, expected_ty, env):
  19114. match e:
  19115. case Lambda(params, body):
  19116. match expected_ty:
  19117. case FunctionType(params_t, return_t):
  19118. new_env = env.copy().update(zip(params, params_t))
  19119. e.has_type = expected_ty
  19120. body_ty = self.type_check_exp(body, new_env)
  19121. self.check_consistent(body_ty, return_t)
  19122. case AnyType():
  19123. new_env = env.copy().update((p, AnyType()) for p in params)
  19124. e.has_type = FunctionType([AnyType()for _ in params],AnyType())
  19125. body_ty = self.type_check_exp(body, new_env)
  19126. case _:
  19127. raise Exception('lambda is not of type ' + str(expected_ty))
  19128. case _:
  19129. e_ty = self.type_check_exp(e, env)
  19130. self.check_consistent(e_ty, expected_ty, e)
  19131. \end{lstlisting}
  19132. \end{tcolorbox}
  19133. \caption{Checking expressions with respect to a type in the \LangGrad{} language.}
  19134. \label{fig:type-check-Lgradual-2}
  19135. \end{figure}
  19136. \begin{figure}[tbp]
  19137. \begin{tcolorbox}[colback=white]
  19138. \begin{lstlisting}
  19139. def type_check_stmt(self, s, env, return_type):
  19140. match s:
  19141. case Assign([Name(id)], value):
  19142. value_ty = self.type_check_exp(value, env)
  19143. if id in env:
  19144. self.check_consistent(env[id], value_ty, value)
  19145. else:
  19146. env[id] = value_ty
  19147. ...
  19148. case _:
  19149. raise Exception('type_check_stmts: unexpected ' + repr(ss))
  19150. def type_check_stmts(self, ss, env, return_type):
  19151. for s in ss:
  19152. self.type_check_stmt(s, env, return_type)
  19153. \end{lstlisting}
  19154. \end{tcolorbox}
  19155. \caption{Type checking statements in the \LangGrad{} language.}
  19156. \label{fig:type-check-Lgradual-3}
  19157. \end{figure}
  19158. \clearpage
  19159. \begin{figure}[tbp]
  19160. \begin{tcolorbox}[colback=white]
  19161. \begin{lstlisting}
  19162. def join_types(self, t1, t2):
  19163. match (t1, t2):
  19164. case (AnyType(), _):
  19165. return t2
  19166. case (_, AnyType()):
  19167. return t1
  19168. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19169. return FunctionType(list(map(self.join_types, ps1, ps2)),
  19170. self.join_types(rt1,rt2))
  19171. case (TupleType(ts1), TupleType(ts2)):
  19172. return TupleType(list(map(self.join_types, ts1, ts2)))
  19173. case (_, _):
  19174. return t1
  19175. def check_consistent(self, t1, t2, e):
  19176. if not self.consistent(t1, t2):
  19177. raise Exception('error: ' + repr(t1) + ' inconsistent with ' \
  19178. + repr(t2) + ' in ' + repr(e))
  19179. \end{lstlisting}
  19180. \end{tcolorbox}
  19181. \caption{Auxiliary methods for type checking \LangGrad{}.}
  19182. \label{fig:type-check-Lgradual-aux}
  19183. \end{figure}
  19184. \fi}
  19185. {\if\edition\racketEd
  19186. \begin{figure}[tbp]
  19187. \begin{tcolorbox}[colback=white]
  19188. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19189. (define/override (type-check-exp env)
  19190. (lambda (e)
  19191. (define recur (type-check-exp env))
  19192. (match e
  19193. [(Prim op es) #:when (not (set-member? explicit-prim-ops op))
  19194. (define-values (new-es ts)
  19195. (for/lists (exprs types) ([e es])
  19196. (recur e)))
  19197. (define t-ret (type-check-op op ts e))
  19198. (values (Prim op new-es) t-ret)]
  19199. [(Prim 'eq? (list e1 e2))
  19200. (define-values (e1^ t1) (recur e1))
  19201. (define-values (e2^ t2) (recur e2))
  19202. (check-consistent? t1 t2 e)
  19203. (define T (meet t1 t2))
  19204. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  19205. [(Prim 'and (list e1 e2))
  19206. (recur (If e1 e2 (Bool #f)))]
  19207. [(Prim 'or (list e1 e2))
  19208. (define tmp (gensym 'tmp))
  19209. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  19210. [(If e1 e2 e3)
  19211. (define-values (e1^ T1) (recur e1))
  19212. (define-values (e2^ T2) (recur e2))
  19213. (define-values (e3^ T3) (recur e3))
  19214. (check-consistent? T1 'Boolean e)
  19215. (check-consistent? T2 T3 e)
  19216. (define Tif (meet T2 T3))
  19217. (values (If e1^ e2^ e3^) Tif)]
  19218. [(SetBang x e1)
  19219. (define-values (e1^ T1) (recur e1))
  19220. (define varT (dict-ref env x))
  19221. (check-consistent? T1 varT e)
  19222. (values (SetBang x e1^) 'Void)]
  19223. [(WhileLoop e1 e2)
  19224. (define-values (e1^ T1) (recur e1))
  19225. (check-consistent? T1 'Boolean e)
  19226. (define-values (e2^ T2) ((type-check-exp env) e2))
  19227. (values (WhileLoop e1^ e2^) 'Void)]
  19228. [(Prim 'vector-length (list e1))
  19229. (define-values (e1^ t) (recur e1))
  19230. (match t
  19231. [`(Vector ,ts ...)
  19232. (values (Prim 'vector-length (list e1^)) 'Integer)]
  19233. ['Any (values (Prim 'vector-length (list e1^)) 'Integer)])]
  19234. \end{lstlisting}
  19235. \end{tcolorbox}
  19236. \caption{Type checker for the \LangGrad{} language, part 1.}
  19237. \label{fig:type-check-Lgradual-1}
  19238. \end{figure}
  19239. \begin{figure}[tbp]
  19240. \begin{tcolorbox}[colback=white]
  19241. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19242. [(Prim 'vector-ref (list e1 e2))
  19243. (define-values (e1^ t1) (recur e1))
  19244. (define-values (e2^ t2) (recur e2))
  19245. (check-consistent? t2 'Integer e)
  19246. (match t1
  19247. [`(Vector ,ts ...)
  19248. (match e2^
  19249. [(Int i)
  19250. (unless (and (0 . <= . i) (i . < . (length ts)))
  19251. (error 'type-check "invalid index ~a in ~a" i e))
  19252. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  19253. [else (values (Prim 'vector-ref (list e1^ e2^)) 'Any)])]
  19254. ['Any (values (Prim 'vector-ref (list e1^ e2^)) 'Any)]
  19255. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19256. [(Prim 'vector-set! (list e1 e2 e3) )
  19257. (define-values (e1^ t1) (recur e1))
  19258. (define-values (e2^ t2) (recur e2))
  19259. (define-values (e3^ t3) (recur e3))
  19260. (check-consistent? t2 'Integer e)
  19261. (match t1
  19262. [`(Vector ,ts ...)
  19263. (match e2^
  19264. [(Int i)
  19265. (unless (and (0 . <= . i) (i . < . (length ts)))
  19266. (error 'type-check "invalid index ~a in ~a" i e))
  19267. (check-consistent? (list-ref ts i) t3 e)
  19268. (values (Prim 'vector-set! (list e1^ (Int i) e3^)) 'Void)]
  19269. [else (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)])]
  19270. ['Any (values (Prim 'vector-set! (list e1^ e2^ e3^)) 'Void)]
  19271. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  19272. [(Apply e1 e2s)
  19273. (define-values (e1^ T1) (recur e1))
  19274. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  19275. (match T1
  19276. [`(,T1ps ... -> ,T1rt)
  19277. (for ([T2 T2s] [Tp T1ps])
  19278. (check-consistent? T2 Tp e))
  19279. (values (Apply e1^ e2s^) T1rt)]
  19280. [`Any (values (Apply e1^ e2s^) 'Any)]
  19281. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  19282. [(Lambda params Tr e1)
  19283. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  19284. (match p
  19285. [`[,x : ,T] (values x T)]
  19286. [(? symbol? x) (values x 'Any)])))
  19287. (define-values (e1^ T1)
  19288. ((type-check-exp (append (map cons xs Ts) env)) e1))
  19289. (check-consistent? Tr T1 e)
  19290. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr e1^)
  19291. `(,@Ts -> ,Tr))]
  19292. [else ((super type-check-exp env) e)]
  19293. )))
  19294. \end{lstlisting}
  19295. \end{tcolorbox}
  19296. \caption{Type checker for the \LangGrad{} language, part 2.}
  19297. \label{fig:type-check-Lgradual-2}
  19298. \end{figure}
  19299. \begin{figure}[tbp]
  19300. \begin{tcolorbox}[colback=white]
  19301. \begin{lstlisting}
  19302. (define/override (type-check-def env)
  19303. (lambda (e)
  19304. (match e
  19305. [(Def f params rt info body)
  19306. (define-values (xs ps) (for/lists (l1 l2) ([p params])
  19307. (match p
  19308. [`[,x : ,T] (values x T)]
  19309. [(? symbol? x) (values x 'Any)])))
  19310. (define new-env (append (map cons xs ps) env))
  19311. (define-values (body^ ty^) ((type-check-exp new-env) body))
  19312. (check-consistent? ty^ rt e)
  19313. (Def f (for/list ([x xs] [T ps]) `[,x : ,T]) rt info body^)]
  19314. [else (error 'type-check "ill-formed function definition ~a" e)]
  19315. )))
  19316. (define/override (type-check-program e)
  19317. (match e
  19318. [(Program info body)
  19319. (define-values (body^ ty) ((type-check-exp '()) body))
  19320. (check-consistent? ty 'Integer e)
  19321. (ProgramDefsExp info '() body^)]
  19322. [(ProgramDefsExp info ds body)
  19323. (define new-env (for/list ([d ds])
  19324. (cons (Def-name d) (fun-def-type d))))
  19325. (define ds^ (for/list ([d ds])
  19326. ((type-check-def new-env) d)))
  19327. (define-values (body^ ty) ((type-check-exp new-env) body))
  19328. (check-consistent? ty 'Integer e)
  19329. (ProgramDefsExp info ds^ body^)]
  19330. [else (super type-check-program e)]))
  19331. \end{lstlisting}
  19332. \end{tcolorbox}
  19333. \caption{Type checker for the \LangGrad{} language, part 3.}
  19334. \label{fig:type-check-Lgradual-3}
  19335. \end{figure}
  19336. \begin{figure}[tbp]
  19337. \begin{tcolorbox}[colback=white]
  19338. \begin{lstlisting}
  19339. (define/public (join t1 t2)
  19340. (match* (t1 t2)
  19341. [('Integer 'Integer) 'Integer]
  19342. [('Boolean 'Boolean) 'Boolean]
  19343. [('Void 'Void) 'Void]
  19344. [('Any t2) t2]
  19345. [(t1 'Any) t1]
  19346. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19347. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  19348. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19349. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  19350. -> ,(join rt1 rt2))]))
  19351. (define/public (meet t1 t2)
  19352. (match* (t1 t2)
  19353. [('Integer 'Integer) 'Integer]
  19354. [('Boolean 'Boolean) 'Boolean]
  19355. [('Void 'Void) 'Void]
  19356. [('Any t2) 'Any]
  19357. [(t1 'Any) 'Any]
  19358. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19359. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  19360. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19361. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  19362. -> ,(meet rt1 rt2))]))
  19363. (define/public (check-consistent? t1 t2 e)
  19364. (unless (consistent? t1 t2)
  19365. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  19366. (define explicit-prim-ops
  19367. (set-union
  19368. (type-predicates)
  19369. (set 'procedure-arity 'eq? 'not 'and 'or
  19370. 'vector 'vector-length 'vector-ref 'vector-set!
  19371. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  19372. (define/override (fun-def-type d)
  19373. (match d
  19374. [(Def f params rt info body)
  19375. (define ps
  19376. (for/list ([p params])
  19377. (match p
  19378. [`[,x : ,T] T]
  19379. [(? symbol?) 'Any]
  19380. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  19381. `(,@ps -> ,rt)]
  19382. [else (error 'fun-def-type "ill-formed definition in ~a" d)]))
  19383. \end{lstlisting}
  19384. \end{tcolorbox}
  19385. \caption{Auxiliary functions for type checking \LangGrad{}.}
  19386. \label{fig:type-check-Lgradual-aux}
  19387. \end{figure}
  19388. \fi}
  19389. \section{Interpreting \LangCast{} }
  19390. \label{sec:interp-casts}
  19391. The runtime behavior of casts involving simple types such as
  19392. \INTTY{} and \BOOLTY{} is straightforward. For example, a
  19393. cast from \INTTY{} to \CANYTY{} can be accomplished with the
  19394. \code{Inject} operator of \LangAny{}, which puts the integer into a
  19395. tagged value (figure~\ref{fig:interp-Lany}). Similarly, a cast from
  19396. \CANYTY{} to \INTTY{} is accomplished with the \code{Project}
  19397. operator, by checking the value's tag and either retrieving
  19398. the underlying integer or signaling an error if the tag is not the
  19399. one for integers (figure~\ref{fig:interp-Lany-aux}).
  19400. %
  19401. Things get more interesting with casts involving
  19402. \racket{function and tuple types}\python{function, tuple, and array types}.
  19403. Consider the cast of the function \code{maybe\_inc} from
  19404. \racket{\code{(Any -> Any)}}\python{\code{Callable[[Any], Any]}}
  19405. to
  19406. \racket{\code{(Integer -> Integer)}}\python{\code{Callable[[int], int]}}
  19407. shown in figure~\ref{fig:map-maybe_inc}.
  19408. When the \code{maybe\_inc} function flows through
  19409. this cast at runtime, we don't know whether it will return
  19410. an integer, because that depends on the input from the user.
  19411. The \LangCast{} interpreter therefore delays the checking
  19412. of the cast until the function is applied. To do so it
  19413. wraps \code{maybe\_inc} in a new function that casts its parameter
  19414. from \INTTY{} to \CANYTY{}, applies \code{maybe\_inc}, and then
  19415. casts the return value from \CANYTY{} to \INTTY{}.
  19416. {\if\edition\pythonEd\pythonColor
  19417. %
  19418. There are further complications regarding casts on mutable data,
  19419. such as the \code{list} type introduced in
  19420. the challenge assignment of section~\ref{sec:arrays}.
  19421. %
  19422. \fi}
  19423. %
  19424. Consider the example presented in figure~\ref{fig:map-bang} that
  19425. defines a partially typed version of \code{map} whose parameter
  19426. \code{v} has type
  19427. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}
  19428. and that updates \code{v} in place
  19429. instead of returning a new tuple. We name this function
  19430. \code{map\_inplace}. We apply \code{map\_inplace} to
  19431. \racket{a tuple}\python{an array} of integers, so the type checker
  19432. inserts a cast from
  19433. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}}
  19434. to
  19435. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}.
  19436. A naive way for the \LangCast{} interpreter to cast between
  19437. \racket{tuple}\python{array} types would be to build a new
  19438. \racket{tuple}\python{array} whose elements are the result
  19439. of casting each of the original elements to the target
  19440. type. However, this approach is not valid for mutable data structures.
  19441. In the example of figure~\ref{fig:map-bang},
  19442. if the cast created a new \racket{tuple}\python{array}, then the updates inside
  19443. \code{map\_inplace} would happen to the new \racket{tuple}\python{array} and not
  19444. the original one.
  19445. Instead the interpreter needs to create a new kind of value, a
  19446. \emph{proxy}, that intercepts every \racket{tuple}\python{array} operation.
  19447. On a read, the proxy reads from the underlying \racket{tuple}\python{array}
  19448. and then applies a
  19449. cast to the resulting value. On a write, the proxy casts the argument
  19450. value and then performs the write to the underlying \racket{tuple}\python{array}.
  19451. \racket{
  19452. For the first \code{(vector-ref v 0)} in \code{map\_inplace}, the proxy casts
  19453. \code{0} from \INTTY{} to \CANYTY{}.
  19454. For the first \code{vector-set!}, the proxy casts a tagged \code{1}
  19455. from \CANYTY{} to \INTTY{}.
  19456. }
  19457. \python{
  19458. For the subscript \code{v[i]} in \code{f(v[i])} of \code{map\_inplace},
  19459. the proxy casts the integer from \INTTY{} to \CANYTY{}.
  19460. For the subscript on the left of the assignment,
  19461. the proxy casts the tagged value from \CANYTY{} to \INTTY{}.
  19462. }
  19463. Finally we consider casts between the \CANYTY{} type and higher-order types
  19464. such as functions and \racket{tuples}\python{lists}. Figure~\ref{fig:map-any}
  19465. shows a variant of \code{map\_inplace} in which parameter \code{v} does not
  19466. have a type annotation, so it is given type \CANYTY{}. In the call to
  19467. \code{map\_inplace}, the \racket{tuple}\python{list} has type
  19468. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}},
  19469. so the type checker inserts a cast to \CANYTY{}. A first thought is to use
  19470. \code{Inject}, but that doesn't work because
  19471. \racket{\code{(Vector Integer Integer)}}\python{\code{list[int]}} is not
  19472. a flat type. Instead, we must first cast to
  19473. \racket{\code{(Vector Any Any)}}\python{\code{list[Any]}}, which is flat,
  19474. and then inject to \CANYTY{}.
  19475. \begin{figure}[tbp]
  19476. \begin{tcolorbox}[colback=white]
  19477. % gradual_test_11.rkt
  19478. {\if\edition\racketEd
  19479. \begin{lstlisting}
  19480. (define (map_inplace [f : (Any -> Any)]
  19481. [v : (Vector Any Any)]) : Void
  19482. (begin
  19483. (vector-set! v 0 (f (vector-ref v 0)))
  19484. (vector-set! v 1 (f (vector-ref v 1)))))
  19485. (define (inc x) (+ x 1))
  19486. (let ([v (vector 0 41)])
  19487. (begin (map_inplace inc v) (vector-ref v 1)))
  19488. \end{lstlisting}
  19489. \fi}
  19490. {\if\edition\pythonEd\pythonColor
  19491. \begin{lstlisting}
  19492. def map_inplace(f : Callable[[int], int], v : list[Any]) -> None:
  19493. i = 0
  19494. while i != len(v):
  19495. v[i] = f(v[i])
  19496. i = i + 1
  19497. def inc(x : int) -> int:
  19498. return x + 1
  19499. v = [0, 41]
  19500. map_inplace(inc, v)
  19501. print(v[1])
  19502. \end{lstlisting}
  19503. \fi}
  19504. \end{tcolorbox}
  19505. \caption{An example involving casts on arrays.}
  19506. \label{fig:map-bang}
  19507. \end{figure}
  19508. \begin{figure}[btp]
  19509. \begin{tcolorbox}[colback=white]
  19510. {\if\edition\racketEd
  19511. \begin{lstlisting}
  19512. (define (map_inplace [f : (Any -> Any)] v) : Void
  19513. (begin
  19514. (vector-set! v 0 (f (vector-ref v 0)))
  19515. (vector-set! v 1 (f (vector-ref v 1)))))
  19516. (define (inc x) (+ x 1))
  19517. (let ([v (vector 0 41)])
  19518. (begin (map_inplace inc v) (vector-ref v 1)))
  19519. \end{lstlisting}
  19520. \fi}
  19521. {\if\edition\pythonEd\pythonColor
  19522. \begin{lstlisting}
  19523. def map_inplace(f : Callable[[Any], Any], v) -> None:
  19524. i = 0
  19525. while i != len(v):
  19526. v[i] = f(v[i])
  19527. i = i + 1
  19528. def inc(x):
  19529. return x + 1
  19530. v = [0, 41]
  19531. map_inplace(inc, v)
  19532. print(v[1])
  19533. \end{lstlisting}
  19534. \fi}
  19535. \end{tcolorbox}
  19536. \caption{Casting \racket{a tuple}\python{an array} to \CANYTY{}.}
  19537. \label{fig:map-any}
  19538. \end{figure}
  19539. \begin{figure}[tbp]
  19540. \begin{tcolorbox}[colback=white]
  19541. {\if\edition\racketEd
  19542. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19543. (define/public (apply_cast v s t)
  19544. (match* (s t)
  19545. [(t1 t2) #:when (equal? t1 t2) v]
  19546. [('Any t2)
  19547. (match t2
  19548. [`(,ts ... -> ,rt)
  19549. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19550. (define v^ (apply-project v any->any))
  19551. (apply_cast v^ any->any `(,@ts -> ,rt))]
  19552. [`(Vector ,ts ...)
  19553. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19554. (define v^ (apply-project v vec-any))
  19555. (apply_cast v^ vec-any `(Vector ,@ts))]
  19556. [else (apply-project v t2)])]
  19557. [(t1 'Any)
  19558. (match t1
  19559. [`(,ts ... -> ,rt)
  19560. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  19561. (define v^ (apply_cast v `(,@ts -> ,rt) any->any))
  19562. (apply-inject v^ (any-tag any->any))]
  19563. [`(Vector ,ts ...)
  19564. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  19565. (define v^ (apply_cast v `(Vector ,@ts) vec-any))
  19566. (apply-inject v^ (any-tag vec-any))]
  19567. [else (apply-inject v (any-tag t1))])]
  19568. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  19569. (define x (gensym 'x))
  19570. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  19571. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  19572. (define cast-writes
  19573. (for/list ([t1 ts1] [t2 ts2])
  19574. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  19575. `(vector-proxy ,(vector v (apply vector cast-reads)
  19576. (apply vector cast-writes)))]
  19577. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  19578. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  19579. `(function ,xs ,(Cast
  19580. (Apply (Value v)
  19581. (for/list ([x xs][t1 ts1][t2 ts2])
  19582. (Cast (Var x) t2 t1)))
  19583. rt1 rt2) ())]
  19584. ))
  19585. \end{lstlisting}
  19586. \fi}
  19587. {\if\edition\pythonEd\pythonColor
  19588. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19589. def apply_cast(self, value, src, tgt):
  19590. match (src, tgt):
  19591. case (AnyType(), FunctionType(ps2, rt2)):
  19592. anyfun = FunctionType([AnyType() for p in ps2], AnyType())
  19593. return self.apply_cast(self.apply_project(value, anyfun), anyfun, tgt)
  19594. case (AnyType(), TupleType(ts2)):
  19595. anytup = TupleType([AnyType() for t1 in ts2])
  19596. return self.apply_cast(self.apply_project(value, anytup), anytup, tgt)
  19597. case (AnyType(), ListType(t2)):
  19598. anylist = ListType([AnyType() for t1 in ts2])
  19599. return self.apply_cast(self.apply_project(value, anylist), anylist, tgt)
  19600. case (AnyType(), AnyType()):
  19601. return value
  19602. case (AnyType(), _):
  19603. return self.apply_project(value, tgt)
  19604. case (FunctionType(ps1,rt1), AnyType()):
  19605. anyfun = FunctionType([AnyType() for p in ps1], AnyType())
  19606. return self.apply_inject(self.apply_cast(value, src, anyfun), anyfun)
  19607. case (TupleType(ts1), AnyType()):
  19608. anytup = TupleType([AnyType() for t1 in ts1])
  19609. return self.apply_inject(self.apply_cast(value, src, anytup), anytup)
  19610. case (ListType(t1), AnyType()):
  19611. anylist = ListType(AnyType())
  19612. return self.apply_inject(self.apply_cast(value,src,anylist), anylist)
  19613. case (_, AnyType()):
  19614. return self.apply_inject(value, src)
  19615. case (FunctionType(ps1, rt1), FunctionType(ps2, rt2)):
  19616. params = [generate_name('x') for p in ps2]
  19617. args = [Cast(Name(x), t2, t1)
  19618. for (x,t1,t2) in zip(params, ps1, ps2)]
  19619. body = Cast(Call(ValueExp(value), args), rt1, rt2)
  19620. return Function('cast', params, [Return(body)], {})
  19621. case (TupleType(ts1), TupleType(ts2)):
  19622. x = generate_name('x')
  19623. reads = [Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19624. for (t1,t2) in zip(ts1,ts2)]
  19625. return ProxiedTuple(value, reads)
  19626. case (ListType(t1), ListType(t2)):
  19627. x = generate_name('x')
  19628. read = Function('cast', [x], [Return(Cast(Name(x), t1, t2))], {})
  19629. write = Function('cast', [x], [Return(Cast(Name(x), t2, t1))], {})
  19630. return ProxiedList(value, read, write)
  19631. case (t1, t2) if t1 == t2:
  19632. return value
  19633. case (t1, t2):
  19634. raise Exception('apply_cast unexpected ' + repr(src) + ' ' + repr(tgt))
  19635. def apply_inject(self, value, src):
  19636. return Tagged(value, self.type_to_tag(src))
  19637. def apply_project(self, value, tgt):
  19638. match value:
  19639. case Tagged(val, tag) if self.type_to_tag(tgt) == tag:
  19640. return val
  19641. case _:
  19642. raise Exception('apply_project, unexpected ' + repr(value))
  19643. \end{lstlisting}
  19644. \fi}
  19645. \end{tcolorbox}
  19646. \caption{The \code{apply\_cast} auxiliary method.}
  19647. \label{fig:apply_cast}
  19648. \end{figure}
  19649. The \LangCast{} interpreter uses an auxiliary function named
  19650. \code{apply\_cast} to cast a value from a source type to a target type,
  19651. shown in figure~\ref{fig:apply_cast}. You'll find that it handles all
  19652. the kinds of casts that we've discussed in this section.
  19653. %
  19654. The definition of the interpreter for \LangCast{} is shown in
  19655. figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  19656. dispatching to \code{apply\_cast}.
  19657. \racket{To handle the addition of tuple
  19658. proxies, we update the tuple primitives in \code{interp-op} using the
  19659. functions given in figure~\ref{fig:guarded-tuple}.}
  19660. Next we turn to the individual passes needed for compiling \LangGrad{}.
  19661. \begin{figure}[tbp]
  19662. \begin{tcolorbox}[colback=white]
  19663. {\if\edition\racketEd
  19664. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19665. (define interp-Lcast-class
  19666. (class interp-Llambda-class
  19667. (super-new)
  19668. (inherit apply-fun apply-inject apply-project)
  19669. (define/override (interp-op op)
  19670. (match op
  19671. ['vector-length guarded-vector-length]
  19672. ['vector-ref guarded-vector-ref]
  19673. ['vector-set! guarded-vector-set!]
  19674. ['any-vector-ref (lambda (v i)
  19675. (match v [`(tagged ,v^ ,tg)
  19676. (guarded-vector-ref v^ i)]))]
  19677. ['any-vector-set! (lambda (v i a)
  19678. (match v [`(tagged ,v^ ,tg)
  19679. (guarded-vector-set! v^ i a)]))]
  19680. ['any-vector-length (lambda (v)
  19681. (match v [`(tagged ,v^ ,tg)
  19682. (guarded-vector-length v^)]))]
  19683. [else (super interp-op op)]
  19684. ))
  19685. (define/override ((interp-exp env) e)
  19686. (define (recur e) ((interp-exp env) e))
  19687. (match e
  19688. [(Value v) v]
  19689. [(Cast e src tgt) (apply_cast (recur e) src tgt)]
  19690. [else ((super interp-exp env) e)]))
  19691. ))
  19692. (define (interp-Lcast p)
  19693. (send (new interp-Lcast-class) interp-program p))
  19694. \end{lstlisting}
  19695. \fi}
  19696. {\if\edition\pythonEd\pythonColor
  19697. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19698. class InterpLcast(InterpLany):
  19699. def interp_exp(self, e, env):
  19700. match e:
  19701. case Cast(value, src, tgt):
  19702. v = self.interp_exp(value, env)
  19703. return self.apply_cast(v, src, tgt)
  19704. case ValueExp(value):
  19705. return value
  19706. ...
  19707. case _:
  19708. return super().interp_exp(e, env)
  19709. \end{lstlisting}
  19710. \fi}
  19711. \end{tcolorbox}
  19712. \caption{The interpreter for \LangCast{}.}
  19713. \label{fig:interp-Lcast}
  19714. \end{figure}
  19715. {\if\edition\racketEd
  19716. \begin{figure}[tbp]
  19717. \begin{tcolorbox}[colback=white]
  19718. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19719. (define (guarded-vector-ref vec i)
  19720. (match vec
  19721. [`(vector-proxy ,proxy)
  19722. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  19723. (define rd (vector-ref (vector-ref proxy 1) i))
  19724. (apply-fun rd (list val) 'guarded-vector-ref)]
  19725. [else (vector-ref vec i)]))
  19726. (define (guarded-vector-set! vec i arg)
  19727. (match vec
  19728. [`(vector-proxy ,proxy)
  19729. (define wr (vector-ref (vector-ref proxy 2) i))
  19730. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  19731. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  19732. [else (vector-set! vec i arg)]))
  19733. (define (guarded-vector-length vec)
  19734. (match vec
  19735. [`(vector-proxy ,proxy)
  19736. (guarded-vector-length (vector-ref proxy 0))]
  19737. [else (vector-length vec)]))
  19738. \end{lstlisting}
  19739. %% {\if\edition\pythonEd\pythonColor
  19740. %% \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19741. %% UNDER CONSTRUCTION
  19742. %% \end{lstlisting}
  19743. %% \fi}
  19744. \end{tcolorbox}
  19745. \caption{The \code{guarded-vector} auxiliary functions.}
  19746. \label{fig:guarded-tuple}
  19747. \end{figure}
  19748. \fi}
  19749. {\if\edition\pythonEd\pythonColor
  19750. \section{Overload Resolution }
  19751. \label{sec:gradual-resolution}
  19752. Recall that when we added support for arrays in
  19753. section~\ref{sec:arrays}, the syntax for the array operations were the
  19754. same as for tuple operations (for example, accessing an element and
  19755. getting the length). So we performed overload resolution, with a pass
  19756. named \code{resolve}, to separate the array and tuple operations. In
  19757. particular, we introduced the primitives \code{array\_load},
  19758. \code{array\_store}, and \code{array\_len}.
  19759. For gradual typing, we further overload these operators to work on
  19760. values of type \CANYTY{}. Thus, the \code{resolve} pass should be
  19761. updated with new cases for the \CANYTY{} type, translating the element
  19762. access and length operations to the primitives \code{any\_load},
  19763. \code{any\_store}, and \code{any\_len}.
  19764. \fi}
  19765. \section{Cast Insertion }
  19766. \label{sec:gradual-insert-casts}
  19767. In our discussion of type checking of \LangGrad{}, we mentioned how
  19768. the runtime aspect of type checking is carried out by the \code{Cast}
  19769. AST node, which is added to the program by a new pass named
  19770. \code{cast\_insert}. The target of this pass is the \LangCast{}
  19771. language. We now discuss the details of this pass.
  19772. The \code{cast\_insert} pass is closely related to the type checker
  19773. for \LangGrad{} (starting in figure~\ref{fig:type-check-Lgradual-1}).
  19774. In particular, the type checker allows implicit casts between
  19775. consistent types. The job of the \code{cast\_insert} pass is to make
  19776. those casts explicit. It does so by inserting
  19777. \code{Cast} nodes into the AST.
  19778. %
  19779. For the most part, the implicit casts occur in places where the type
  19780. checker checks two types for consistency. Consider the case for
  19781. binary operators in figure~\ref{fig:type-check-Lgradual-1}. The type
  19782. checker requires that the type of the left operand is consistent with
  19783. \INTTY{}. Thus, the \code{cast\_insert} pass should insert a
  19784. \code{Cast} around the left operand, converting from its type to
  19785. \INTTY{}. The story is similar for the right operand. It is not always
  19786. necessary to insert a cast, for example, if the left operand already has type
  19787. \INTTY{} then there is no need for a \code{Cast}.
  19788. Some of the implicit casts are not as straightforward. One such case
  19789. arises with the
  19790. conditional expression. In figure~\ref{fig:type-check-Lgradual-1} we
  19791. see that the type checker requires that the two branches have
  19792. consistent types and that type of the conditional expression is the
  19793. meet of the branches' types. In the target language \LangCast{}, both
  19794. branches will need to have the same type, and that type
  19795. will be the type of the conditional expression. Thus, each branch requires
  19796. a \code{Cast} to convert from its type to the meet of the branches' types.
  19797. The case for the function call exhibits another interesting situation. If
  19798. the function expression is of type \CANYTY{}, then it needs to be cast
  19799. to a function type so that it can be used in a function call in
  19800. \LangCast{}. Which function type should it be cast to? The parameter
  19801. and return types are unknown, so we can simply use \CANYTY{} for all
  19802. of them. Furthermore, in \LangCast{} the argument types will need to
  19803. exactly match the parameter types, so we must cast all the arguments
  19804. to type \CANYTY{} (if they are not already of that type).
  19805. {\if\edition\racketEd
  19806. %
  19807. Likewise, the cases for the tuple operators \code{vector-length},
  19808. \code{vector-ref}, and \code{vector-set!} need to handle the situation
  19809. where the tuple expression is of type \CANYTY{}. Instead of
  19810. handling these situations with casts, we recommend translating
  19811. the special-purpose variants of the tuple operators that handle
  19812. tuples of type \CANYTY{}: \code{any-vector-length},
  19813. \code{any-vector-ref}, and \code{any-vector-set!}.
  19814. %
  19815. \fi}
  19816. \section{Lower Casts }
  19817. \label{sec:lower_casts}
  19818. The next step in the journey toward x86 is the \code{lower\_casts}
  19819. pass that translates the casts in \LangCast{} to the lower-level
  19820. \code{Inject} and \code{Project} operators and new operators for
  19821. proxies, extending the \LangLam{} language to \LangProxy{}.
  19822. The \LangProxy{} language can also be described as an extension of
  19823. \LangAny{}, with the addition of proxies. We recommend creating an
  19824. auxiliary function named \code{lower\_cast} that takes an expression
  19825. (in \LangCast{}), a source type, and a target type and translates it
  19826. to an expression in \LangProxy{}.
  19827. The \code{lower\_cast} function can follow a code structure similar to
  19828. the \code{apply\_cast} function (figure~\ref{fig:apply_cast}) used in
  19829. the interpreter for \LangCast{}, because it must handle the same cases
  19830. as \code{apply\_cast} and it needs to mimic the behavior of
  19831. \code{apply\_cast}. The most interesting cases concern
  19832. the casts involving \racket{tuple and function types}\python{tuple, array, and function types}.
  19833. {\if\edition\racketEd
  19834. As mentioned in section~\ref{sec:interp-casts}, a cast from one tuple
  19835. type to another tuple type is accomplished by creating a proxy that
  19836. intercepts the operations on the underlying tuple. Here we make the
  19837. creation of the proxy explicit with the \code{vector-proxy} AST
  19838. node. It takes three arguments: the first is an expression for the
  19839. tuple, the second is a tuple of functions for casting an element that is
  19840. being read from the tuple, and the third is a tuple of functions for
  19841. casting an element that is being written to the array. You can create
  19842. the functions for reading and writing using lambda expressions. Also,
  19843. as we show in the next section, we need to differentiate these tuples
  19844. of functions from the user-created ones, so we recommend using a new
  19845. AST node named \code{raw-vector} instead of \code{vector}.
  19846. %
  19847. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19848. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19849. that involved casting a tuple of integers to a tuple of \CANYTY{}.
  19850. \fi}
  19851. {\if\edition\pythonEd\pythonColor
  19852. As mentioned in section~\ref{sec:interp-casts}, a cast from one array
  19853. type to another array type is accomplished by creating a proxy that
  19854. intercepts the operations on the underlying array. Here we make the
  19855. creation of the proxy explicit with the \code{ListProxy} AST node. It
  19856. takes fives arguments: the first is an expression for the array, the
  19857. second is a function for casting an element that is being read from
  19858. the array, the third is a function for casting an element that is
  19859. being written to the array, the fourth is the type of the underlying
  19860. array, and the fifth is the type of the proxied array. You can create
  19861. the functions for reading and writing using lambda expressions.
  19862. A cast between two tuple types can be handled in a similar manner. We
  19863. create a proxy with the \code{TupleProxy} AST node. Tuples are
  19864. immutable, so there is no need for a function to cast the value during
  19865. a write. Because there is a separate element type for each slot in
  19866. the tuple, we need more than one function for casting during a read:
  19867. we need a tuple of functions.
  19868. %
  19869. Also, as we show in the next section, we need to differentiate these
  19870. tuples from the user-created ones, so we recommend using a new AST
  19871. node named \code{RawTuple} instead of \code{Tuple} to create the
  19872. tuples of functions.
  19873. %
  19874. Figure~\ref{fig:map-bang-lower-cast} shows the output of
  19875. \code{lower\_casts} on the example given in figure~\ref{fig:map-bang}
  19876. that involves casting an array of integers to an array of \CANYTY{}.
  19877. \fi}
  19878. \begin{figure}[tbp]
  19879. \begin{tcolorbox}[colback=white]
  19880. {\if\edition\racketEd
  19881. \begin{lstlisting}
  19882. (define (map_inplace [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  19883. (begin
  19884. (vector-set! v 0 (f (vector-ref v 0)))
  19885. (vector-set! v 1 (f (vector-ref v 1)))))
  19886. (define (inc [x : Any]) : Any
  19887. (inject (+ (project x Integer) 1) Integer))
  19888. (let ([v (vector 0 41)])
  19889. (begin
  19890. (map_inplace inc (vector-proxy v
  19891. (raw-vector (lambda: ([x9 : Integer]) : Any
  19892. (inject x9 Integer))
  19893. (lambda: ([x9 : Integer]) : Any
  19894. (inject x9 Integer)))
  19895. (raw-vector (lambda: ([x9 : Any]) : Integer
  19896. (project x9 Integer))
  19897. (lambda: ([x9 : Any]) : Integer
  19898. (project x9 Integer)))))
  19899. (vector-ref v 1)))
  19900. \end{lstlisting}
  19901. \fi}
  19902. {\if\edition\pythonEd\pythonColor
  19903. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19904. def map_inplace(f : Callable[[int], int], v : list[Any]) -> void:
  19905. i = 0
  19906. while i != array_len(v):
  19907. array_store(v, i, inject(f(project(array_load(v, i), int)), int))
  19908. i = (i + 1)
  19909. def inc(x : int) -> int:
  19910. return (x + 1)
  19911. def main() -> int:
  19912. v = [0, 41]
  19913. map_inplace(inc, array_proxy(v, list[int], list[Any]))
  19914. print(array_load(v, 1))
  19915. return 0
  19916. \end{lstlisting}
  19917. \fi}
  19918. \end{tcolorbox}
  19919. \caption{Output of \code{lower\_casts} on the example shown in
  19920. figure~\ref{fig:map-bang}.}
  19921. \label{fig:map-bang-lower-cast}
  19922. \end{figure}
  19923. A cast from one function type to another function type is accomplished
  19924. by generating a \code{lambda} whose parameter and return types match
  19925. the target function type. The body of the \code{lambda} should cast
  19926. the parameters from the target type to the source type. (Yes,
  19927. backward! Functions are contravariant\index{subject}{contravariant}
  19928. in the parameters.) Afterward, call the underlying function and then
  19929. cast the result from the source return type to the target return type.
  19930. Figure~\ref{fig:map-lower-cast} shows the output of the
  19931. \code{lower\_casts} pass on the \code{map} example given in
  19932. figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  19933. call to \code{map} is wrapped in a \code{lambda}.
  19934. \begin{figure}[tbp]
  19935. \begin{tcolorbox}[colback=white]
  19936. {\if\edition\racketEd
  19937. \begin{lstlisting}
  19938. (define (map [f : (Integer -> Integer)]
  19939. [v : (Vector Integer Integer)])
  19940. : (Vector Integer Integer)
  19941. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  19942. (define (inc [x : Any]) : Any
  19943. (inject (+ (project x Integer) 1) Integer))
  19944. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  19945. (project (inc (inject x9 Integer)) Integer))
  19946. (vector 0 41)) 1)
  19947. \end{lstlisting}
  19948. \fi}
  19949. {\if\edition\pythonEd\pythonColor
  19950. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  19951. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  19952. return (f(v[0]), f(v[1]),)
  19953. def inc(x : any) -> any:
  19954. return inject((project(x, int) + 1), int)
  19955. def main() -> int:
  19956. t = map(lambda x: project(inc(inject(x, int)), int), (0, 41,))
  19957. print(t[1])
  19958. return 0
  19959. \end{lstlisting}
  19960. \fi}
  19961. \end{tcolorbox}
  19962. \caption{Output of \code{lower\_casts} on the example shown in
  19963. figure~\ref{fig:gradual-map}.}
  19964. \label{fig:map-lower-cast}
  19965. \end{figure}
  19966. %\pagebreak
  19967. \section{Differentiate Proxies }
  19968. \label{sec:differentiate-proxies}
  19969. So far, the responsibility of differentiating tuples and tuple proxies
  19970. has been the job of the interpreter.
  19971. %
  19972. \racket{For example, the interpreter for \LangCast{} implements
  19973. \code{vector-ref} using the \code{guarded-vector-ref} function shown in
  19974. figure~\ref{fig:guarded-tuple}.}
  19975. %
  19976. In the \code{differentiate\_proxies} pass we shift this responsibility
  19977. to the generated code.
  19978. We begin by designing the output language \LangPVec{}. In \LangGrad{}
  19979. we used the type \TUPLETYPENAME{} for both
  19980. real tuples and tuple proxies.
  19981. \python{Similarly, we use the type \code{list} for both arrays and
  19982. array proxies.}
  19983. In \LangPVec{} we return the
  19984. \TUPLETYPENAME{} type to its original
  19985. meaning, as the type of just tuples, and we introduce a new type,
  19986. \PTUPLETYNAME{}, whose values
  19987. can be either real tuples or tuple
  19988. proxies.
  19989. %
  19990. {\if\edition\pythonEd\pythonColor
  19991. Likewise, we return the
  19992. \ARRAYTYPENAME{} type to its original
  19993. meaning, as the type of arrays, and we introduce a new type,
  19994. \PARRAYTYNAME{}, whose values
  19995. can be either arrays or array proxies.
  19996. These new types come with a suite of new primitive operations.
  19997. \fi}
  19998. {\if\edition\racketEd
  19999. A tuple proxy is represented by a tuple containing three things: (1) the
  20000. underlying tuple, (2) a tuple of functions for casting elements that
  20001. are read from the tuple, and (3) a tuple of functions for casting
  20002. values to be written to the tuple. So, we define the following
  20003. abbreviation for the type of a tuple proxy:
  20004. \[
  20005. \itm{TupleProxy} (T\ldots \Rightarrow T'\ldots)
  20006. = (\ttm{Vector}~\PTUPLETY{T\ldots} ~R~ W)
  20007. \]
  20008. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  20009. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  20010. %
  20011. Next we describe each of the new primitive operations.
  20012. \begin{description}
  20013. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  20014. (\key{PVector} $T \ldots$)]\ \\
  20015. %
  20016. This operation brands a vector as a value of the \code{PVector} type.
  20017. \item[\code{inject-proxy} : $\itm{TupleProxy}(T\ldots \Rightarrow T'\ldots)$
  20018. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  20019. %
  20020. This operation brands a vector proxy as value of the \code{PVector} type.
  20021. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  20022. \BOOLTY{}] \ \\
  20023. %
  20024. This returns true if the value is a tuple proxy and false if it is a
  20025. real tuple.
  20026. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  20027. (\key{Vector} $T \ldots$)]\ \\
  20028. %
  20029. Assuming that the input is a tuple, this operation returns the
  20030. tuple.
  20031. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  20032. $\to$ \INTTY{}]\ \\
  20033. %
  20034. Given a tuple proxy, this operation returns the length of the tuple.
  20035. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  20036. $\to$ ($i$ : \INTTY{}) $\to$ $T_i$]\ \\
  20037. %
  20038. Given a tuple proxy, this operation returns the $i$th element of the
  20039. tuple.
  20040. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  20041. : \INTTY{}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  20042. Given a tuple proxy, this operation writes a value to the $i$th element
  20043. of the tuple.
  20044. \end{description}
  20045. \fi}
  20046. {\if\edition\pythonEd\pythonColor
  20047. %
  20048. A tuple proxy is represented by a tuple containing (1) the underlying
  20049. tuple and (2) a tuple of functions for casting elements that are read
  20050. from the tuple. The \LangPVec{} language includes the following AST
  20051. classes and primitive functions.
  20052. \begin{description}
  20053. \item[\code{InjectTuple}] \ \\
  20054. %
  20055. This AST node brands a tuple as a value of the \PTUPLETYNAME{} type.
  20056. \item[\code{InjectTupleProxy}]\ \\
  20057. %
  20058. This AST node brands a tuple proxy as value of the \PTUPLETYNAME{} type.
  20059. \item[\code{is\_tuple\_proxy}]\ \\
  20060. %
  20061. This primitive returns true if the value is a tuple proxy and false
  20062. if it is a tuple.
  20063. \item[\code{project\_tuple}]\ \\
  20064. %
  20065. Converts a tuple that is branded as \PTUPLETYNAME{}
  20066. back to a tuple.
  20067. \item[\code{proxy\_tuple\_len}]\ \\
  20068. %
  20069. Given a tuple proxy, returns the length of the underlying tuple.
  20070. \item[\code{proxy\_tuple\_load}]\ \\
  20071. %
  20072. Given a tuple proxy, returns the $i$th element of the underlying
  20073. tuple.
  20074. \end{description}
  20075. An array proxy is represented by a tuple containing (1) the underlying
  20076. array, (2) a function for casting elements that are read from the
  20077. array, and (3) a function for casting elements that are written to the
  20078. array. The \LangPVec{} language includes the following AST classes
  20079. and primitive functions.
  20080. \begin{description}
  20081. \item[\code{InjectList}]\ \\
  20082. This AST node brands an array as a value of the \PARRAYTYNAME{} type.
  20083. \item[\code{InjectListProxy}]\ \\
  20084. %
  20085. This AST node brands an array proxy as a value of the \PARRAYTYNAME{} type.
  20086. \item[\code{is\_array\_proxy}]\ \\
  20087. %
  20088. Returns true if the value is an array proxy and false if it is an
  20089. array.
  20090. \item[\code{project\_array}]\ \\
  20091. %
  20092. Converts an array that is branded as \PARRAYTYNAME{} back to an
  20093. array.
  20094. \item[\code{proxy\_array\_len}]\ \\
  20095. %
  20096. Given an array proxy, returns the length of the underlying array.
  20097. \item[\code{proxy\_array\_load}]\ \\
  20098. %
  20099. Given an array proxy, returns the $i$th element of the underlying
  20100. array.
  20101. \item[\code{proxy\_array\_store}]\ \\
  20102. %
  20103. Given an array proxy, writes a value to the $i$th element of the
  20104. underlying array.
  20105. \end{description}
  20106. \fi}
  20107. Now we discuss the translation that differentiates tuples and arrays
  20108. from proxies. First, every type annotation in the program is
  20109. translated (recursively) to replace \TUPLETYPENAME{} with \PTUPLETYNAME{}.
  20110. Next, we insert uses of \PTUPLETYNAME{} operations in the appropriate
  20111. places. For example, we wrap every tuple creation with an
  20112. \racket{\code{inject-vector}}\python{\code{InjectTuple}}.
  20113. %
  20114. {\if\edition\racketEd
  20115. \begin{minipage}{0.96\textwidth}
  20116. \begin{lstlisting}
  20117. (vector |$e_1 \ldots e_n$|)
  20118. |$\Rightarrow$|
  20119. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  20120. \end{lstlisting}
  20121. \end{minipage}
  20122. \fi}
  20123. {\if\edition\pythonEd\pythonColor
  20124. \begin{lstlisting}
  20125. Tuple(|$e_1, \ldots, e_n$|)
  20126. |$\Rightarrow$|
  20127. InjectTuple(Tuple(|$e'_1, \ldots, e'_n$|))
  20128. \end{lstlisting}
  20129. \fi}
  20130. The \racket{\code{raw-vector}}\python{\code{RawTuple}}
  20131. AST node that we introduced in the previous
  20132. section does not get injected.
  20133. {\if\edition\racketEd
  20134. \begin{lstlisting}
  20135. (raw-vector |$e_1 \ldots e_n$|)
  20136. |$\Rightarrow$|
  20137. (vector |$e'_1 \ldots e'_n$|)
  20138. \end{lstlisting}
  20139. \fi}
  20140. {\if\edition\pythonEd\pythonColor
  20141. \begin{lstlisting}
  20142. RawTuple(|$e_1, \ldots, e_n$|)
  20143. |$\Rightarrow$|
  20144. Tuple(|$e'_1, \ldots, e'_n$|)
  20145. \end{lstlisting}
  20146. \fi}
  20147. The \racket{\code{vector-proxy}}\python{\code{TupleProxy}} AST
  20148. translates as follows:
  20149. %
  20150. {\if\edition\racketEd
  20151. \begin{lstlisting}
  20152. (vector-proxy |$e_1~e_2~e_3$|)
  20153. |$\Rightarrow$|
  20154. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  20155. \end{lstlisting}
  20156. \fi}
  20157. {\if\edition\pythonEd\pythonColor
  20158. \begin{lstlisting}
  20159. TupleProxy(|$e_1, e_2, T_1, T_2$|)
  20160. |$\Rightarrow$|
  20161. InjectTupleProxy(Tuple(|$e'_1,e'_2, T'_1, T'_2$|))
  20162. \end{lstlisting}
  20163. \fi}
  20164. We translate the element access operations into conditional
  20165. expressions that check whether the value is a proxy and then dispatch
  20166. to either the appropriate proxy tuple operation or the regular tuple
  20167. operation.
  20168. {\if\edition\racketEd
  20169. \begin{lstlisting}
  20170. (vector-ref |$e_1$| |$i$|)
  20171. |$\Rightarrow$|
  20172. (let ([|$v~e_1$|])
  20173. (if (proxy? |$v$|)
  20174. (proxy-vector-ref |$v$| |$i$|)
  20175. (vector-ref (project-vector |$v$|) |$i$|)
  20176. \end{lstlisting}
  20177. \fi}
  20178. %
  20179. Note that in the branch for a tuple, we must apply
  20180. \racket{\code{project-vector}}\python{\code{project\_tuple}} before reading
  20181. from the tuple.
  20182. The translation of array operations is similar to the ones for tuples.
  20183. \section{Reveal Casts }
  20184. \label{sec:reveal-casts-gradual}
  20185. {\if\edition\racketEd
  20186. Recall that the \code{reveal\_casts} pass
  20187. (section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  20188. \code{Inject} and \code{Project} into lower-level operations.
  20189. %
  20190. In particular, \code{Project} turns into a conditional expression that
  20191. inspects the tag and retrieves the underlying value. Here we need to
  20192. augment the translation of \code{Project} to handle the situation in which
  20193. the target type is \code{PVector}. Instead of using
  20194. \code{vector-length} we need to use \code{proxy-vector-length}.
  20195. \begin{lstlisting}
  20196. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  20197. |$\Rightarrow$|
  20198. (let |$\itm{tmp}$| |$e'$|
  20199. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  20200. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  20201. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  20202. (exit)))
  20203. \end{lstlisting}
  20204. \fi}
  20205. %
  20206. {\if\edition\pythonEd\pythonColor
  20207. Recall that the $\itm{tagof}$ function determines the bits used to
  20208. identify values of different types, and it is used in the \code{reveal\_casts}
  20209. pass in the translation of \code{Project}. The \PTUPLETYNAME{} and
  20210. \PARRAYTYNAME{} types can be mapped to $010$ in binary ($2$ in
  20211. decimal), just like the tuple and array types.
  20212. \fi}
  20213. %
  20214. Otherwise, the only other changes are adding cases that copy the new AST nodes.
  20215. \pagebreak
  20216. \section{Closure Conversion }
  20217. \label{sec:closure-conversion-gradual}
  20218. The auxiliary function that translates type annotations needs to be
  20219. updated to handle the \PTUPLETYNAME{}
  20220. \racket{type}\python{and \PARRAYTYNAME{} types}.
  20221. %
  20222. Otherwise, the only other changes are adding cases that copy the new
  20223. AST nodes.
  20224. \section{Select Instructions }
  20225. \label{sec:select-instructions-gradual}
  20226. \index{subject}{select instructions}
  20227. Recall that the \code{select\_instructions} pass is responsible for
  20228. lowering the primitive operations into x86 instructions. So, we need
  20229. to translate the new operations on \PTUPLETYNAME{} \python{and \PARRAYTYNAME{}}
  20230. to x86. To do so, the first question we need to answer is how to
  20231. differentiate between tuple and tuple proxies\python{, and likewise for
  20232. arrays and array proxies}. We need just one bit to accomplish this;
  20233. we use the bit in position $63$ of the 64-bit tag at the front of
  20234. every tuple (see figure~\ref{fig:tuple-rep})\python{ or array
  20235. (section~\ref{sec:array-rep})}. So far, this bit has been set to $0$,
  20236. so for \racket{\code{inject-vector}}\python{\code{InjectTuple}} we leave
  20237. it that way.
  20238. {\if\edition\racketEd
  20239. \begin{lstlisting}
  20240. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  20241. |$\Rightarrow$|
  20242. movq |$e'_1$|, |$\itm{lhs'}$|
  20243. \end{lstlisting}
  20244. \fi}
  20245. {\if\edition\pythonEd\pythonColor
  20246. \begin{lstlisting}
  20247. Assign([|$\itm{lhs}$|], InjectTuple(|$e_1$|))
  20248. |$\Rightarrow$|
  20249. movq |$e'_1$|, |$\itm{lhs'}$|
  20250. \end{lstlisting}
  20251. \fi}
  20252. \python{The translation for \code{InjectList} is also a move instruction.}
  20253. \noindent On the other hand,
  20254. \racket{\code{inject-proxy}}\python{\code{InjectTupleProxy}} sets bit
  20255. $63$ to $1$.
  20256. %
  20257. {\if\edition\racketEd
  20258. \begin{lstlisting}
  20259. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  20260. |$\Rightarrow$|
  20261. movq |$e'_1$|, %r11
  20262. movq |$(1 << 63)$|, %rax
  20263. orq 0(%r11), %rax
  20264. movq %rax, 0(%r11)
  20265. movq %r11, |$\itm{lhs'}$|
  20266. \end{lstlisting}
  20267. \fi}
  20268. {\if\edition\pythonEd\pythonColor
  20269. \begin{lstlisting}
  20270. Assign([|$\itm{lhs}$|], InjectTupleProxy(|$e_1$|))
  20271. |$\Rightarrow$|
  20272. movq |$e'_1$|, %r11
  20273. movq |$(1 << 63)$|, %rax
  20274. orq 0(%r11), %rax
  20275. movq %rax, 0(%r11)
  20276. movq %r11, |$\itm{lhs'}$|
  20277. \end{lstlisting}
  20278. \fi}
  20279. \python{\noindent The translation for \code{InjectListProxy} should set bit $63$
  20280. of the tag and also bit $62$, to differentiate between arrays and tuples.}
  20281. The \racket{\code{proxy?} operation consumes}%
  20282. \python{\code{is\_tuple\_proxy} and \code{is\_array\_proxy} operations
  20283. consume}
  20284. the information so carefully stashed away by the injections. It
  20285. isolates bit $63$ to tell whether the value is a proxy.
  20286. %
  20287. {\if\edition\racketEd
  20288. \begin{lstlisting}
  20289. (Assign |$\itm{lhs}$| (Prim 'proxy? (list |$e_1$|)))
  20290. |$\Rightarrow$|
  20291. movq |$e_1'$|, %r11
  20292. movq 0(%r11), %rax
  20293. sarq $63, %rax
  20294. andq $1, %rax
  20295. movq %rax, |$\itm{lhs'}$|
  20296. \end{lstlisting}
  20297. \fi}%
  20298. %
  20299. {\if\edition\pythonEd\pythonColor
  20300. \begin{lstlisting}
  20301. Assign([|$\itm{lhs}$|], Call(Name('is_tuple_proxy'), [|$e_1$|]))
  20302. |$\Rightarrow$|
  20303. movq |$e_1'$|, %r11
  20304. movq 0(%r11), %rax
  20305. sarq $63, %rax
  20306. andq $1, %rax
  20307. movq %rax, |$\itm{lhs'}$|
  20308. \end{lstlisting}
  20309. \fi}%
  20310. %
  20311. The \racket{\code{project-vector} operation is}
  20312. \python{\code{project\_tuple} and \code{project\_array} operations are}
  20313. straightforward to translate, so we leave that to the reader.
  20314. Regarding the element access operations for tuples\python{ and arrays}, the
  20315. runtime provides procedures that implement them (they are recursive
  20316. functions!), so here we simply need to translate these tuple
  20317. operations into the appropriate function call. For example, here is
  20318. the translation for
  20319. \racket{\code{proxy-vector-ref}}\python{\code{proxy\_tuple\_load}}.
  20320. {\if\edition\racketEd
  20321. \begin{minipage}{0.96\textwidth}
  20322. \begin{lstlisting}
  20323. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  20324. |$\Rightarrow$|
  20325. movq |$e_1'$|, %rdi
  20326. movq |$e_2'$|, %rsi
  20327. callq proxy_vector_ref
  20328. movq %rax, |$\itm{lhs'}$|
  20329. \end{lstlisting}
  20330. \end{minipage}
  20331. \fi}
  20332. {\if\edition\pythonEd\pythonColor
  20333. \begin{lstlisting}
  20334. Assign([|$\itm{lhs}$|], Call(Name('proxy_tuple_load'), [|$e_1$|, |$e_2$|]))
  20335. |$\Rightarrow$|
  20336. movq |$e_1'$|, %rdi
  20337. movq |$e_2'$|, %rsi
  20338. callq proxy_vector_ref
  20339. movq %rax, |$\itm{lhs'}$|
  20340. \end{lstlisting}
  20341. \fi}
  20342. {\if\edition\pythonEd\pythonColor
  20343. % TODO: revisit the names vecof for python -Jeremy
  20344. We translate
  20345. \code{proxy\_array\_load} to \code{proxy\_vecof\_ref},
  20346. \code{proxy\_array\_store} to \code{proxy\_vecof\_set}, and
  20347. \code{proxy\_array\_len} to \code{proxy\_vecof\_length}.
  20348. \fi}
  20349. We have another batch of operations to deal with: those for the
  20350. \CANYTY{} type. Recall that we generate an
  20351. \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}} when
  20352. there is a element access on something of type \CANYTY{}, and
  20353. similarly for
  20354. \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}} and
  20355. \racket{\code{any-vector-length}}\python{\code{any\_len}}. In
  20356. section~\ref{sec:select-Lany} we selected instructions for these
  20357. operations on the basis of the idea that the underlying value was a tuple or
  20358. array. But in the current setting, the underlying value is of type
  20359. \PTUPLETYNAME{}\python{ or \PARRAYTYNAME{}}. We have added three runtime
  20360. functions to deal with this:
  20361. \code{proxy\_vector\_ref},
  20362. \code{proxy\_vector\_set}, and
  20363. \code{proxy\_vector\_length} that inspect bit $62$ of the tag
  20364. to determine whether the value is a proxy, and then
  20365. dispatches to the the appropriate code.
  20366. %
  20367. So \racket{\code{any-vector-ref}}\python{\code{any\_load\_unsafe}}
  20368. can be translated as follows.
  20369. We begin by projecting the underlying value out of the tagged value and
  20370. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  20371. {\if\edition\racketEd
  20372. \begin{lstlisting}
  20373. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  20374. |$\Rightarrow$|
  20375. movq |$\neg 111$|, %rdi
  20376. andq |$e_1'$|, %rdi
  20377. movq |$e_2'$|, %rsi
  20378. callq proxy_vector_ref
  20379. movq %rax, |$\itm{lhs'}$|
  20380. \end{lstlisting}
  20381. \fi}
  20382. {\if\edition\pythonEd\pythonColor
  20383. \begin{lstlisting}
  20384. Assign([|$\itm{lhs}$|], Call(Name('any_load_unsafe'), [|$e_1$|, |$e_2$|]))
  20385. |$\Rightarrow$|
  20386. movq |$\neg 111$|, %rdi
  20387. andq |$e_1'$|, %rdi
  20388. movq |$e_2'$|, %rsi
  20389. callq proxy_vector_ref
  20390. movq %rax, |$\itm{lhs'}$|
  20391. \end{lstlisting}
  20392. \fi}
  20393. \noindent The \racket{\code{any-vector-set!}}\python{\code{any\_store\_unsafe}}
  20394. and \racket{\code{any-vector-length}}\python{\code{any\_len}} operators
  20395. are translated in a similar way. Alternatively, you could generate
  20396. instructions to open-code
  20397. the \code{proxy\_vector\_ref}, \code{proxy\_vector\_set},
  20398. and \code{proxy\_vector\_length} functions.
  20399. \begin{exercise}\normalfont\normalsize
  20400. Implement a compiler for the gradually typed \LangGrad{} language by
  20401. extending and adapting your compiler for \LangLam{}. Create ten new
  20402. partially typed test programs. In addition to testing with these
  20403. new programs, test your compiler on all the tests for \LangLam{}
  20404. and for \LangDyn{}.
  20405. %
  20406. \racket{Sometimes you may get a type-checking error on the
  20407. \LangDyn{} programs, but you can adapt them by inserting a cast to
  20408. the \CANYTY{} type around each subexpression that has caused a type
  20409. error. Although \LangDyn{} does not have explicit casts, you can
  20410. induce one by wrapping the subexpression \code{e} with a call to
  20411. an unannotated identity function, as follows: \code{((lambda (x) x) e)}.}
  20412. %
  20413. \python{Sometimes you may get a type-checking error on the
  20414. \LangDyn{} programs, but you can adapt them by inserting a
  20415. temporary variable of type \CANYTY{} that is initialized with the
  20416. troublesome expression.}
  20417. \end{exercise}
  20418. \begin{figure}[t]
  20419. \begin{tcolorbox}[colback=white]
  20420. {\if\edition\racketEd
  20421. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  20422. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20423. \node (Lgradual2) at (4,4) {\large \LangCast{}};
  20424. \node (Lgradual3) at (8,4) {\large \LangProxy{}};
  20425. \node (Lgradual4) at (12,4) {\large \LangPVec{}};
  20426. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20427. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20428. \node (Llambdapp) at (4,2) {\large \LangPVecFunRef{}};
  20429. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20430. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20431. %\node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20432. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20433. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20434. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  20435. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20436. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20437. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20438. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20439. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  20440. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  20441. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20442. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20443. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  20444. \path[->,bend left=15] (Lgradual) edge [above] node
  20445. {\ttfamily\footnotesize cast\_insert} (Lgradual2);
  20446. \path[->,bend left=15] (Lgradual2) edge [above] node
  20447. {\ttfamily\footnotesize lower\_casts} (Lgradual3);
  20448. \path[->,bend left=15] (Lgradual3) edge [above] node
  20449. {\ttfamily\footnotesize differentiate\_proxies} (Lgradual4);
  20450. \path[->,bend left=15] (Lgradual4) edge [left] node
  20451. {\ttfamily\footnotesize shrink} (Lgradualr);
  20452. \path[->,bend left=15] (Lgradualr) edge [above] node
  20453. {\ttfamily\footnotesize uniquify} (Lgradualp);
  20454. \path[->,bend right=15] (Lgradualp) edge [above] node
  20455. {\ttfamily\footnotesize reveal\_functions} (Llambdapp);
  20456. %% \path[->,bend left=15] (Llambdaproxy-4) edge [left] node
  20457. %% {\ttfamily\footnotesize resolve} (Lgradualr);
  20458. \path[->,bend right=15] (Llambdapp) edge [above] node
  20459. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-4);
  20460. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20461. {\ttfamily\footnotesize convert\_assignments} (Llambdaproxy-5);
  20462. \path[->,bend right=10] (Llambdaproxy-5) edge [above] node
  20463. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20464. \path[->,bend left=15] (F1-2) edge [above] node
  20465. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20466. \path[->,bend left=15] (F1-3) edge [left] node
  20467. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  20468. \path[->,bend left=15] (F1-4) edge [below] node
  20469. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  20470. \path[->,bend right=15] (F1-5) edge [above] node
  20471. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20472. \path[->,bend right=15] (F1-6) edge [above] node
  20473. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20474. \path[->,bend right=15] (C3-2) edge [right] node
  20475. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20476. \path[->,bend right=15] (x86-2) edge [right] node
  20477. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  20478. \path[->,bend right=15] (x86-2-1) edge [below] node
  20479. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  20480. \path[->,bend right=15] (x86-2-2) edge [right] node
  20481. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  20482. \path[->,bend left=15] (x86-3) edge [above] node
  20483. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20484. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20485. \end{tikzpicture}
  20486. \fi}
  20487. {\if\edition\pythonEd\pythonColor
  20488. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.80]
  20489. \node (Lgradual) at (0,4) {\large \LangGrad{}};
  20490. \node (Lgradual2) at (4,4) {\large \LangGrad{}};
  20491. \node (Lgradual3) at (8,4) {\large \LangCast{}};
  20492. \node (Lgradual4) at (12,4) {\large \LangProxy{}};
  20493. \node (Lgradualr) at (12,2) {\large \LangPVec{}};
  20494. \node (Lgradualp) at (8,2) {\large \LangPVec{}};
  20495. \node (Llambdapp) at (4,2) {\large \LangPVec{}};
  20496. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  20497. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  20498. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  20499. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  20500. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  20501. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  20502. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  20503. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  20504. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  20505. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  20506. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  20507. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  20508. \path[->,bend left=15] (Lgradual) edge [above] node
  20509. {\ttfamily\footnotesize shrink} (Lgradual2);
  20510. \path[->,bend left=15] (Lgradual2) edge [above] node
  20511. {\ttfamily\footnotesize uniquify} (Lgradual3);
  20512. \path[->,bend left=15] (Lgradual3) edge [above] node
  20513. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  20514. \path[->,bend left=15] (Lgradual4) edge [left] node
  20515. {\ttfamily\footnotesize resolve} (Lgradualr);
  20516. \path[->,bend left=15] (Lgradualr) edge [below] node
  20517. {\ttfamily\footnotesize cast\_insert} (Lgradualp);
  20518. \path[->,bend right=15] (Lgradualp) edge [above] node
  20519. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  20520. \path[->,bend right=15] (Llambdapp) edge [above] node
  20521. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  20522. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  20523. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  20524. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  20525. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  20526. \path[->,bend left=15] (F1-1) edge [above] node
  20527. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  20528. \path[->,bend left=15] (F1-2) edge [above] node
  20529. {\ttfamily\footnotesize limit\_functions} (F1-3);
  20530. \path[->,bend left=15] (F1-3) edge [right] node
  20531. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  20532. \path[->,bend right=15] (F1-5) edge [above] node
  20533. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  20534. \path[->,bend right=15] (F1-6) edge [above] node
  20535. {\ttfamily\footnotesize explicate\_control} (C3-2);
  20536. \path[->,bend right=15] (C3-2) edge [right] node
  20537. {\ttfamily\footnotesize select\_instructions} (x86-2);
  20538. \path[->,bend right=15] (x86-2) edge [below] node
  20539. {\ttfamily\footnotesize assign\_homes} (x86-3);
  20540. \path[->,bend right=15] (x86-3) edge [below] node
  20541. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  20542. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  20543. \end{tikzpicture}
  20544. \fi}
  20545. \end{tcolorbox}
  20546. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  20547. \label{fig:Lgradual-passes}
  20548. \end{figure}
  20549. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  20550. needed for the compilation of \LangGrad{}.
  20551. \section{Further Reading}
  20552. This chapter just scratches the surface of gradual typing. The basic
  20553. approach described here is missing two key ingredients that one would
  20554. want in an implementation of gradual typing: blame
  20555. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  20556. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  20557. problem addressed by blame tracking is that when a cast on a
  20558. higher-order value fails, it often does so at a point in the program
  20559. that is far removed from the original cast. Blame tracking is a
  20560. technique for propagating extra information through casts and proxies
  20561. so that when a cast fails, the error message can point back to the
  20562. original location of the cast in the source program.
  20563. The problem addressed by space-efficient casts also relates to
  20564. higher-order casts. It turns out that in partially typed programs, a
  20565. function or tuple can flow through a great many casts at runtime. With
  20566. the approach described in this chapter, each cast adds another
  20567. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  20568. considerable space, but it also makes the function calls and tuple
  20569. operations slow. For example, a partially typed version of quicksort
  20570. could, in the worst case, build a chain of proxies of length $O(n)$
  20571. around the tuple, changing the overall time complexity of the
  20572. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  20573. solution to this problem by representing casts using the coercion
  20574. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  20575. long chains of proxies by compressing them into a concise normal
  20576. form. \citet{Siek:2015ab} give an algorithm for compressing coercions,
  20577. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  20578. the Grift compiler:
  20579. \begin{center}
  20580. \url{https://github.com/Gradual-Typing/Grift}
  20581. \end{center}
  20582. There are also interesting interactions between gradual typing and
  20583. other language features, such as generics, information-flow types, and
  20584. type inference, to name a few. We recommend to the reader the
  20585. online gradual typing bibliography for more material:
  20586. \begin{center}
  20587. \url{http://samth.github.io/gradual-typing-bib/}
  20588. \end{center}
  20589. % TODO: challenge problem:
  20590. % type analysis and type specialization?
  20591. % coercions?
  20592. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  20593. \chapter{Generics}
  20594. \label{ch:Lpoly}
  20595. \setcounter{footnote}{0}
  20596. This chapter studies the compilation of
  20597. generics\index{subject}{generics} (aka parametric
  20598. polymorphism\index{subject}{parametric polymorphism}), compiling the
  20599. \LangPoly{} subset of \racket{Typed Racket}\python{Python}. Generics
  20600. enable programmers to make code more reusable by parameterizing
  20601. functions and data structures with respect to the types on which they
  20602. operate. For example, figure~\ref{fig:map-poly} revisits the
  20603. \code{map} example and this time gives it a more fitting type. This
  20604. \code{map} function is parameterized with respect to the element type
  20605. of the tuple. The type of \code{map} is the following generic type
  20606. specified by the \code{All} type with parameter \code{T}:
  20607. {\if\edition\racketEd
  20608. \begin{lstlisting}
  20609. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  20610. \end{lstlisting}
  20611. \fi}
  20612. {\if\edition\pythonEd\pythonColor
  20613. \begin{lstlisting}
  20614. All[[T], Callable[[Callable[[T],T], tuple[T,T]], tuple[T,T]]]
  20615. \end{lstlisting}
  20616. \fi}
  20617. %
  20618. The idea is that \code{map} can be used at \emph{all} choices of a
  20619. type for parameter \code{T}. In the example shown in
  20620. figure~\ref{fig:map-poly} we apply \code{map} to a tuple of integers,
  20621. implicitly choosing \racket{\code{Integer}}\python{\code{int}} for
  20622. \code{T}, but we could have just as well applied \code{map} to a tuple
  20623. of Booleans.
  20624. %
  20625. A \emph{monomorphic} function is simply one that is not generic.
  20626. %
  20627. We use the term \emph{instantiation} for the process (within the
  20628. language implementation) of turning a generic function into a
  20629. monomorphic one, where the type parameters have been replaced by
  20630. types.
  20631. {\if\edition\pythonEd\pythonColor
  20632. %
  20633. In Python, when writing a generic function such as \code{map}, one
  20634. does not explicitly write its generic type (using \code{All}).
  20635. Instead, that the function is generic is implied by the use of type
  20636. variables (such as \code{T}) in the type annotations of its
  20637. parameters.
  20638. %
  20639. \fi}
  20640. \begin{figure}[tbp]
  20641. % poly_test_2.rkt
  20642. \begin{tcolorbox}[colback=white]
  20643. {\if\edition\racketEd
  20644. \begin{lstlisting}
  20645. (: map (All (T) ((T -> T) (Vector T T) -> (Vector T T))))
  20646. (define (map f v)
  20647. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  20648. (define (inc [x : Integer]) : Integer (+ x 1))
  20649. (vector-ref (map inc (vector 0 41)) 1)
  20650. \end{lstlisting}
  20651. \fi}
  20652. {\if\edition\pythonEd\pythonColor
  20653. \begin{lstlisting}
  20654. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  20655. return (f(tup[0]), f(tup[1]))
  20656. def add1(x : int) -> int:
  20657. return x + 1
  20658. t = map(add1, (0, 41))
  20659. print(t[1])
  20660. \end{lstlisting}
  20661. \fi}
  20662. \end{tcolorbox}
  20663. \caption{A generic version of the \code{map} function.}
  20664. \label{fig:map-poly}
  20665. \end{figure}
  20666. Figure~\ref{fig:Lpoly-concrete-syntax} presents the definition of the
  20667. concrete syntax of \LangPoly{}, and figure~\ref{fig:Lpoly-syntax}
  20668. shows the definition of the abstract syntax.
  20669. %
  20670. {\if\edition\racketEd
  20671. We add a second form for function definitions in which a type
  20672. declaration comes before the \code{define}. In the abstract syntax,
  20673. the return type in the \code{Def} is \CANYTY{}, but that should be
  20674. ignored in favor of the return type in the type declaration. (The
  20675. \CANYTY{} comes from using the same parser as discussed in
  20676. chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  20677. enables the use of an \code{All} type for a function, thereby making
  20678. it generic.
  20679. \fi}
  20680. %
  20681. The grammar for types is extended to include the type of a generic
  20682. (\code{All}) and type variables\python{\ (\code{GenericVar} in the
  20683. abstract syntax)}.
  20684. \newcommand{\LpolyGrammarRacket}{
  20685. \begin{array}{lcl}
  20686. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20687. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  20688. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  20689. \end{array}
  20690. }
  20691. \newcommand{\LpolyASTRacket}{
  20692. \begin{array}{lcl}
  20693. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  20694. \Def &::=& \DECL{\Var}{\Type} \\
  20695. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  20696. \end{array}
  20697. }
  20698. \newcommand{\LpolyGrammarPython}{
  20699. \begin{array}{lcl}
  20700. \Type &::=& \key{All}\LS \LS\Var\ldots\RS,\Type\RS \MID \Var
  20701. \end{array}
  20702. }
  20703. \newcommand{\LpolyASTPython}{
  20704. \begin{array}{lcl}
  20705. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP
  20706. \MID \key{GenericVar}\LP\Var\RP
  20707. \end{array}
  20708. }
  20709. \begin{figure}[tp]
  20710. \centering
  20711. \begin{tcolorbox}[colback=white]
  20712. \footnotesize
  20713. {\if\edition\racketEd
  20714. \[
  20715. \begin{array}{l}
  20716. \gray{\LintGrammarRacket{}} \\ \hline
  20717. \gray{\LvarGrammarRacket{}} \\ \hline
  20718. \gray{\LifGrammarRacket{}} \\ \hline
  20719. \gray{\LwhileGrammarRacket} \\ \hline
  20720. \gray{\LtupGrammarRacket} \\ \hline
  20721. \gray{\LfunGrammarRacket} \\ \hline
  20722. \gray{\LlambdaGrammarRacket} \\ \hline
  20723. \LpolyGrammarRacket \\
  20724. \begin{array}{lcl}
  20725. \LangPoly{} &::=& \Def \ldots ~ \Exp
  20726. \end{array}
  20727. \end{array}
  20728. \]
  20729. \fi}
  20730. {\if\edition\pythonEd\pythonColor
  20731. \[
  20732. \begin{array}{l}
  20733. \gray{\LintGrammarPython{}} \\ \hline
  20734. \gray{\LvarGrammarPython{}} \\ \hline
  20735. \gray{\LifGrammarPython{}} \\ \hline
  20736. \gray{\LwhileGrammarPython} \\ \hline
  20737. \gray{\LtupGrammarPython} \\ \hline
  20738. \gray{\LfunGrammarPython} \\ \hline
  20739. \gray{\LlambdaGrammarPython} \\\hline
  20740. \LpolyGrammarPython \\
  20741. \begin{array}{lcl}
  20742. \LangPoly{} &::=& \Def\ldots \Stmt\ldots
  20743. \end{array}
  20744. \end{array}
  20745. \]
  20746. \fi}
  20747. \end{tcolorbox}
  20748. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  20749. (figure~\ref{fig:Llam-concrete-syntax}).}
  20750. \label{fig:Lpoly-concrete-syntax}
  20751. \end{figure}
  20752. \begin{figure}[tp]
  20753. \centering
  20754. \begin{tcolorbox}[colback=white]
  20755. \footnotesize
  20756. {\if\edition\racketEd
  20757. \[
  20758. \begin{array}{l}
  20759. \gray{\LintOpAST} \\ \hline
  20760. \gray{\LvarASTRacket{}} \\ \hline
  20761. \gray{\LifASTRacket{}} \\ \hline
  20762. \gray{\LwhileASTRacket{}} \\ \hline
  20763. \gray{\LtupASTRacket{}} \\ \hline
  20764. \gray{\LfunASTRacket} \\ \hline
  20765. \gray{\LlambdaASTRacket} \\ \hline
  20766. \LpolyASTRacket \\
  20767. \begin{array}{lcl}
  20768. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  20769. \end{array}
  20770. \end{array}
  20771. \]
  20772. \fi}
  20773. {\if\edition\pythonEd\pythonColor
  20774. \[
  20775. \begin{array}{l}
  20776. \gray{\LintASTPython} \\ \hline
  20777. \gray{\LvarASTPython{}} \\ \hline
  20778. \gray{\LifASTPython{}} \\ \hline
  20779. \gray{\LwhileASTPython{}} \\ \hline
  20780. \gray{\LtupASTPython{}} \\ \hline
  20781. \gray{\LfunASTPython} \\ \hline
  20782. \gray{\LlambdaASTPython} \\ \hline
  20783. \LpolyASTPython \\
  20784. \begin{array}{lcl}
  20785. \LangPoly{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  20786. \end{array}
  20787. \end{array}
  20788. \]
  20789. \fi}
  20790. \end{tcolorbox}
  20791. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  20792. (figure~\ref{fig:Llam-syntax}).}
  20793. \label{fig:Lpoly-syntax}
  20794. \end{figure}
  20795. By including the \code{All} type in the $\Type$ nonterminal of the
  20796. grammar we choose to make generics first class, which has interesting
  20797. repercussions on the compiler.\footnote{The Python \code{typing} library does
  20798. not include syntax for the \code{All} type. It is inferred for functions whose
  20799. type annotations contain type variables.} Many languages with generics, such as
  20800. C++~\citep{stroustrup88:_param_types} and Standard
  20801. ML~\citep{Milner:1990fk}, support only second-class generics, so it
  20802. may be helpful to see an example of first-class generics in action. In
  20803. figure~\ref{fig:apply-twice} we define a function \code{apply\_twice}
  20804. whose parameter is a generic function. Indeed, because the grammar for
  20805. $\Type$ includes the \code{All} type, a generic function may also be
  20806. returned from a function or stored inside a tuple. The body of
  20807. \code{apply\_twice} applies the generic function \code{f} to a Boolean
  20808. and also to an integer, which would not be possible if \code{f} were
  20809. not generic.
  20810. \begin{figure}[tbp]
  20811. \begin{tcolorbox}[colback=white]
  20812. {\if\edition\racketEd
  20813. \begin{lstlisting}
  20814. (: apply_twice ((All (U) (U -> U)) -> Integer))
  20815. (define (apply_twice f)
  20816. (if (f #t) (f 42) (f 777)))
  20817. (: id (All (T) (T -> T)))
  20818. (define (id x) x)
  20819. (apply_twice id)
  20820. \end{lstlisting}
  20821. \fi}
  20822. {\if\edition\pythonEd\pythonColor
  20823. \begin{lstlisting}
  20824. def apply_twice(f : All[[U], Callable[[U],U]]) -> int:
  20825. if f(True):
  20826. return f(42)
  20827. else:
  20828. return f(777)
  20829. def id(x: T) -> T:
  20830. return x
  20831. print(apply_twice(id))
  20832. \end{lstlisting}
  20833. \fi}
  20834. \end{tcolorbox}
  20835. \caption{An example illustrating first-class generics.}
  20836. \label{fig:apply-twice}
  20837. \end{figure}
  20838. The type checker for \LangPoly{} shown in
  20839. figure~\ref{fig:type-check-Lpoly} has several new responsibilities
  20840. (compared to \LangLam{}) which we discuss in the following paragraphs.
  20841. {\if\edition\pythonEd\pythonColor
  20842. %
  20843. Regarding function definitions, if the type annotations on its
  20844. parameters contain generic variables, then the function is generic and
  20845. therefore its type is an \code{All} type wrapped around a function
  20846. type. Otherwise the function is monomorphic and its type is simply
  20847. a function type.
  20848. %
  20849. \fi}
  20850. The type checking of a function application is extended to handle the
  20851. case in which the operator expression is a generic function. In that case
  20852. the type arguments are deduced by matching the types of the parameters
  20853. with the types of the arguments.
  20854. %
  20855. The \code{match\_types} auxiliary function
  20856. (figure~\ref{fig:type-check-Lpoly-aux}) carries out this deduction by
  20857. recursively descending through a parameter type \code{param\_ty} and
  20858. the corresponding argument type \code{arg\_ty}, making sure that they
  20859. are equal except when there is a type parameter in the parameter
  20860. type. Upon encountering a type parameter for the first time, the
  20861. algorithm deduces an association of the type parameter to the
  20862. corresponding part of the argument type. If it is not the first time
  20863. that the type parameter has been encountered, the algorithm looks up
  20864. its deduced type and makes sure that it is equal to the corresponding
  20865. part of the argument type. The return type of the application is the
  20866. return type of the generic function with the type parameters
  20867. replaced by the deduced type arguments, using the
  20868. \code{substitute\_type} auxiliary function, which is also listed in
  20869. figure~\ref{fig:type-check-Lpoly-aux}.
  20870. The type checker extends type equality to handle the \code{All} type.
  20871. This is not quite as simple as for other types, such as function and
  20872. tuple types, because two \code{All} types can be syntactically
  20873. different even though they are equivalent. For example,
  20874. \begin{center}
  20875. \racket{\code{(All (T) (T -> T))}}\python{\code{All[[T], Callable[[T], T]]}}
  20876. \end{center}
  20877. is equivalent to
  20878. \begin{center}
  20879. \racket{\code{(All (U) (U -> U))}}\python{\code{All[[U], Callable[[U], U]]}}.
  20880. \end{center}
  20881. Two generic types are equal if they differ only in
  20882. the choice of the names of the type parameters. The definition of type
  20883. equality shown in figure~\ref{fig:type-check-Lpoly-aux} renames the type
  20884. parameters in one type to match the type parameters of the other type.
  20885. {\if\edition\racketEd
  20886. %
  20887. The type checker also ensures that only defined type variables appear
  20888. in type annotations. The \code{check\_well\_formed} function for which
  20889. the definition is shown in figure~\ref{fig:well-formed-types}
  20890. recursively inspects a type, making sure that each type variable has
  20891. been defined.
  20892. %
  20893. \fi}
  20894. \begin{figure}[tbp]
  20895. \begin{tcolorbox}[colback=white]
  20896. {\if\edition\racketEd
  20897. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  20898. (define type-check-poly-class
  20899. (class type-check-Llambda-class
  20900. (super-new)
  20901. (inherit check-type-equal?)
  20902. (define/override (type-check-apply env e1 es)
  20903. (define-values (e^ ty) ((type-check-exp env) e1))
  20904. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  20905. ((type-check-exp env) e)))
  20906. (match ty
  20907. [`(,ty^* ... -> ,rt)
  20908. (for ([arg-ty ty*] [param-ty ty^*])
  20909. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  20910. (values e^ es^ rt)]
  20911. [`(All ,xs (,tys ... -> ,rt))
  20912. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  20913. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  20914. (match_types env^^ param-ty arg-ty)))
  20915. (define targs
  20916. (for/list ([x xs])
  20917. (match (dict-ref env^^ x (lambda () #f))
  20918. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  20919. x (Apply e1 es))]
  20920. [ty ty])))
  20921. (values (Inst e^ ty targs) es^ (substitute_type env^^ rt))]
  20922. [else (error 'type-check "expected a function, not ~a" ty)]))
  20923. (define/override ((type-check-exp env) e)
  20924. (match e
  20925. [(Lambda `([,xs : ,Ts] ...) rT body)
  20926. (for ([T Ts]) ((check_well_formed env) T))
  20927. ((check_well_formed env) rT)
  20928. ((super type-check-exp env) e)]
  20929. [(HasType e1 ty)
  20930. ((check_well_formed env) ty)
  20931. ((super type-check-exp env) e)]
  20932. [else ((super type-check-exp env) e)]))
  20933. (define/override ((type-check-def env) d)
  20934. (verbose 'type-check "poly/def" d)
  20935. (match d
  20936. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  20937. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  20938. (for ([p ps]) ((check_well_formed ts-env) p))
  20939. ((check_well_formed ts-env) rt)
  20940. (define new-env (append ts-env (map cons xs ps) env))
  20941. (define-values (body^ ty^) ((type-check-exp new-env) body))
  20942. (check-type-equal? ty^ rt body)
  20943. (Generic ts (Def f p:t* rt info body^))]
  20944. [else ((super type-check-def env) d)]))
  20945. (define/override (type-check-program p)
  20946. (match p
  20947. [(Program info body)
  20948. (type-check-program (ProgramDefsExp info '() body))]
  20949. [(ProgramDefsExp info ds body)
  20950. (define ds^ (combine-decls-defs ds))
  20951. (define new-env (for/list ([d ds^])
  20952. (cons (def-name d) (fun-def-type d))))
  20953. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  20954. (define-values (body^ ty) ((type-check-exp new-env) body))
  20955. (check-type-equal? ty 'Integer body)
  20956. (ProgramDefsExp info ds^^ body^)]))
  20957. ))
  20958. \end{lstlisting}
  20959. \fi}
  20960. {\if\edition\pythonEd\pythonColor
  20961. \begin{lstlisting}[basicstyle=\ttfamily\small]
  20962. def type_check_exp(self, e, env):
  20963. match e:
  20964. case Call(Name(f), args) if f in builtin_functions:
  20965. return super().type_check_exp(e, env)
  20966. case Call(func, args):
  20967. func_t = self.type_check_exp(func, env)
  20968. func.has_type = func_t
  20969. match func_t:
  20970. case AllType(ps, FunctionType(p_tys, rt)):
  20971. for arg in args:
  20972. arg.has_type = self.type_check_exp(arg, env)
  20973. arg_tys = [arg.has_type for arg in args]
  20974. deduced = {}
  20975. for (p, a) in zip(p_tys, arg_tys):
  20976. self.match_types(p, a, deduced, e)
  20977. return self.substitute_type(rt, deduced)
  20978. case _:
  20979. return super().type_check_exp(e, env)
  20980. case _:
  20981. return super().type_check_exp(e, env)
  20982. def type_check(self, p):
  20983. match p:
  20984. case Module(body):
  20985. env = {}
  20986. for s in body:
  20987. match s:
  20988. case FunctionDef(name, params, bod, dl, returns, comment):
  20989. params_t = [t for (x,t) in params]
  20990. ty_params = set()
  20991. for t in params_t:
  20992. ty_params |$\mid$|= self.generic_variables(t)
  20993. ty = FunctionType(params_t, returns)
  20994. if len(ty_params) > 0:
  20995. ty = AllType(list(ty_params), ty)
  20996. env[name] = ty
  20997. self.check_stmts(body, IntType(), env)
  20998. case _:
  20999. raise Exception('type_check: unexpected ' + repr(p))
  21000. \end{lstlisting}
  21001. \fi}
  21002. \end{tcolorbox}
  21003. \caption{Type checker for the \LangPoly{} language.}
  21004. \label{fig:type-check-Lpoly}
  21005. \end{figure}
  21006. \begin{figure}[tbp]
  21007. \begin{tcolorbox}[colback=white]
  21008. {\if\edition\racketEd
  21009. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21010. (define/override (type-equal? t1 t2)
  21011. (match* (t1 t2)
  21012. [(`(All ,xs ,T1) `(All ,ys ,T2))
  21013. (define env (map cons xs ys))
  21014. (type-equal? (substitute_type env T1) T2)]
  21015. [(other wise)
  21016. (super type-equal? t1 t2)]))
  21017. (define/public (match_types env pt at)
  21018. (match* (pt at)
  21019. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  21020. [('Void 'Void) env] [('Any 'Any) env]
  21021. [(`(Vector ,pts ...) `(Vector ,ats ...))
  21022. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  21023. (match_types env^ pt1 at1))]
  21024. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  21025. (define env^ (match_types env prt art))
  21026. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  21027. (match_types env^^ pt1 at1))]
  21028. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  21029. (define env^ (append (map cons pxs axs) env))
  21030. (match_types env^ pt1 at1)]
  21031. [((? symbol? x) at)
  21032. (match (dict-ref env x (lambda () #f))
  21033. [#f (error 'type-check "undefined type variable ~a" x)]
  21034. ['Type (cons (cons x at) env)]
  21035. [t^ (check-type-equal? at t^ 'matching) env])]
  21036. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  21037. (define/public (substitute_type env pt)
  21038. (match pt
  21039. ['Integer 'Integer] ['Boolean 'Boolean]
  21040. ['Void 'Void] ['Any 'Any]
  21041. [`(Vector ,ts ...)
  21042. `(Vector ,@(for/list ([t ts]) (substitute_type env t)))]
  21043. [`(,ts ... -> ,rt)
  21044. `(,@(for/list ([t ts]) (substitute_type env t)) -> ,(substitute_type env rt))]
  21045. [`(All ,xs ,t)
  21046. `(All ,xs ,(substitute_type (append (map cons xs xs) env) t))]
  21047. [(? symbol? x) (dict-ref env x)]
  21048. [else (error 'type-check "expected a type not ~a" pt)]))
  21049. (define/public (combine-decls-defs ds)
  21050. (match ds
  21051. ['() '()]
  21052. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  21053. (unless (equal? name f)
  21054. (error 'type-check "name mismatch, ~a != ~a" name f))
  21055. (match type
  21056. [`(All ,xs (,ps ... -> ,rt))
  21057. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21058. (cons (Generic xs (Def name params^ rt info body))
  21059. (combine-decls-defs ds^))]
  21060. [`(,ps ... -> ,rt)
  21061. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  21062. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  21063. [else (error 'type-check "expected a function type, not ~a" type) ])]
  21064. [`(,(Def f params rt info body) . ,ds^)
  21065. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  21066. \end{lstlisting}
  21067. \fi}
  21068. {\if\edition\pythonEd\pythonColor
  21069. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  21070. def match_types(self, param_ty, arg_ty, deduced, e):
  21071. match (param_ty, arg_ty):
  21072. case (GenericVar(id), _):
  21073. if id in deduced:
  21074. self.check_type_equal(arg_ty, deduced[id], e)
  21075. else:
  21076. deduced[id] = arg_ty
  21077. case (AllType(ps, ty), AllType(arg_ps, arg_ty)):
  21078. rename = {ap:p for (ap,p) in zip(arg_ps, ps)}
  21079. new_arg_ty = self.substitute_type(arg_ty, rename)
  21080. self.match_types(ty, new_arg_ty, deduced, e)
  21081. case (TupleType(ps), TupleType(ts)):
  21082. for (p, a) in zip(ps, ts):
  21083. self.match_types(p, a, deduced, e)
  21084. case (ListType(p), ListType(a)):
  21085. self.match_types(p, a, deduced, e)
  21086. case (FunctionType(pps, prt), FunctionType(aps, art)):
  21087. for (pp, ap) in zip(pps, aps):
  21088. self.match_types(pp, ap, deduced, e)
  21089. self.match_types(prt, art, deduced, e)
  21090. case (IntType(), IntType()):
  21091. pass
  21092. case (BoolType(), BoolType()):
  21093. pass
  21094. case _:
  21095. raise Exception('mismatch: ' + str(param_ty) + '\n!= ' + str(arg_ty))
  21096. def substitute_type(self, ty, var_map):
  21097. match ty:
  21098. case GenericVar(id):
  21099. return var_map[id]
  21100. case AllType(ps, ty):
  21101. new_map = copy.deepcopy(var_map)
  21102. for p in ps:
  21103. new_map[p] = GenericVar(p)
  21104. return AllType(ps, self.substitute_type(ty, new_map))
  21105. case TupleType(ts):
  21106. return TupleType([self.substitute_type(t, var_map) for t in ts])
  21107. case ListType(ty):
  21108. return ListType(self.substitute_type(ty, var_map))
  21109. case FunctionType(pts, rt):
  21110. return FunctionType([self.substitute_type(p, var_map) for p in pts],
  21111. self.substitute_type(rt, var_map))
  21112. case IntType():
  21113. return IntType()
  21114. case BoolType():
  21115. return BoolType()
  21116. case _:
  21117. raise Exception('substitute_type: unexpected ' + repr(ty))
  21118. def check_type_equal(self, t1, t2, e):
  21119. match (t1, t2):
  21120. case (AllType(ps1, ty1), AllType(ps2, ty2)):
  21121. rename = {p2: GenericVar(p1) for (p1,p2) in zip(ps1,ps2)}
  21122. return self.check_type_equal(ty1, self.substitute_type(ty2, rename), e)
  21123. case (_, _):
  21124. return super().check_type_equal(t1, t2, e)
  21125. \end{lstlisting}
  21126. \fi}
  21127. \end{tcolorbox}
  21128. \caption{Auxiliary functions for type checking \LangPoly{}.}
  21129. \label{fig:type-check-Lpoly-aux}
  21130. \end{figure}
  21131. {\if\edition\racketEd
  21132. \begin{figure}[tbp]
  21133. \begin{tcolorbox}[colback=white]
  21134. \begin{lstlisting}
  21135. (define/public ((check_well_formed env) ty)
  21136. (match ty
  21137. ['Integer (void)]
  21138. ['Boolean (void)]
  21139. ['Void (void)]
  21140. [(? symbol? a)
  21141. (match (dict-ref env a (lambda () #f))
  21142. ['Type (void)]
  21143. [else (error 'type-check "undefined type variable ~a" a)])]
  21144. [`(Vector ,ts ...)
  21145. (for ([t ts]) ((check_well_formed env) t))]
  21146. [`(,ts ... -> ,t)
  21147. (for ([t ts]) ((check_well_formed env) t))
  21148. ((check_well_formed env) t)]
  21149. [`(All ,xs ,t)
  21150. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  21151. ((check_well_formed env^) t)]
  21152. [else (error 'type-check "unrecognized type ~a" ty)]))
  21153. \end{lstlisting}
  21154. \end{tcolorbox}
  21155. \caption{Well-formed types.}
  21156. \label{fig:well-formed-types}
  21157. \end{figure}
  21158. \fi}
  21159. % TODO: interpreter for R'_10
  21160. \clearpage
  21161. \section{Compiling Generics}
  21162. \label{sec:compiling-poly}
  21163. Broadly speaking, there are four approaches to compiling generics, as
  21164. follows:
  21165. \begin{description}
  21166. \item[Monomorphization] generates a different version of a generic
  21167. function for each set of type arguments with which it is used,
  21168. producing type-specialized code. This approach results in the most
  21169. efficient code but requires whole-program compilation (no separate
  21170. compilation) and may increase code size. Unfortunately,
  21171. monomorphization is incompatible with first-class generics because
  21172. it is not always possible to determine which generic functions are
  21173. used with which type arguments during compilation. (It can be done
  21174. at runtime with just-in-time compilation.) Monomorphization is
  21175. used to compile C++ templates~\citep{stroustrup88:_param_types} and
  21176. generic functions in NESL~\citep{Blelloch:1993aa} and
  21177. ML~\citep{Weeks:2006aa}.
  21178. \item[Uniform representation] generates one version of each generic
  21179. function and requires all values to have a common \emph{boxed} format,
  21180. such as the tagged values of type \CANYTY{} in \LangAny{}. Both
  21181. generic and monomorphic code is compiled similarly to code in a
  21182. dynamically typed language (like \LangDyn{}), in which primitive
  21183. operators require their arguments to be projected from \CANYTY{} and
  21184. their results to be injected into \CANYTY{}. (In object-oriented
  21185. languages, the projection is accomplished via virtual method
  21186. dispatch.) The uniform representation approach is compatible with
  21187. separate compilation and with first-class generics. However, it
  21188. produces the least efficient code because it introduces overhead in
  21189. the entire program. This approach is used in
  21190. Java~\citep{Bracha:1998fk},
  21191. CLU~\citep{liskov79:_clu_ref,Liskov:1993dk}, and some implementations
  21192. of ML~\citep{Cardelli:1984aa,Appel:1987aa}.
  21193. \item[Mixed representation] generates one version of each generic
  21194. function, using a boxed representation for type variables. However,
  21195. monomorphic code is compiled as usual (as in \LangLam{}), and
  21196. conversions are performed at the boundaries between monomorphic code
  21197. and polymorphic code (for example, when a generic function is instantiated
  21198. and called). This approach is compatible with separate compilation
  21199. and first-class generics and maintains efficiency in monomorphic
  21200. code. The trade-off is increased overhead at the boundary between
  21201. monomorphic and generic code. This approach is used in
  21202. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  21203. Java 5 with the addition of autoboxing.
  21204. \item[Type passing] uses the unboxed representation in both
  21205. monomorphic and generic code. Each generic function is compiled to a
  21206. single function with extra parameters that describe the type
  21207. arguments. The type information is used by the generated code to
  21208. determine how to access the unboxed values at runtime. This approach is
  21209. used in implementation of Napier88~\citep{Morrison:1991aa} and
  21210. ML~\citep{Harper:1995um}. Type passing is compatible with separate
  21211. compilation and first-class generics and maintains the
  21212. efficiency for monomorphic code. There is runtime overhead in
  21213. polymorphic code from dispatching on type information.
  21214. \end{description}
  21215. In this chapter we use the mixed representation approach, partly
  21216. because of its favorable attributes and partly because it is
  21217. straightforward to implement using the tools that we have already
  21218. built to support gradual typing. The work of compiling generic
  21219. functions is performed in two passes, \code{resolve} and
  21220. \code{erase\_types}, that we discuss next. The output of
  21221. \code{erase\_types} is \LangCast{}
  21222. (section~\ref{sec:gradual-insert-casts}), so the rest of the
  21223. compilation is handled by the compiler of chapter~\ref{ch:Lgrad}.
  21224. \section{Resolve Instantiation}
  21225. \label{sec:generic-resolve}
  21226. Recall that the type checker for \LangPoly{} deduces the type
  21227. arguments at call sites to a generic function. The purpose of the
  21228. \code{resolve} pass is to turn this implicit instantiation into an
  21229. explicit one, by adding \code{inst} nodes to the syntax of the
  21230. intermediate language. An \code{inst} node records the mapping of
  21231. type parameters to type arguments. The semantics of the \code{inst}
  21232. node is to instantiate the result of its first argument, a generic
  21233. function, to produce a monomorphic function. However, because the
  21234. interpreter never analyzes type annotations, instantiation can be a
  21235. no-op and simply return the generic function.
  21236. %
  21237. The output language of the \code{resolve} pass is \LangInst{},
  21238. for which the definition is shown in figure~\ref{fig:Lpoly-prime-syntax}.
  21239. {\if\edition\racketEd
  21240. The \code{resolve} pass combines the type declaration and polymorphic
  21241. function into a single definition, using the \code{Poly} form, to make
  21242. polymorphic functions more convenient to process in the next pass of the
  21243. compiler.
  21244. \fi}
  21245. \newcommand{\LinstASTRacket}{
  21246. \begin{array}{lcl}
  21247. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  21248. \Exp &::=& \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  21249. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  21250. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP
  21251. \end{array}
  21252. }
  21253. \newcommand{\LinstASTPython}{
  21254. \begin{array}{lcl}
  21255. \Type &::=& \key{AllType}\LP\LS\Var\ldots\RS, \Type\RP \MID \Var \\
  21256. \Exp &::=& \INST{\Exp}{\LC\Var\key{:}\Type\ldots\RC}
  21257. \end{array}
  21258. }
  21259. \begin{figure}[tp]
  21260. \centering
  21261. \begin{tcolorbox}[colback=white]
  21262. \small
  21263. {\if\edition\racketEd
  21264. \[
  21265. \begin{array}{l}
  21266. \gray{\LintOpAST} \\ \hline
  21267. \gray{\LvarASTRacket{}} \\ \hline
  21268. \gray{\LifASTRacket{}} \\ \hline
  21269. \gray{\LwhileASTRacket{}} \\ \hline
  21270. \gray{\LtupASTRacket{}} \\ \hline
  21271. \gray{\LfunASTRacket} \\ \hline
  21272. \gray{\LlambdaASTRacket} \\ \hline
  21273. \LinstASTRacket \\
  21274. \begin{array}{lcl}
  21275. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  21276. \end{array}
  21277. \end{array}
  21278. \]
  21279. \fi}
  21280. {\if\edition\pythonEd\pythonColor
  21281. \[
  21282. \begin{array}{l}
  21283. \gray{\LintASTPython} \\ \hline
  21284. \gray{\LvarASTPython{}} \\ \hline
  21285. \gray{\LifASTPython{}} \\ \hline
  21286. \gray{\LwhileASTPython{}} \\ \hline
  21287. \gray{\LtupASTPython{}} \\ \hline
  21288. \gray{\LfunASTPython} \\ \hline
  21289. \gray{\LlambdaASTPython} \\ \hline
  21290. \LinstASTPython \\
  21291. \begin{array}{lcl}
  21292. \LangInst{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  21293. \end{array}
  21294. \end{array}
  21295. \]
  21296. \fi}
  21297. \end{tcolorbox}
  21298. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  21299. (figure~\ref{fig:Llam-syntax}).}
  21300. \label{fig:Lpoly-prime-syntax}
  21301. \end{figure}
  21302. The output of the \code{resolve} pass on the generic \code{map}
  21303. example is listed in figure~\ref{fig:map-resolve}. Note that the use
  21304. of \code{map} is wrapped in an \code{inst} node, with the parameter
  21305. \code{T} chosen to be \racket{\code{Integer}}\python{\code{int}}.
  21306. \begin{figure}[tbp]
  21307. % poly_test_2.rkt
  21308. \begin{tcolorbox}[colback=white]
  21309. {\if\edition\racketEd
  21310. \begin{lstlisting}
  21311. (poly (T) (define (map [f : (T -> T)] [v : (Vector T T)]) : (Vector T T)
  21312. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  21313. (define (inc [x : Integer]) : Integer (+ x 1))
  21314. (vector-ref ((inst map (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21315. (Integer))
  21316. inc (vector 0 41)) 1)
  21317. \end{lstlisting}
  21318. \fi}
  21319. {\if\edition\pythonEd\pythonColor
  21320. \begin{lstlisting}
  21321. def map(f : Callable[[T],T], tup : tuple[T,T]) -> tuple[T,T]:
  21322. return (f(tup[0]), f(tup[1]))
  21323. def add1(x : int) -> int:
  21324. return x + 1
  21325. t = inst(map, {T: int})(add1, (0, 41))
  21326. print(t[1])
  21327. \end{lstlisting}
  21328. \fi}
  21329. \end{tcolorbox}
  21330. \caption{Output of the \code{resolve} pass on the \code{map} example.}
  21331. \label{fig:map-resolve}
  21332. \end{figure}
  21333. \section{Erase Generic Types}
  21334. \label{sec:erase_types}
  21335. We use the \CANYTY{} type presented in chapter~\ref{ch:Ldyn} to
  21336. represent type variables. For example, figure~\ref{fig:map-erase}
  21337. shows the output of the \code{erase\_types} pass on the generic
  21338. \code{map} (figure~\ref{fig:map-poly}). The occurrences of
  21339. type parameter \code{T} are replaced by \CANYTY{}, and the generic
  21340. \code{All} types are removed from the type of \code{map}.
  21341. \begin{figure}[tbp]
  21342. \begin{tcolorbox}[colback=white]
  21343. {\if\edition\racketEd
  21344. \begin{lstlisting}
  21345. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  21346. : (Vector Any Any)
  21347. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  21348. (define (inc [x : Integer]) : Integer (+ x 1))
  21349. (vector-ref ((cast map
  21350. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21351. ((Integer -> Integer) (Vector Integer Integer)
  21352. -> (Vector Integer Integer)))
  21353. inc (vector 0 41)) 1)
  21354. \end{lstlisting}
  21355. \fi}
  21356. {\if\edition\pythonEd\pythonColor
  21357. \begin{lstlisting}
  21358. def map(f : Callable[[Any],Any], tup : tuple[Any,Any])-> tuple[Any,Any]:
  21359. return (f(tup[0]), f(tup[1]))
  21360. def add1(x : int) -> int:
  21361. return (x + 1)
  21362. def main() -> int:
  21363. t = cast(map, |$T_1$|, |$T_2$|)(add1, (0, 41))
  21364. print(t[1])
  21365. return 0
  21366. \end{lstlisting}
  21367. {\small
  21368. where\\
  21369. $T_1 = $ \code{Callable[[Callable[[Any], Any],tuple[Any,Any]], tuple[Any,Any]]}\\
  21370. $T_2 = $ \code{Callable[[Callable[[int], int],tuple[int,int]], tuple[int,int]]}
  21371. }
  21372. \fi}
  21373. \end{tcolorbox}
  21374. \caption{The generic \code{map} example after type erasure.}
  21375. \label{fig:map-erase}
  21376. \end{figure}
  21377. This process of type erasure creates a challenge at points of
  21378. instantiation. For example, consider the instantiation of
  21379. \code{map} shown in figure~\ref{fig:map-resolve}.
  21380. The type of \code{map} is
  21381. %
  21382. {\if\edition\racketEd
  21383. \begin{lstlisting}
  21384. (All (T) ((T -> T) (Vector T T) -> (Vector T T)))
  21385. \end{lstlisting}
  21386. \fi}
  21387. {\if\edition\pythonEd\pythonColor
  21388. \begin{lstlisting}
  21389. All[[T], Callable[[Callable[[T], T], tuple[T, T]], tuple[T, T]]]
  21390. \end{lstlisting}
  21391. \fi}
  21392. %
  21393. \noindent and it is instantiated to
  21394. %
  21395. {\if\edition\racketEd
  21396. \begin{lstlisting}
  21397. ((Integer -> Integer) (Vector Integer Integer)
  21398. -> (Vector Integer Integer))
  21399. \end{lstlisting}
  21400. \fi}
  21401. {\if\edition\pythonEd\pythonColor
  21402. \begin{lstlisting}
  21403. Callable[[Callable[[int], int], tuple[int, int]], tuple[int, int]]
  21404. \end{lstlisting}
  21405. \fi}
  21406. %
  21407. \noindent After erasure, the type of \code{map} is
  21408. %
  21409. {\if\edition\racketEd
  21410. \begin{lstlisting}
  21411. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  21412. \end{lstlisting}
  21413. \fi}
  21414. {\if\edition\pythonEd\pythonColor
  21415. \begin{lstlisting}
  21416. Callable[[Callable[[Any], Any], tuple[Any, Any]], tuple[Any, Any]]
  21417. \end{lstlisting}
  21418. \fi}
  21419. %
  21420. \noindent but we need to convert it to the instantiated type. This is
  21421. easy to do in the language \LangCast{} with a single \code{cast}. In
  21422. the example shown in figure~\ref{fig:map-erase}, the instantiation of
  21423. \code{map} has been compiled to a \code{cast} from the type of
  21424. \code{map} to the instantiated type. The source and the target type of
  21425. a cast must be consistent (figure~\ref{fig:consistent}), which indeed
  21426. is the case because both the source and target are obtained from the
  21427. same generic type of \code{map}, replacing the type parameters with
  21428. \CANYTY{} in the former and with the deduced type arguments in the
  21429. latter. (Recall that the \CANYTY{} type is consistent with any type.)
  21430. To implement the \code{erase\_types} pass, we first recommend defining
  21431. a recursive function that translates types, named
  21432. \code{erase\_type}. It replaces type variables with \CANYTY{} as
  21433. follows.
  21434. %
  21435. {\if\edition\racketEd
  21436. \begin{lstlisting}
  21437. |$T$|
  21438. |$\Rightarrow$|
  21439. Any
  21440. \end{lstlisting}
  21441. \fi}
  21442. {\if\edition\pythonEd\pythonColor
  21443. \begin{lstlisting}
  21444. GenericVar(|$T$|)
  21445. |$\Rightarrow$|
  21446. Any
  21447. \end{lstlisting}
  21448. \fi}
  21449. %
  21450. \noindent The \code{erase\_type} function also removes the generic
  21451. \code{All} types.
  21452. %
  21453. {\if\edition\racketEd
  21454. \begin{lstlisting}
  21455. (All |$xs$| |$T_1$|)
  21456. |$\Rightarrow$|
  21457. |$T'_1$|
  21458. \end{lstlisting}
  21459. \fi}
  21460. {\if\edition\pythonEd\pythonColor
  21461. \begin{lstlisting}
  21462. AllType(|$xs$|, |$T_1$|)
  21463. |$\Rightarrow$|
  21464. |$T'_1$|
  21465. \end{lstlisting}
  21466. \fi}
  21467. \noindent where $T'_1$ is the result of applying \code{erase\_type} to
  21468. $T_1$.
  21469. %
  21470. In this compiler pass, apply the \code{erase\_type} function to all
  21471. the type annotations in the program.
  21472. Regarding the translation of expressions, the case for \code{Inst} is
  21473. the interesting one. We translate it into a \code{Cast}, as shown
  21474. next.
  21475. The type of the subexpression $e$ is a generic type of the form
  21476. \racket{$\LP\key{All}~\itm{xs}~T\RP$}\python{$\key{AllType}\LP\itm{xs}, T\RP$}.
  21477. The source type of the cast is the erasure of $T$, the type $T_s$.
  21478. %
  21479. {\if\edition\racketEd
  21480. %
  21481. The target type $T_t$ is the result of substituting the argument types
  21482. $ts$ for the type parameters $xs$ in $T$ and then performing type
  21483. erasure.
  21484. %
  21485. \begin{lstlisting}
  21486. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  21487. |$\Rightarrow$|
  21488. (Cast |$e'$| |$T_s$| |$T_t$|)
  21489. \end{lstlisting}
  21490. %
  21491. where $T_t = \LP\code{erase\_type}~\LP\code{substitute\_type}~s~T\RP\RP$,
  21492. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  21493. \fi}
  21494. {\if\edition\pythonEd\pythonColor
  21495. %
  21496. The target type $T_t$ is the result of substituting the deduced
  21497. argument types $d$ in $T$ and then performing type erasure.
  21498. %
  21499. \begin{lstlisting}
  21500. Inst(|$e$|, |$d$|)
  21501. |$\Rightarrow$|
  21502. Cast(|$e'$|, |$T_s$|, |$T_t$|)
  21503. \end{lstlisting}
  21504. %
  21505. where
  21506. $T_t = \code{erase\_type}\LP\code{substitute\_type}\LP d, T\RP\RP$.
  21507. \fi}
  21508. Finally, each generic function is translated to a regular
  21509. function in which type erasure has been applied to all the type
  21510. annotations and the body.
  21511. %% \begin{lstlisting}
  21512. %% (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  21513. %% |$\Rightarrow$|
  21514. %% (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  21515. %% \end{lstlisting}
  21516. \begin{exercise}\normalfont\normalsize
  21517. Implement a compiler for the polymorphic language \LangPoly{} by
  21518. extending and adapting your compiler for \LangGrad{}. Create six new
  21519. test programs that use polymorphic functions. Some of them should
  21520. make use of first-class generics.
  21521. \end{exercise}
  21522. \begin{figure}[tbp]
  21523. \begin{tcolorbox}[colback=white]
  21524. {\if\edition\racketEd
  21525. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21526. \node (Lpoly) at (0,4) {\large \LangPoly{}};
  21527. \node (Lpolyp) at (4,4) {\large \LangInst{}};
  21528. \node (Lgradualp) at (8,4) {\large \LangCast{}};
  21529. \node (Llambdapp) at (12,4) {\large \LangProxy{}};
  21530. \node (Llambdaproxy) at (12,2) {\large \LangPVec{}};
  21531. \node (Llambdaproxy-2) at (8,2) {\large \LangPVec{}};
  21532. \node (Llambdaproxy-3) at (4,2) {\large \LangPVec{}};
  21533. \node (Llambdaproxy-4) at (0,2) {\large \LangPVecFunRef{}};
  21534. \node (Llambdaproxy-5) at (0,0) {\large \LangPVecFunRef{}};
  21535. \node (F1-1) at (4,0) {\large \LangPVecFunRef{}};
  21536. \node (F1-2) at (8,0) {\large \LangPVecFunRef{}};
  21537. \node (F1-3) at (12,0) {\large \LangPVecFunRef{}};
  21538. \node (F1-4) at (12,-2) {\large \LangPVecAlloc{}};
  21539. \node (F1-5) at (8,-2) {\large \LangPVecAlloc{}};
  21540. \node (F1-6) at (4,-2) {\large \LangPVecAlloc{}};
  21541. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21542. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21543. \node (x86-2-1) at (0,-6) {\large \LangXIndCallVar{}};
  21544. \node (x86-2-2) at (4,-6) {\large \LangXIndCallVar{}};
  21545. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21546. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21547. \node (x86-5) at (8,-6) {\large \LangXIndCall{}};
  21548. \path[->,bend left=15] (Lpoly) edge [above] node
  21549. {\ttfamily\footnotesize resolve} (Lpolyp);
  21550. \path[->,bend left=15] (Lpolyp) edge [above] node
  21551. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  21552. \path[->,bend left=15] (Lgradualp) edge [above] node
  21553. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  21554. \path[->,bend left=15] (Llambdapp) edge [left] node
  21555. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  21556. \path[->,bend left=15] (Llambdaproxy) edge [below] node
  21557. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  21558. \path[->,bend right=15] (Llambdaproxy-2) edge [above] node
  21559. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  21560. \path[->,bend right=15] (Llambdaproxy-3) edge [above] node
  21561. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  21562. \path[->,bend right=15] (Llambdaproxy-4) edge [right] node
  21563. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21564. \path[->,bend right=15] (Llambdaproxy-5) edge [below] node
  21565. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21566. \path[->,bend left=15] (F1-1) edge [above] node
  21567. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21568. \path[->,bend left=15] (F1-2) edge [above] node
  21569. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21570. \path[->,bend left=15] (F1-3) edge [left] node
  21571. {\ttfamily\footnotesize expose\_allocation} (F1-4);
  21572. \path[->,bend left=15] (F1-4) edge [below] node
  21573. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  21574. \path[->,bend right=15] (F1-5) edge [above] node
  21575. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21576. \path[->,bend right=15] (F1-6) edge [above] node
  21577. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21578. \path[->,bend right=15] (C3-2) edge [right] node
  21579. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21580. \path[->,bend right=15] (x86-2) edge [right] node
  21581. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  21582. \path[->,bend right=15] (x86-2-1) edge [below] node
  21583. {\ttfamily\footnotesize build\_interference} (x86-2-2);
  21584. \path[->,bend right=15] (x86-2-2) edge [right] node
  21585. {\ttfamily\footnotesize allocate\_registers} (x86-3);
  21586. \path[->,bend left=15] (x86-3) edge [above] node
  21587. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21588. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21589. \end{tikzpicture}
  21590. \fi}
  21591. {\if\edition\pythonEd\pythonColor
  21592. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.85]
  21593. \node (Lgradual) at (0,4) {\large \LangPoly{}};
  21594. \node (Lgradual2) at (4,4) {\large \LangPoly{}};
  21595. \node (Lgradual3) at (8,4) {\large \LangPoly{}};
  21596. \node (Lgradual4) at (12,4) {\large \LangPoly{}};
  21597. \node (Lgradualr) at (12,2) {\large \LangInst{}};
  21598. \node (Llambdapp) at (8,2) {\large \LangCast{}};
  21599. \node (Llambdaproxy-4) at (4,2) {\large \LangPVec{}};
  21600. \node (Llambdaproxy-5) at (0,2) {\large \LangPVec{}};
  21601. \node (F1-1) at (0,0) {\large \LangPVec{}};
  21602. \node (F1-2) at (4,0) {\large \LangPVec{}};
  21603. \node (F1-3) at (8,0) {\large \LangPVec{}};
  21604. \node (F1-5) at (12,0) {\large \LangPVecAlloc{}};
  21605. \node (F1-6) at (12,-2) {\large \LangPVecAlloc{}};
  21606. \node (C3-2) at (0,-2) {\large \LangCLoopPVec{}};
  21607. \node (x86-2) at (0,-4) {\large \LangXIndCallVar{}};
  21608. \node (x86-3) at (4,-4) {\large \LangXIndCallVar{}};
  21609. \node (x86-4) at (8,-4) {\large \LangXIndCall{}};
  21610. \node (x86-5) at (12,-4) {\large \LangXIndCall{}};
  21611. \path[->,bend left=15] (Lgradual) edge [above] node
  21612. {\ttfamily\footnotesize shrink} (Lgradual2);
  21613. \path[->,bend left=15] (Lgradual2) edge [above] node
  21614. {\ttfamily\footnotesize uniquify} (Lgradual3);
  21615. \path[->,bend left=15] (Lgradual3) edge [above] node
  21616. {\ttfamily\footnotesize reveal\_functions} (Lgradual4);
  21617. \path[->,bend left=15] (Lgradual4) edge [left] node
  21618. {\ttfamily\footnotesize resolve} (Lgradualr);
  21619. \path[->,bend left=15] (Lgradualr) edge [below] node
  21620. {\ttfamily\footnotesize erase\_types} (Llambdapp);
  21621. \path[->,bend right=15] (Llambdapp) edge [above] node
  21622. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy-4);
  21623. \path[->,bend right=15] (Llambdaproxy-4) edge [above] node
  21624. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  21625. \path[->,bend right=15] (Llambdaproxy-5) edge [right] node
  21626. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  21627. \path[->,bend right=15] (F1-1) edge [below] node
  21628. {\ttfamily\footnotesize convert\_to\_closures} (F1-2);
  21629. \path[->,bend right=15] (F1-2) edge [below] node
  21630. {\ttfamily\footnotesize limit\_functions} (F1-3);
  21631. \path[->,bend left=15] (F1-3) edge [above] node
  21632. {\ttfamily\footnotesize expose\_allocation} (F1-5);
  21633. \path[->,bend left=15] (F1-5) edge [left] node
  21634. {\ttfamily\footnotesize remove\_complex\_operands} (F1-6);
  21635. \path[->,bend left=5] (F1-6) edge [below] node
  21636. {\ttfamily\footnotesize explicate\_control} (C3-2);
  21637. \path[->,bend right=15] (C3-2) edge [right] node
  21638. {\ttfamily\footnotesize select\_instructions} (x86-2);
  21639. \path[->,bend right=15] (x86-2) edge [below] node
  21640. {\ttfamily\footnotesize assign\_homes} (x86-3);
  21641. \path[->,bend right=15] (x86-3) edge [below] node
  21642. {\ttfamily\footnotesize patch\_instructions} (x86-4);
  21643. \path[->,bend left=15] (x86-4) edge [above] node
  21644. {\ttfamily\footnotesize prelude\_and\_conclusion} (x86-5);
  21645. \end{tikzpicture}
  21646. \fi}
  21647. \end{tcolorbox}
  21648. \caption{Diagram of the passes for \LangPoly{} (generics).}
  21649. \label{fig:Lpoly-passes}
  21650. \end{figure}
  21651. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  21652. needed to compile \LangPoly{}.
  21653. % TODO: challenge problem: specialization of instantiations
  21654. % Further Reading
  21655. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  21656. \clearpage
  21657. \appendix
  21658. \chapter{Appendix}
  21659. \setcounter{footnote}{0}
  21660. {\if\edition\racketEd
  21661. \section{Interpreters}
  21662. \label{appendix:interp}
  21663. \index{subject}{interpreter}
  21664. We provide interpreters for each of the source languages \LangInt{},
  21665. \LangVar{}, $\ldots$ in the files \code{interp-Lint.rkt},
  21666. \code{interp-Lvar.rkt}, and so on. The interpreters for the
  21667. intermediate languages \LangCVar{} and \LangCIf{} are in
  21668. \code{interp-Cvar.rkt} and \code{interp-C1.rkt}. The interpreters for
  21669. \LangCVec{}, \LangCFun{}, pseudo-x86, and x86 are in the
  21670. \key{interp.rkt} file.
  21671. \section{Utility Functions}
  21672. \label{appendix:utilities}
  21673. The utility functions described in this section are in the
  21674. \key{utilities.rkt} file of the support code.
  21675. \paragraph{\code{interp-tests}}
  21676. This function runs the compiler passes and the interpreters on each of
  21677. the specified tests to check whether each pass is correct. The
  21678. \key{interp-tests} function has the following parameters:
  21679. \begin{description}
  21680. \item[name (a string)] A name to identify the compiler.
  21681. \item[typechecker] A function of exactly one argument that either
  21682. raises an error using the \code{error} function when it encounters a
  21683. type error, or returns \code{\#f} when it encounters a type
  21684. error. If there is no type error, the type checker returns the
  21685. program.
  21686. \item[passes] A list with one entry per pass. An entry is a list
  21687. consisting of four things:
  21688. \begin{enumerate}
  21689. \item a string giving the name of the pass;
  21690. \item the function that implements the pass (a translator from AST
  21691. to AST);
  21692. \item a function that implements the interpreter (a function from
  21693. AST to result value) for the output language; and,
  21694. \item a type checker for the output language. Type checkers for
  21695. all the $\Lang{}$ and $\CLang{}$ languages are provided in the support code.
  21696. For example, the type checkers for \LangVar{} and \LangCVar{} are in
  21697. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  21698. type checker entry is optional. The support code does not provide
  21699. type checkers for the x86 languages.
  21700. \end{enumerate}
  21701. \item[source-interp] An interpreter for the source language. The
  21702. interpreters from appendix~\ref{appendix:interp} make a good choice.
  21703. \item[test-family (a string)] For example, \code{"var"} or \code{"cond"}.
  21704. \item[tests] A list of test numbers that specifies which tests to
  21705. run (explained next).
  21706. \end{description}
  21707. %
  21708. The \key{interp-tests} function assumes that the subdirectory
  21709. \key{tests} has a collection of Racket programs whose names all start
  21710. with the family name, followed by an underscore and then the test
  21711. number, and ending with the file extension \key{.rkt}. Also, for each test
  21712. program that calls \code{read} one or more times, there is a file with
  21713. the same name except that the file extension is \key{.in}, which
  21714. provides the input for the Racket program. If the test program is
  21715. expected to fail type checking, then there should be an empty file of
  21716. the same name with extension \key{.tyerr}.
  21717. \paragraph{\code{compiler-tests}}
  21718. This function runs the compiler passes to generate x86 (a \key{.s}
  21719. file) and then runs the GNU C compiler (gcc) to generate machine code.
  21720. It runs the machine code and checks that the output is $42$. The
  21721. parameters to the \code{compiler-tests} function are similar to those
  21722. of the \code{interp-tests} function, and they consist of
  21723. \begin{itemize}
  21724. \item a compiler name (a string),
  21725. \item a type checker,
  21726. \item description of the passes,
  21727. \item name of a test-family, and
  21728. \item a list of test numbers.
  21729. \end{itemize}
  21730. \paragraph{\code{compile-file}}
  21731. This function takes a description of the compiler passes (see the
  21732. comment for \key{interp-tests}) and returns a function that, given a
  21733. program file name (a string ending in \key{.rkt}), applies all the
  21734. passes and writes the output to a file whose name is the same as the
  21735. program file name with extension \key{.rkt} replaced by \key{.s}.
  21736. \paragraph{\code{read-program}}
  21737. This function takes a file path and parses that file (it must be a
  21738. Racket program) into an abstract syntax tree.
  21739. \paragraph{\code{parse-program}}
  21740. This function takes an S-expression representation of an abstract
  21741. syntax tree and converts it into the struct-based representation.
  21742. \paragraph{\code{assert}}
  21743. This function takes two parameters, a string (\code{msg}) and Boolean
  21744. (\code{bool}), and displays the message \key{msg} if the Boolean
  21745. \key{bool} is false.
  21746. \paragraph{\code{lookup}}
  21747. % remove discussion of lookup? -Jeremy
  21748. This function takes a key and an alist and returns the first value that is
  21749. associated with the given key, if there is one. If not, an error is
  21750. triggered. The alist may contain both immutable pairs (built with
  21751. \key{cons}) and mutable pairs (built with \key{mcons}).
  21752. %The \key{map2} function ...
  21753. \fi} %\racketEd
  21754. \section{x86 Instruction Set Quick Reference}
  21755. \label{sec:x86-quick-reference}
  21756. \index{subject}{x86}
  21757. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  21758. do. We write $A \to B$ to mean that the value of $A$ is written into
  21759. location $B$. Address offsets are given in bytes. The instruction
  21760. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  21761. registers (such as \code{\%rax}), or memory references (such as
  21762. \code{-4(\%ebp)}). Most x86 instructions allow at most one memory
  21763. reference per instruction. Other operands must be immediates or
  21764. registers.
  21765. \begin{table}[tbp]
  21766. \captionabove{Quick reference for the x86 instructions used in this book.}
  21767. \label{tab:x86-instr}
  21768. \centering
  21769. \begin{tabular}{l|l}
  21770. \textbf{Instruction} & \textbf{Operation} \\ \hline
  21771. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  21772. \texttt{negq} $A$ & $- A \to A$ \\
  21773. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  21774. \texttt{imulq} $A$, $B$ & $A \times B \to B$ ($B$ must be a register).\\
  21775. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$. \\
  21776. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  21777. \texttt{retq} & Pops the return address and jumps to it. \\
  21778. \texttt{popq} $A$ & $*\texttt{rsp} \to A;\, \texttt{rsp} + 8 \to \texttt{rsp}$ \\
  21779. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp};\, A \to *\texttt{rsp}$\\
  21780. \texttt{leaq} $A$, $B$ & $A \to B$ ($B$ must be a register.) \\
  21781. \texttt{cmpq} $A$, $B$ & Compare $A$ and $B$ and set the flag register ($B$ must not
  21782. be an immediate). \\
  21783. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  21784. matches the condition code of the instruction; otherwise go to the
  21785. next instructions. The condition codes are \key{e} for \emph{equal},
  21786. \key{l} for \emph{less}, \key{le} for \emph{less or equal}, \key{g}
  21787. for \emph{greater}, and \key{ge} for \emph{greater or equal}.} \\
  21788. \texttt{jl} $L$ & \\
  21789. \texttt{jle} $L$ & \\
  21790. \texttt{jg} $L$ & \\
  21791. \texttt{jge} $L$ & \\
  21792. \texttt{jmp} $L$ & Jump to label $L$. \\
  21793. \texttt{movq} $A$, $B$ & $A \to B$ \\
  21794. \texttt{movzbq} $A$, $B$ &
  21795. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  21796. (e.g., \texttt{al} or \texttt{cl}), $B$ is an 8-byte register,
  21797. and the extra bytes of $B$ are set to zero.} \\
  21798. & \\
  21799. & \\
  21800. \texttt{notq} $A$ & $\sim A \to A$ (bitwise complement)\\
  21801. \texttt{orq} $A$, $B$ & $A \mid B \to B$ (bitwise-or)\\
  21802. \texttt{andq} $A$, $B$ & $A \& B \to B$ (bitwise-and)\\
  21803. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  21804. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  21805. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  21806. then $1 \to A$; else $0 \to A$. Refer to \texttt{je} for the
  21807. description of the condition codes. $A$ must be a single byte register
  21808. (e.g., \texttt{al} or \texttt{cl}).} \\
  21809. \texttt{setl} $A$ & \\
  21810. \texttt{setle} $A$ & \\
  21811. \texttt{setg} $A$ & \\
  21812. \texttt{setge} $A$ &
  21813. \end{tabular}
  21814. \end{table}
  21815. \backmatter
  21816. \addtocontents{toc}{\vspace{11pt}}
  21817. \cleardoublepage % needed for right page number in TOC for References
  21818. %% \nocite{*} is a way to get all the entries in the .bib file to
  21819. %% print in the bibliography:
  21820. \nocite{*}\let\bibname\refname
  21821. \addcontentsline{toc}{fmbm}{\refname}
  21822. \printbibliography
  21823. %\printindex{authors}{Author Index}
  21824. \printindex{subject}{Index}
  21825. \end{document}
  21826. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  21827. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  21828. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  21829. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  21830. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  21831. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  21832. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  21833. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  21834. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  21835. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  21836. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  21837. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  21838. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  21839. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  21840. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  21841. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  21842. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  21843. % LocalWords: numberstyle Cormen sudoku Balakrishnan ve aka DSATUR
  21844. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  21845. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  21846. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  21847. % LocalWords: eq prog rcl definitional Evaluator os
  21848. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  21849. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  21850. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  21851. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  21852. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  21853. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  21854. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  21855. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  21856. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  21857. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  21858. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  21859. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  21860. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  21861. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  21862. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  21863. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  21864. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  21865. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  21866. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  21867. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  21868. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  21869. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  21870. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  21871. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  21872. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  21873. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  21874. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  21875. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  21876. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  21877. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  21878. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  21879. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  21880. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  21881. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  21882. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  21883. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  21884. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  21885. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  21886. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  21887. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  21888. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  21889. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  21890. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  21891. % LocalWords: notq setle setg setge uncredited LT Std groundbreaking
  21892. % LocalWords: colback GitHub inputint nonatomic ea tcolorbox bassed
  21893. % LocalWords: tikzpicture Chaitin's Belady's Cocke Freiburghouse Lt
  21894. % LocalWords: lessthan lessthaneq greaterthan greaterthaneq Gt pt Te
  21895. % LocalWords: ts escapechar Tc bl ch cl cc foo lt metavariables vars
  21896. % LocalWords: trans naively IR rep assoc ListType TypeCheckLarray dz
  21897. % LocalWords: Mult InterpLarray lst array's generation's Collins inc
  21898. % LocalWords: Cutler Kelsey val rt bod conflates reg inlining lam AF
  21899. % LocalWords: ASTPython body's bot todo rs ls TypeCheckLgrad ops ab
  21900. % LocalWords: value's inplace anyfun anytup anylist ValueExp proxied
  21901. % LocalWords: ProxiedTuple ProxiedList InterpLcast ListProxy vectof
  21902. % LocalWords: TupleProxy RawTuple InjectTuple InjectTupleProxy vecof
  21903. % LocalWords: InjectList InjectListProxy unannotated Lgradualr poly
  21904. % LocalWords: GenericVar AllType Inst builtin ap pps aps pp deepcopy
  21905. % LocalWords: liskov clu Liskov dk Napier um inst popl jg seq ith qy
  21906. % LocalWords: racketEd subparts subpart nonterminal nonterminals Dyn
  21907. % LocalWords: pseudocode underapproximation underapproximations LALR
  21908. % LocalWords: semilattices overapproximate incrementing Earley docs
  21909. % LocalWords: multilanguage Prelim shinan DeRemer lexer Lesk LPAR cb
  21910. % LocalWords: RPAR abcbab abc bzca usub paren expr lang WS Tomita qr
  21911. % LocalWords: subparses LCCN ebook hardcover epub pdf LCSH LCC DDC
  21912. % LocalWords: LC partialevaluation pythonEd TOC TrappedError