book.tex 711 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526
  1. \documentclass[7x10,nocrop]{TimesAPriori_MIT}%%7x10
  2. % TODO:
  3. % move binary subtraction from Lif to Lint
  4. \usepackage[utf8]{inputenc}
  5. %% \usepackage{setspace}
  6. %% \doublespacing
  7. \usepackage{listings}
  8. \usepackage{verbatim}
  9. \usepackage{amssymb}
  10. \usepackage{lmodern} % better typewriter font for code
  11. %\usepackage{wrapfig}
  12. \usepackage{multirow}
  13. \usepackage{tcolorbox}
  14. \usepackage{color}
  15. %\usepackage{ifthen}
  16. \usepackage{upquote}
  17. \usepackage[all]{xy}
  18. \definecolor{lightgray}{gray}{1}
  19. \newcommand{\black}[1]{{\color{black} #1}}
  20. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  21. \newcommand{\gray}[1]{{\color{gray} #1}}
  22. \def\racketEd{0}
  23. \def\pythonEd{1}
  24. \def\edition{0}
  25. % material that is specific to the Racket edition of the book
  26. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  27. % would like a command for: \if\edition\racketEd\color{olive}
  28. % and : \fi\color{black}
  29. % material that is specific to the Python edition of the book
  30. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  31. %% For multiple indices:
  32. \usepackage{multind}
  33. \makeindex{subject}
  34. \makeindex{authors}
  35. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  36. \if\edition\racketEd
  37. \lstset{%
  38. language=Lisp,
  39. basicstyle=\ttfamily\small,
  40. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  41. deletekeywords={read,mapping,vector},
  42. escapechar=|,
  43. columns=flexible,
  44. moredelim=[is][\color{red}]{~}{~},
  45. showstringspaces=false
  46. }
  47. \fi
  48. \if\edition\pythonEd
  49. \lstset{%
  50. language=Python,
  51. basicstyle=\ttfamily\small,
  52. morekeywords={match,case,bool,int,let},
  53. deletekeywords={},
  54. escapechar=|,
  55. columns=flexible,
  56. moredelim=[is][\color{red}]{~}{~},
  57. showstringspaces=false
  58. }
  59. \fi
  60. %%% Any shortcut own defined macros place here
  61. %% sample of author macro:
  62. \input{defs}
  63. \newtheorem{exercise}[theorem]{Exercise}
  64. % Adjusted settings
  65. \setlength{\columnsep}{4pt}
  66. %% \begingroup
  67. %% \setlength{\intextsep}{0pt}%
  68. %% \setlength{\columnsep}{0pt}%
  69. %% \begin{wrapfigure}{r}{0.5\textwidth}
  70. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  71. %% \caption{Basic layout}
  72. %% \end{wrapfigure}
  73. %% \lipsum[1]
  74. %% \endgroup
  75. \newbox\oiintbox
  76. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  77. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  78. \def\oiint{\copy\oiintbox}
  79. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  80. %\usepackage{showframe}
  81. \def\ShowFrameLinethickness{0.125pt}
  82. \addbibresource{book.bib}
  83. \begin{document}
  84. \frontmatter
  85. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  86. \halftitlepage
  87. \Title{Essentials of Compilation}
  88. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  89. %\edition{First Edition}
  90. \BookAuthor{Jeremy G. Siek}
  91. \imprint{The MIT Press\\
  92. Cambridge, Massachusetts\\
  93. London, England}
  94. \begin{copyrightpage}
  95. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  96. or personal downloading under the
  97. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  98. license.
  99. Copyright in this monograph has been licensed exclusively to The MIT
  100. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  101. version to the public in 2022. All inquiries regarding rights should
  102. be addressed to The MIT Press, Rights and Permissions Department.
  103. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  104. %% All rights reserved. No part of this book may be reproduced in any
  105. %% form by any electronic or mechanical means (including photocopying,
  106. %% recording, or information storage and retrieval) without permission in
  107. %% writing from the publisher.
  108. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  109. %% United States of America.
  110. %% Library of Congress Cataloging-in-Publication Data is available.
  111. %% ISBN:
  112. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  113. \end{copyrightpage}
  114. \dedication{This book is dedicated to the programming language wonks
  115. at Indiana University.}
  116. %% \begin{epigraphpage}
  117. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  118. %% \textit{Book Name if any}}
  119. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  120. %% \end{epigraphpage}
  121. \tableofcontents
  122. %\listoffigures
  123. %\listoftables
  124. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  125. \chapter*{Preface}
  126. \addcontentsline{toc}{fmbm}{Preface}
  127. There is a magical moment when a programmer presses the ``run'' button
  128. and the software begins to execute. Somehow a program written in a
  129. high-level language is running on a computer that is only capable of
  130. shuffling bits. Here we reveal the wizardry that makes that moment
  131. possible. Beginning with the groundbreaking work of Backus and
  132. colleagues in the 1950s, computer scientists discovered techniques for
  133. constructing programs, called \emph{compilers}, that automatically
  134. translate high-level programs into machine code.
  135. We take you on a journey of constructing your own compiler for a small
  136. but powerful language. Along the way we explain the essential
  137. concepts, algorithms, and data structures that underlie compilers. We
  138. develop your understanding of how programs are mapped onto computer
  139. hardware, which is helpful when reasoning about properties at the
  140. junction between hardware and software such as execution time,
  141. software errors, and security vulnerabilities. For those interested
  142. in pursuing compiler construction as a career, our goal is to provide a
  143. stepping-stone to advanced topics such as just-in-time compilation,
  144. program analysis, and program optimization. For those interested in
  145. designing and implementing programming languages, we connect
  146. language design choices to their impact on the compiler and the generated
  147. code.
  148. A compiler is typically organized as a sequence of stages that
  149. progressively translate a program to the code that runs on
  150. hardware. We take this approach to the extreme by partitioning our
  151. compiler into a large number of \emph{nanopasses}, each of which
  152. performs a single task. This enables the testing of each pass in
  153. isolation and focuses our attention, making the compiler far easier to
  154. understand.
  155. The most familiar approach to describing compilers is with each
  156. chapter dedicated to one pass. The problem with that approach is it
  157. obfuscates how language features motivate design choices in a
  158. compiler. We instead take an \emph{incremental} approach in which we
  159. build a complete compiler in each chapter, starting with a small input
  160. language that includes only arithmetic and variables. We add new
  161. language features in subsequent chapters, extending the compiler as
  162. necessary.
  163. Our choice of language features is designed to elicit fundamental
  164. concepts and algorithms used in compilers.
  165. \begin{itemize}
  166. \item We begin with integer arithmetic and local variables in
  167. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  168. the fundamental tools of compiler construction: \emph{abstract
  169. syntax trees} and \emph{recursive functions}.
  170. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  171. \emph{graph coloring} to assign variables to machine registers.
  172. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  173. motivates an elegant recursive algorithm for translating them into
  174. conditional \code{goto}'s.
  175. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  176. variables}. This elicits the need for \emph{dataflow
  177. analysis} in the register allocator.
  178. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  179. \emph{garbage collection}.
  180. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  181. without lexical scoping, similar to functions in the C programming
  182. language~\citep{Kernighan:1988nx}. The reader learns about the
  183. procedure call stack and \emph{calling conventions} and how they interact
  184. with register allocation and garbage collection. The chapter also
  185. describes how to generate efficient tail calls.
  186. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  187. scoping, i.e., \emph{lambda} expressions. The reader learns about
  188. \emph{closure conversion}, in which lambdas are translated into a
  189. combination of functions and tuples.
  190. % Chapter about classes and objects?
  191. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  192. point the input languages are statically typed. The reader extends
  193. the statically typed language with an \code{Any} type which serves
  194. as a target for compiling the dynamically typed language.
  195. {\if\edition\pythonEd
  196. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  197. \emph{classes}.
  198. \fi}
  199. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  200. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  201. in which different regions of a program may be static or dynamically
  202. typed. The reader implements runtime support for \emph{proxies} that
  203. allow values to safely move between regions.
  204. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  205. leveraging the \code{Any} type and type casts developed in Chapters
  206. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  207. \end{itemize}
  208. There are many language features that we do not include. Our choices
  209. balance the incidental complexity of a feature versus the fundamental
  210. concepts that it exposes. For example, we include tuples and not
  211. records because they both elicit the study of heap allocation and
  212. garbage collection but records come with more incidental complexity.
  213. Since 2009 drafts of this book have served as the textbook for 16-week
  214. compiler courses for upper-level undergraduates and first-year
  215. graduate students at the University of Colorado and Indiana
  216. University.
  217. %
  218. Students come into the course having learned the basics of
  219. programming, data structures and algorithms, and discrete
  220. mathematics.
  221. %
  222. At the beginning of the course, students form groups of 2-4 people.
  223. The groups complete one chapter every two weeks, starting with
  224. Chapter~\ref{ch:Lvar} and finishing with
  225. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  226. that we assign to the graduate students. The last two weeks of the
  227. course involve a final project in which students design and implement
  228. a compiler extension of their choosing. The later chapters can be
  229. used in support of these projects. For compiler courses at
  230. universities on the quarter system (about 10 weeks in length), we
  231. recommend completing up through Chapter~\ref{ch:Lvec} or
  232. Chapter~\ref{ch:Lfun} and providing some scaffolding code to the
  233. students for each compiler pass.
  234. %
  235. The course can be adapted to emphasize functional languages by
  236. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  237. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  238. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  239. %
  240. \python{A course that emphasizes object-oriented languages would
  241. include Chapter~\ref{ch:Lobject}.}
  242. %
  243. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  244. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  245. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  246. tail calls.
  247. This book has been used in compiler courses at California Polytechnic
  248. State University, Portland State University, Rose–Hulman Institute of
  249. Technology, University of Freiburg, University of Massachusetts
  250. Lowell, and the University of Vermont.
  251. \begin{figure}[tp]
  252. \fbox{
  253. \begin{minipage}{0.96\textwidth}
  254. {\if\edition\racketEd
  255. \begin{tikzpicture}[baseline=(current bounding box.center)]
  256. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  257. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  258. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  259. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  260. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  261. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  262. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  263. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  264. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  265. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  266. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  267. \path[->] (C1) edge [above] node {} (C2);
  268. \path[->] (C2) edge [above] node {} (C3);
  269. \path[->] (C3) edge [above] node {} (C4);
  270. \path[->] (C4) edge [above] node {} (C5);
  271. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  272. \path[->] (C5) edge [above] node {} (C7);
  273. \path[->] (C6) edge [above] node {} (C7);
  274. \path[->] (C4) edge [above] node {} (C8);
  275. \path[->] (C4) edge [above] node {} (C9);
  276. \path[->] (C7) edge [above] node {} (C10);
  277. \path[->] (C8) edge [above] node {} (C10);
  278. \path[->] (C10) edge [above] node {} (C11);
  279. \end{tikzpicture}
  280. \fi}
  281. {\if\edition\pythonEd
  282. \begin{tikzpicture}[baseline=(current bounding box.center)]
  283. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  284. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  285. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  286. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  287. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  288. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  289. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  290. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  291. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  292. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  293. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  294. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  295. \path[->] (C1) edge [above] node {} (C2);
  296. \path[->] (C2) edge [above] node {} (C3);
  297. \path[->] (C3) edge [above] node {} (C4);
  298. \path[->] (C4) edge [above] node {} (C5);
  299. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  300. \path[->] (C5) edge [above] node {} (C7);
  301. \path[->] (C6) edge [above] node {} (C7);
  302. \path[->] (C4) edge [above] node {} (C8);
  303. \path[->] (C4) edge [above] node {} (C9);
  304. \path[->] (C7) edge [above] node {} (C10);
  305. \path[->] (C8) edge [above] node {} (C10);
  306. \path[->] (C8) edge [above] node {} (CO);
  307. \path[->] (C10) edge [above] node {} (C11);
  308. \end{tikzpicture}
  309. \fi}
  310. \end{minipage}
  311. }
  312. \caption{Diagram of chapter dependencies.}
  313. \label{fig:chapter-dependences}
  314. \end{figure}
  315. \racket{
  316. We use the \href{https://racket-lang.org/}{Racket} language both for
  317. the implementation of the compiler and for the input language, so the
  318. reader should be proficient with Racket or Scheme. There are many
  319. excellent resources for learning Scheme and
  320. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  321. }
  322. \python{
  323. This edition of the book uses \href{https://www.python.org/}{Python}
  324. both for the implementation of the compiler and for the input language, so the
  325. reader should be proficient with Python. There are many
  326. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  327. }
  328. The support code for this book is in the github repository at
  329. the following location:
  330. \if\edition\racketEd
  331. \begin{center}\small
  332. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  333. \end{center}
  334. \fi
  335. \if\edition\pythonEd
  336. \begin{center}\small
  337. \url{https://github.com/IUCompilerCourse/}
  338. \end{center}
  339. \fi
  340. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  341. is helpful but not necessary for the reader to have taken a computer
  342. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  343. assembly language that are needed in the compiler.
  344. %
  345. We follow the System V calling
  346. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  347. that we generate works with the runtime system (written in C) when it
  348. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  349. operating systems on Intel hardware.
  350. %
  351. On the Windows operating system, \code{gcc} uses the Microsoft x64
  352. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  353. assembly code that we generate does \emph{not} work with the runtime
  354. system on Windows. One workaround is to use a virtual machine with
  355. Linux as the guest operating system.
  356. \section*{Acknowledgments}
  357. The tradition of compiler construction at Indiana University goes back
  358. to research and courses on programming languages by Daniel Friedman in
  359. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  360. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  361. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  362. the compiler course and continued the development of Chez Scheme.
  363. %
  364. The compiler course evolved to incorporate novel pedagogical ideas
  365. while also including elements of real-world compilers. One of
  366. Friedman's ideas was to split the compiler into many small
  367. passes. Another idea, called ``the game'', was to test the code
  368. generated by each pass using interpreters.
  369. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  370. developed infrastructure to support this approach and evolved the
  371. course to use even smaller
  372. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  373. design decisions in this book are inspired by the assignment
  374. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  375. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  376. organization of the course made it difficult for students to
  377. understand the rationale for the compiler design. Ghuloum proposed the
  378. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  379. on.
  380. We thank the many students who served as teaching assistants for the
  381. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  382. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  383. garbage collector and x86 interpreter, Michael Vollmer for work on
  384. efficient tail calls, and Michael Vitousek for help with the first
  385. offering of the incremental compiler course at IU.
  386. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  387. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  388. Michael Wollowski for teaching courses based on drafts of this book
  389. and for their feedback.
  390. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  391. course in the early 2000's and especially for finding the bug that
  392. sent our garbage collector on a wild goose chase!
  393. \mbox{}\\
  394. \noindent Jeremy G. Siek \\
  395. Bloomington, Indiana
  396. \mainmatter
  397. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  398. \chapter{Preliminaries}
  399. \label{ch:trees-recur}
  400. In this chapter we review the basic tools that are needed to implement
  401. a compiler. Programs are typically input by a programmer as text,
  402. i.e., a sequence of characters. The program-as-text representation is
  403. called \emph{concrete syntax}. We use concrete syntax to concisely
  404. write down and talk about programs. Inside the compiler, we use
  405. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  406. that efficiently supports the operations that the compiler needs to
  407. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  408. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  409. from concrete syntax to abstract syntax is a process called
  410. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  411. implementation of parsing in this book.
  412. %
  413. \racket{A parser is provided in the support code for translating from
  414. concrete to abstract syntax.}
  415. %
  416. \python{We use Python's \code{ast} module to translate from concrete
  417. to abstract syntax.}
  418. ASTs can be represented in many different ways inside the compiler,
  419. depending on the programming language used to write the compiler.
  420. %
  421. \racket{We use Racket's
  422. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  423. feature to represent ASTs (Section~\ref{sec:ast}).}
  424. %
  425. \python{We use Python classes and objects to represent ASTs, especially the
  426. classes defined in the standard \code{ast} module for the Python
  427. source language.}
  428. %
  429. We use grammars to define the abstract syntax of programming languages
  430. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  431. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  432. recursive functions to construct and deconstruct ASTs
  433. (Section~\ref{sec:recursion}). This chapter provides an brief
  434. introduction to these ideas.
  435. \racket{\index{subject}{struct}}
  436. \python{\index{subject}{class}\index{subject}{object}}
  437. \section{Abstract Syntax Trees}
  438. \label{sec:ast}
  439. Compilers use abstract syntax trees to represent programs because they
  440. often need to ask questions like: for a given part of a program, what
  441. kind of language feature is it? What are its sub-parts? Consider the
  442. program on the left and its AST on the right. This program is an
  443. addition operation and it has two sub-parts, a
  444. \racket{read}\python{input} operation and a negation. The negation has
  445. another sub-part, the integer constant \code{8}. By using a tree to
  446. represent the program, we can easily follow the links to go from one
  447. part of a program to its sub-parts.
  448. \begin{center}
  449. \begin{minipage}{0.4\textwidth}
  450. \if\edition\racketEd
  451. \begin{lstlisting}
  452. (+ (read) (- 8))
  453. \end{lstlisting}
  454. \fi
  455. \if\edition\pythonEd
  456. \begin{lstlisting}
  457. input_int() + -8
  458. \end{lstlisting}
  459. \fi
  460. \end{minipage}
  461. \begin{minipage}{0.4\textwidth}
  462. \begin{equation}
  463. \begin{tikzpicture}
  464. \node[draw] (plus) at (0 , 0) {\key{+}};
  465. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  466. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  467. \node[draw] (8) at (1 , -3) {\key{8}};
  468. \draw[->] (plus) to (read);
  469. \draw[->] (plus) to (minus);
  470. \draw[->] (minus) to (8);
  471. \end{tikzpicture}
  472. \label{eq:arith-prog}
  473. \end{equation}
  474. \end{minipage}
  475. \end{center}
  476. We use the standard terminology for trees to describe ASTs: each
  477. rectangle above is called a \emph{node}. The arrows connect a node to its
  478. \emph{children} (which are also nodes). The top-most node is the
  479. \emph{root}. Every node except for the root has a \emph{parent} (the
  480. node it is the child of). If a node has no children, it is a
  481. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  482. \index{subject}{node}
  483. \index{subject}{children}
  484. \index{subject}{root}
  485. \index{subject}{parent}
  486. \index{subject}{leaf}
  487. \index{subject}{internal node}
  488. %% Recall that an \emph{symbolic expression} (S-expression) is either
  489. %% \begin{enumerate}
  490. %% \item an atom, or
  491. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  492. %% where $e_1$ and $e_2$ are each an S-expression.
  493. %% \end{enumerate}
  494. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  495. %% null value \code{'()}, etc. We can create an S-expression in Racket
  496. %% simply by writing a backquote (called a quasi-quote in Racket)
  497. %% followed by the textual representation of the S-expression. It is
  498. %% quite common to use S-expressions to represent a list, such as $a, b
  499. %% ,c$ in the following way:
  500. %% \begin{lstlisting}
  501. %% `(a . (b . (c . ())))
  502. %% \end{lstlisting}
  503. %% Each element of the list is in the first slot of a pair, and the
  504. %% second slot is either the rest of the list or the null value, to mark
  505. %% the end of the list. Such lists are so common that Racket provides
  506. %% special notation for them that removes the need for the periods
  507. %% and so many parenthesis:
  508. %% \begin{lstlisting}
  509. %% `(a b c)
  510. %% \end{lstlisting}
  511. %% The following expression creates an S-expression that represents AST
  512. %% \eqref{eq:arith-prog}.
  513. %% \begin{lstlisting}
  514. %% `(+ (read) (- 8))
  515. %% \end{lstlisting}
  516. %% When using S-expressions to represent ASTs, the convention is to
  517. %% represent each AST node as a list and to put the operation symbol at
  518. %% the front of the list. The rest of the list contains the children. So
  519. %% in the above case, the root AST node has operation \code{`+} and its
  520. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  521. %% diagram \eqref{eq:arith-prog}.
  522. %% To build larger S-expressions one often needs to splice together
  523. %% several smaller S-expressions. Racket provides the comma operator to
  524. %% splice an S-expression into a larger one. For example, instead of
  525. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  526. %% we could have first created an S-expression for AST
  527. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  528. %% S-expression.
  529. %% \begin{lstlisting}
  530. %% (define ast1.4 `(- 8))
  531. %% (define ast1_1 `(+ (read) ,ast1.4))
  532. %% \end{lstlisting}
  533. %% In general, the Racket expression that follows the comma (splice)
  534. %% can be any expression that produces an S-expression.
  535. {\if\edition\racketEd
  536. We define a Racket \code{struct} for each kind of node. For this
  537. chapter we require just two kinds of nodes: one for integer constants
  538. and one for primitive operations. The following is the \code{struct}
  539. definition for integer constants.\footnote{All of the AST structures are
  540. defined in the file \code{utilities.rkt} in the support code.}
  541. \begin{lstlisting}
  542. (struct Int (value))
  543. \end{lstlisting}
  544. An integer node includes just one thing: the integer value.
  545. To create an AST node for the integer $8$, we write \INT{8}.
  546. \begin{lstlisting}
  547. (define eight (Int 8))
  548. \end{lstlisting}
  549. We say that the value created by \INT{8} is an
  550. \emph{instance} of the
  551. \code{Int} structure.
  552. The following is the \code{struct} definition for primitive operations.
  553. \begin{lstlisting}
  554. (struct Prim (op args))
  555. \end{lstlisting}
  556. A primitive operation node includes an operator symbol \code{op} and a
  557. list of child \code{args}. For example, to create an AST that negates
  558. the number $8$, we write the following.
  559. \begin{lstlisting}
  560. (define neg-eight (Prim '- (list eight)))
  561. \end{lstlisting}
  562. Primitive operations may have zero or more children. The \code{read}
  563. operator has zero:
  564. \begin{lstlisting}
  565. (define rd (Prim 'read '()))
  566. \end{lstlisting}
  567. The addition operator has two children:
  568. \begin{lstlisting}
  569. (define ast1_1 (Prim '+ (list rd neg-eight)))
  570. \end{lstlisting}
  571. We have made a design choice regarding the \code{Prim} structure.
  572. Instead of using one structure for many different operations
  573. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  574. structure for each operation, as follows.
  575. \begin{lstlisting}
  576. (struct Read ())
  577. (struct Add (left right))
  578. (struct Neg (value))
  579. \end{lstlisting}
  580. The reason we choose to use just one structure is that in many parts
  581. of the compiler the code for the different primitive operators is the
  582. same, so we might as well just write that code once, which is enabled
  583. by using a single structure.
  584. \fi}
  585. {\if\edition\pythonEd
  586. We use a Python \code{class} for each kind of node.
  587. The following is the class definition for constants.
  588. \begin{lstlisting}
  589. class Constant:
  590. def __init__(self, value):
  591. self.value = value
  592. \end{lstlisting}
  593. An integer constant node includes just one thing: the integer value.
  594. To create an AST node for the integer $8$, we write \INT{8}.
  595. \begin{lstlisting}
  596. eight = Constant(8)
  597. \end{lstlisting}
  598. We say that the value created by \INT{8} is an
  599. \emph{instance} of the \code{Constant} class.
  600. The following is the class definition for unary operators.
  601. \begin{lstlisting}
  602. class UnaryOp:
  603. def __init__(self, op, operand):
  604. self.op = op
  605. self.operand = operand
  606. \end{lstlisting}
  607. The specific operation is specified by the \code{op} parameter. For
  608. example, the class \code{USub} is for unary subtraction. (More unary
  609. operators are introduced in later chapters.) To create an AST that
  610. negates the number $8$, we write the following.
  611. \begin{lstlisting}
  612. neg_eight = UnaryOp(USub(), eight)
  613. \end{lstlisting}
  614. The call to the \code{input\_int} function is represented by the
  615. \code{Call} and \code{Name} classes.
  616. \begin{lstlisting}
  617. class Call:
  618. def __init__(self, func, args):
  619. self.func = func
  620. self.args = args
  621. class Name:
  622. def __init__(self, id):
  623. self.id = id
  624. \end{lstlisting}
  625. To create an AST node that calls \code{input\_int}, we write
  626. \begin{lstlisting}
  627. read = Call(Name('input_int'), [])
  628. \end{lstlisting}
  629. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  630. the \code{BinOp} class for binary operators.
  631. \begin{lstlisting}
  632. class BinOp:
  633. def __init__(self, left, op, right):
  634. self.op = op
  635. self.left = left
  636. self.right = right
  637. \end{lstlisting}
  638. Similar to \code{UnaryOp}, the specific operation is specified by the
  639. \code{op} parameter, which for now is just an instance of the
  640. \code{Add} class. So to create the AST node that adds negative eight
  641. to some user input, we write the following.
  642. \begin{lstlisting}
  643. ast1_1 = BinOp(read, Add(), neg_eight)
  644. \end{lstlisting}
  645. \fi}
  646. When compiling a program such as \eqref{eq:arith-prog}, we need to
  647. know that the operation associated with the root node is addition and
  648. we need to be able to access its two children. \racket{Racket}\python{Python}
  649. provides pattern matching to support these kinds of queries, as we see in
  650. Section~\ref{sec:pattern-matching}.
  651. We often write down the concrete syntax of a program even when we
  652. really have in mind the AST because the concrete syntax is more
  653. concise. We recommend that, in your mind, you always think of
  654. programs as abstract syntax trees.
  655. \section{Grammars}
  656. \label{sec:grammar}
  657. \index{subject}{integer}
  658. \index{subject}{literal}
  659. \index{subject}{constant}
  660. A programming language can be thought of as a \emph{set} of programs.
  661. The set is typically infinite (one can always create larger and larger
  662. programs) so one cannot simply describe a language by listing all of
  663. the programs in the language. Instead we write down a set of rules, a
  664. \emph{grammar}, for building programs. Grammars are often used to
  665. define the concrete syntax of a language but they can also be used to
  666. describe the abstract syntax. We write our rules in a variant of
  667. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  668. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  669. As an example, we describe a small language, named \LangInt{}, that consists of
  670. integers and arithmetic operations.
  671. \index{subject}{grammar}
  672. The first grammar rule for the abstract syntax of \LangInt{} says that an
  673. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  674. \begin{equation}
  675. \Exp ::= \INT{\Int} \label{eq:arith-int}
  676. \end{equation}
  677. %
  678. Each rule has a left-hand-side and a right-hand-side.
  679. If you have an AST node that matches the
  680. right-hand-side, then you can categorize it according to the
  681. left-hand-side.
  682. %
  683. Symbols in typewriter font are \emph{terminal} symbols and must
  684. literally appear in the program for the rule to be applicable.
  685. \index{subject}{terminal}
  686. %
  687. Our grammars do not mention \emph{white-space}, that is, separating characters
  688. like spaces, tabulators, and newlines. White-space may be inserted
  689. between symbols for disambiguation and to improve readability.
  690. \index{subject}{white-space}
  691. %
  692. A name such as $\Exp$ that is defined by the grammar rules is a
  693. \emph{non-terminal}. \index{subject}{non-terminal}
  694. %
  695. The name $\Int$ is also a non-terminal, but instead of defining it
  696. with a grammar rule, we define it with the following explanation. An
  697. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  698. $-$ (for negative integers), such that the sequence of decimals
  699. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  700. the representation of integers using 63 bits, which simplifies several
  701. aspects of compilation. \racket{Thus, these integers correspond to
  702. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  703. \python{In contrast, integers in Python have unlimited precision, but
  704. the techniques needed to handle unlimited precision fall outside the
  705. scope of this book.}
  706. The second grammar rule is the \READOP{} operation that receives an
  707. input integer from the user of the program.
  708. \begin{equation}
  709. \Exp ::= \READ{} \label{eq:arith-read}
  710. \end{equation}
  711. The third rule categorizes the negation of an $\Exp$ node as an
  712. $\Exp$.
  713. \begin{equation}
  714. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  715. \end{equation}
  716. We can apply these rules to categorize the ASTs that are in the
  717. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  718. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  719. following AST is an $\Exp$.
  720. \begin{center}
  721. \begin{minipage}{0.5\textwidth}
  722. \NEG{\INT{\code{8}}}
  723. \end{minipage}
  724. \begin{minipage}{0.25\textwidth}
  725. \begin{equation}
  726. \begin{tikzpicture}
  727. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  728. \node[draw, circle] (8) at (0, -1.2) {$8$};
  729. \draw[->] (minus) to (8);
  730. \end{tikzpicture}
  731. \label{eq:arith-neg8}
  732. \end{equation}
  733. \end{minipage}
  734. \end{center}
  735. The next grammar rules are for addition and subtraction expressions:
  736. \begin{align}
  737. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  738. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  739. \end{align}
  740. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  741. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  742. \eqref{eq:arith-read} and we have already categorized
  743. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  744. to show that
  745. \[
  746. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  747. \]
  748. is an $\Exp$ in the \LangInt{} language.
  749. If you have an AST for which the above rules do not apply, then the
  750. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  751. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  752. because there is no rule for the \key{*} operator. Whenever we
  753. define a language with a grammar, the language only includes those
  754. programs that are justified by the grammar rules.
  755. {\if\edition\pythonEd
  756. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  757. There is a statement for printing the value of an expression
  758. \[
  759. \Stmt{} ::= \PRINT{\Exp}
  760. \]
  761. and a statement that evaluates an expression but ignores the result.
  762. \[
  763. \Stmt{} ::= \EXPR{\Exp}
  764. \]
  765. \fi}
  766. {\if\edition\racketEd
  767. The last grammar rule for \LangInt{} states that there is a
  768. \code{Program} node to mark the top of the whole program:
  769. \[
  770. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  771. \]
  772. The \code{Program} structure is defined as follows
  773. \begin{lstlisting}
  774. (struct Program (info body))
  775. \end{lstlisting}
  776. where \code{body} is an expression. In later chapters, the \code{info}
  777. part will be used to store auxiliary information but for now it is
  778. just the empty list.
  779. \fi}
  780. {\if\edition\pythonEd
  781. The last grammar rule for \LangInt{} states that there is a
  782. \code{Module} node to mark the top of the whole program:
  783. \[
  784. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  785. \]
  786. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  787. this case, a list of statements.
  788. %
  789. The \code{Module} class is defined as follows
  790. \begin{lstlisting}
  791. class Module:
  792. def __init__(self, body):
  793. self.body = body
  794. \end{lstlisting}
  795. where \code{body} is a list of statements.
  796. \fi}
  797. It is common to have many grammar rules with the same left-hand side
  798. but different right-hand sides, such as the rules for $\Exp$ in the
  799. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  800. combine several right-hand-sides into a single rule.
  801. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  802. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  803. defined in Figure~\ref{fig:r0-concrete-syntax}.
  804. \racket{The \code{read-program} function provided in
  805. \code{utilities.rkt} of the support code reads a program in from a
  806. file (the sequence of characters in the concrete syntax of Racket)
  807. and parses it into an abstract syntax tree. See the description of
  808. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  809. details.}
  810. \python{The \code{parse} function in Python's \code{ast} module
  811. converts the concrete syntax (represented as a string) into an
  812. abstract syntax tree.}
  813. \newcommand{\LintGrammarRacket}{
  814. \begin{array}{rcl}
  815. \Type &::=& \key{Integer} \\
  816. \Exp{} &::=& \Int{} \MID \CREAD \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  817. \MID \CSUB{\Exp}{\Exp}
  818. \end{array}
  819. }
  820. \newcommand{\LintASTRacket}{
  821. \begin{array}{rcl}
  822. \Type &::=& \key{Integer} \\
  823. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  824. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  825. \end{array}
  826. }
  827. \newcommand{\LintGrammarPython}{
  828. \begin{array}{rcl}
  829. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  830. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  831. \end{array}
  832. }
  833. \newcommand{\LintASTPython}{
  834. \begin{array}{rcl}
  835. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  836. \itm{unaryop} &::= & \code{USub()} \\
  837. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  838. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  839. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  840. \end{array}
  841. }
  842. \begin{figure}[tp]
  843. \fbox{
  844. \begin{minipage}{0.96\textwidth}
  845. {\if\edition\racketEd
  846. \[
  847. \begin{array}{l}
  848. \LintGrammarRacket \\
  849. \begin{array}{rcl}
  850. \LangInt{} &::=& \Exp
  851. \end{array}
  852. \end{array}
  853. \]
  854. \fi}
  855. {\if\edition\pythonEd
  856. \[
  857. \begin{array}{l}
  858. \LintGrammarPython \\
  859. \begin{array}{rcl}
  860. \LangInt{} &::=& \Stmt^{*}
  861. \end{array}
  862. \end{array}
  863. \]
  864. \fi}
  865. \end{minipage}
  866. }
  867. \caption{The concrete syntax of \LangInt{}.}
  868. \label{fig:r0-concrete-syntax}
  869. \end{figure}
  870. \begin{figure}[tp]
  871. \fbox{
  872. \begin{minipage}{0.96\textwidth}
  873. {\if\edition\racketEd
  874. \[
  875. \begin{array}{l}
  876. \LintASTRacket{} \\
  877. \begin{array}{rcl}
  878. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  879. \end{array}
  880. \end{array}
  881. \]
  882. \fi}
  883. {\if\edition\pythonEd
  884. \[
  885. \begin{array}{l}
  886. \LintASTPython\\
  887. \begin{array}{rcl}
  888. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  889. \end{array}
  890. \end{array}
  891. \]
  892. \fi}
  893. \end{minipage}
  894. }
  895. \caption{The abstract syntax of \LangInt{}.}
  896. \label{fig:r0-syntax}
  897. \end{figure}
  898. \section{Pattern Matching}
  899. \label{sec:pattern-matching}
  900. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  901. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  902. \texttt{match} feature to access the parts of a value.
  903. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  904. \begin{center}
  905. \begin{minipage}{0.5\textwidth}
  906. {\if\edition\racketEd
  907. \begin{lstlisting}
  908. (match ast1_1
  909. [(Prim op (list child1 child2))
  910. (print op)])
  911. \end{lstlisting}
  912. \fi}
  913. {\if\edition\pythonEd
  914. \begin{lstlisting}
  915. match ast1_1:
  916. case BinOp(child1, op, child2):
  917. print(op)
  918. \end{lstlisting}
  919. \fi}
  920. \end{minipage}
  921. \end{center}
  922. {\if\edition\racketEd
  923. %
  924. In the above example, the \texttt{match} form checks whether the AST
  925. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  926. three pattern variables \texttt{op}, \texttt{child1}, and
  927. \texttt{child2}. In general, a match clause consists of a
  928. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  929. recursively defined to be either a pattern variable, a structure name
  930. followed by a pattern for each of the structure's arguments, or an
  931. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  932. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  933. and Chapter 9 of The Racket
  934. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  935. for complete descriptions of \code{match}.)
  936. %
  937. The body of a match clause may contain arbitrary Racket code. The
  938. pattern variables can be used in the scope of the body, such as
  939. \code{op} in \code{(print op)}.
  940. %
  941. \fi}
  942. %
  943. %
  944. {\if\edition\pythonEd
  945. %
  946. In the above example, the \texttt{match} form checks whether the AST
  947. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  948. three pattern variables \texttt{child1}, \texttt{op}, and
  949. \texttt{child2}, and then prints out the operator. In general, each
  950. \code{case} consists of a \emph{pattern} and a
  951. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  952. to be either a pattern variable, a class name followed by a pattern
  953. for each of its constructor's arguments, or other literals such as
  954. strings, lists, etc.
  955. %
  956. The body of each \code{case} may contain arbitrary Python code. The
  957. pattern variables can be used in the body, such as \code{op} in
  958. \code{print(op)}.
  959. %
  960. \fi}
  961. A \code{match} form may contain several clauses, as in the following
  962. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  963. the AST. The \code{match} proceeds through the clauses in order,
  964. checking whether the pattern can match the input AST. The body of the
  965. first clause that matches is executed. The output of \code{leaf} for
  966. several ASTs is shown on the right.
  967. \begin{center}
  968. \begin{minipage}{0.6\textwidth}
  969. {\if\edition\racketEd
  970. \begin{lstlisting}
  971. (define (leaf arith)
  972. (match arith
  973. [(Int n) #t]
  974. [(Prim 'read '()) #t]
  975. [(Prim '- (list e1)) #f]
  976. [(Prim '+ (list e1 e2)) #f]
  977. [(Prim '- (list e1 e2)) #f]))
  978. (leaf (Prim 'read '()))
  979. (leaf (Prim '- (list (Int 8))))
  980. (leaf (Int 8))
  981. \end{lstlisting}
  982. \fi}
  983. {\if\edition\pythonEd
  984. \begin{lstlisting}
  985. def leaf(arith):
  986. match arith:
  987. case Constant(n):
  988. return True
  989. case Call(Name('input_int'), []):
  990. return True
  991. case UnaryOp(USub(), e1):
  992. return False
  993. case BinOp(e1, Add(), e2):
  994. return False
  995. case BinOp(e1, Sub(), e2):
  996. return False
  997. print(leaf(Call(Name('input_int'), [])))
  998. print(leaf(UnaryOp(USub(), eight)))
  999. print(leaf(Constant(8)))
  1000. \end{lstlisting}
  1001. \fi}
  1002. \end{minipage}
  1003. \vrule
  1004. \begin{minipage}{0.25\textwidth}
  1005. {\if\edition\racketEd
  1006. \begin{lstlisting}
  1007. #t
  1008. #f
  1009. #t
  1010. \end{lstlisting}
  1011. \fi}
  1012. {\if\edition\pythonEd
  1013. \begin{lstlisting}
  1014. True
  1015. False
  1016. True
  1017. \end{lstlisting}
  1018. \fi}
  1019. \end{minipage}
  1020. \end{center}
  1021. When constructing a \code{match} expression, we refer to the grammar
  1022. definition to identify which non-terminal we are expecting to match
  1023. against, then we make sure that 1) we have one
  1024. \racket{clause}\python{case} for each alternative of that non-terminal
  1025. and 2) that the pattern in each \racket{clause}\python{case}
  1026. corresponds to the corresponding right-hand side of a grammar
  1027. rule. For the \code{match} in the \code{leaf} function, we refer to
  1028. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1029. non-terminal has 4 alternatives, so the \code{match} has 4
  1030. \racket{clauses}\python{cases}. The pattern in each
  1031. \racket{clause}\python{case} corresponds to the right-hand side of a
  1032. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1033. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1034. translating from grammars to patterns, replace non-terminals such as
  1035. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1036. \code{e2}).
  1037. \section{Recursive Functions}
  1038. \label{sec:recursion}
  1039. \index{subject}{recursive function}
  1040. Programs are inherently recursive. For example, an expression is often
  1041. made of smaller expressions. Thus, the natural way to process an
  1042. entire program is with a recursive function. As a first example of
  1043. such a recursive function, we define the function \code{is\_exp} in
  1044. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1045. determines whether or not it is an expression in \LangInt{}.
  1046. %
  1047. We say that a function is defined by \emph{structural recursion} when
  1048. it is defined using a sequence of match \racket{clauses}\python{cases}
  1049. that correspond to a grammar, and the body of each
  1050. \racket{clause}\python{case} makes a recursive call on each child
  1051. node.\footnote{This principle of structuring code according to the
  1052. data definition is advocated in the book \emph{How to Design
  1053. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1054. second function, named \code{stmt}, that recognizes whether a value
  1055. is a \LangInt{} statement.} \python{Finally, }
  1056. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1057. which determines whether an AST is a program in \LangInt{}. In
  1058. general we can write one recursive function to handle each
  1059. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1060. two examples at the bottom of the figure, the first is in
  1061. \LangInt{} and the second is not.
  1062. \begin{figure}[tp]
  1063. {\if\edition\racketEd
  1064. \begin{lstlisting}[frame=single]
  1065. (define (is_exp ast)
  1066. (match ast
  1067. [(Int n) #t]
  1068. [(Prim 'read '()) #t]
  1069. [(Prim '- (list e)) (is_exp e)]
  1070. [(Prim '+ (list e1 e2))
  1071. (and (is_exp e1) (is_exp e2))]
  1072. [(Prim '- (list e1 e2))
  1073. (and (is_exp e1) (is_exp e2))]
  1074. [else #f]))
  1075. (define (is_Lint ast)
  1076. (match ast
  1077. [(Program '() e) (is_exp e)]
  1078. [else #f]))
  1079. (is_Lint (Program '() ast1_1)
  1080. (is_Lint (Program '()
  1081. (Prim '* (list (Prim 'read '())
  1082. (Prim '+ (list (Int 8)))))))
  1083. \end{lstlisting}
  1084. \fi}
  1085. {\if\edition\pythonEd
  1086. \begin{lstlisting}[frame=single]
  1087. def is_exp(e):
  1088. match e:
  1089. case Constant(n):
  1090. return True
  1091. case Call(Name('input_int'), []):
  1092. return True
  1093. case UnaryOp(USub(), e1):
  1094. return is_exp(e1)
  1095. case BinOp(e1, Add(), e2):
  1096. return is_exp(e1) and is_exp(e2)
  1097. case BinOp(e1, Sub(), e2):
  1098. return is_exp(e1) and is_exp(e2)
  1099. case _:
  1100. return False
  1101. def stmt(s):
  1102. match s:
  1103. case Expr(Call(Name('print'), [e])):
  1104. return is_exp(e)
  1105. case Expr(e):
  1106. return is_exp(e)
  1107. case _:
  1108. return False
  1109. def is_Lint(p):
  1110. match p:
  1111. case Module(body):
  1112. return all([stmt(s) for s in body])
  1113. case _:
  1114. return False
  1115. print(is_Lint(Module([Expr(ast1_1)])))
  1116. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1117. UnaryOp(Add(), Constant(8))))])))
  1118. \end{lstlisting}
  1119. \fi}
  1120. \caption{Example of recursive functions for \LangInt{}. These functions
  1121. recognize whether an AST is in \LangInt{}.}
  1122. \label{fig:exp-predicate}
  1123. \end{figure}
  1124. %% You may be tempted to merge the two functions into one, like this:
  1125. %% \begin{center}
  1126. %% \begin{minipage}{0.5\textwidth}
  1127. %% \begin{lstlisting}
  1128. %% (define (Lint ast)
  1129. %% (match ast
  1130. %% [(Int n) #t]
  1131. %% [(Prim 'read '()) #t]
  1132. %% [(Prim '- (list e)) (Lint e)]
  1133. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1134. %% [(Program '() e) (Lint e)]
  1135. %% [else #f]))
  1136. %% \end{lstlisting}
  1137. %% \end{minipage}
  1138. %% \end{center}
  1139. %% %
  1140. %% Sometimes such a trick will save a few lines of code, especially when
  1141. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1142. %% \emph{not} recommended because it can get you into trouble.
  1143. %% %
  1144. %% For example, the above function is subtly wrong:
  1145. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1146. %% returns true when it should return false.
  1147. \section{Interpreters}
  1148. \label{sec:interp_Lint}
  1149. \index{subject}{interpreter}
  1150. The behavior of a program is defined by the specification of the
  1151. programming language.
  1152. %
  1153. \racket{For example, the Scheme language is defined in the report by
  1154. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1155. reference manual~\citep{plt-tr}.}
  1156. %
  1157. \python{For example, the Python language is defined in the Python
  1158. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1159. %
  1160. In this book we use interpreters to specify each language that we
  1161. consider. An interpreter that is designated as the definition of a
  1162. language is called a \emph{definitional
  1163. interpreter}~\citep{reynolds72:_def_interp}.
  1164. \index{subject}{definitional interpreter} We warm up by creating a
  1165. definitional interpreter for the \LangInt{} language. This interpreter
  1166. serves as a second example of structural recursion. The
  1167. \code{interp\_Lint} function is defined in
  1168. Figure~\ref{fig:interp_Lint}.
  1169. %
  1170. \racket{The body of the function is a match on the input program
  1171. followed by a call to the \lstinline{interp_exp} helper function,
  1172. which in turn has one match clause per grammar rule for \LangInt{}
  1173. expressions.}
  1174. %
  1175. \python{The body of the function matches on the \code{Module} AST node
  1176. and then invokes \code{interp\_stmt} on each statement in the
  1177. module. The \code{interp\_stmt} function includes a case for each
  1178. grammar rule of the \Stmt{} non-terminal and it calls
  1179. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1180. function includes a case for each grammar rule of the \Exp{}
  1181. non-terminal.}
  1182. \begin{figure}[tp]
  1183. {\if\edition\racketEd
  1184. \begin{lstlisting}[frame=single]
  1185. (define (interp_exp e)
  1186. (match e
  1187. [(Int n) n]
  1188. [(Prim 'read '())
  1189. (define r (read))
  1190. (cond [(fixnum? r) r]
  1191. [else (error 'interp_exp "read expected an integer" r)])]
  1192. [(Prim '- (list e))
  1193. (define v (interp_exp e))
  1194. (fx- 0 v)]
  1195. [(Prim '+ (list e1 e2))
  1196. (define v1 (interp_exp e1))
  1197. (define v2 (interp_exp e2))
  1198. (fx+ v1 v2)]
  1199. [(Prim '- (list e1 e2))
  1200. (define v1 ((interp-exp env) e1))
  1201. (define v2 ((interp-exp env) e2))
  1202. (fx- v1 v2)]))
  1203. (define (interp_Lint p)
  1204. (match p
  1205. [(Program '() e) (interp_exp e)]))
  1206. \end{lstlisting}
  1207. \fi}
  1208. {\if\edition\pythonEd
  1209. \begin{lstlisting}[frame=single]
  1210. def interp_exp(e):
  1211. match e:
  1212. case BinOp(left, Add(), right):
  1213. l = interp_exp(left); r = interp_exp(right)
  1214. return l + r
  1215. case BinOp(left, Sub(), right):
  1216. l = interp_exp(left); r = interp_exp(right)
  1217. return l - r
  1218. case UnaryOp(USub(), v):
  1219. return - interp_exp(v)
  1220. case Constant(value):
  1221. return value
  1222. case Call(Name('input_int'), []):
  1223. return int(input())
  1224. def interp_stmt(s):
  1225. match s:
  1226. case Expr(Call(Name('print'), [arg])):
  1227. print(interp_exp(arg))
  1228. case Expr(value):
  1229. interp_exp(value)
  1230. def interp_Lint(p):
  1231. match p:
  1232. case Module(body):
  1233. for s in body:
  1234. interp_stmt(s)
  1235. \end{lstlisting}
  1236. \fi}
  1237. \caption{Interpreter for the \LangInt{} language.}
  1238. \label{fig:interp_Lint}
  1239. \end{figure}
  1240. Let us consider the result of interpreting a few \LangInt{} programs. The
  1241. following program adds two integers.
  1242. {\if\edition\racketEd
  1243. \begin{lstlisting}
  1244. (+ 10 32)
  1245. \end{lstlisting}
  1246. \fi}
  1247. {\if\edition\pythonEd
  1248. \begin{lstlisting}
  1249. print(10 + 32)
  1250. \end{lstlisting}
  1251. \fi}
  1252. %
  1253. \noindent The result is \key{42}, the answer to life, the universe,
  1254. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1255. the Galaxy} by Douglas Adams.}
  1256. %
  1257. We wrote the above program in concrete syntax whereas the parsed
  1258. abstract syntax is:
  1259. {\if\edition\racketEd
  1260. \begin{lstlisting}
  1261. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1262. \end{lstlisting}
  1263. \fi}
  1264. {\if\edition\pythonEd
  1265. \begin{lstlisting}
  1266. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1267. \end{lstlisting}
  1268. \fi}
  1269. The next example demonstrates that expressions may be nested within
  1270. each other, in this case nesting several additions and negations.
  1271. {\if\edition\racketEd
  1272. \begin{lstlisting}
  1273. (+ 10 (- (+ 12 20)))
  1274. \end{lstlisting}
  1275. \fi}
  1276. {\if\edition\pythonEd
  1277. \begin{lstlisting}
  1278. print(10 + -(12 + 20))
  1279. \end{lstlisting}
  1280. \fi}
  1281. %
  1282. \noindent What is the result of the above program?
  1283. {\if\edition\racketEd
  1284. As mentioned previously, the \LangInt{} language does not support
  1285. arbitrarily-large integers, but only $63$-bit integers, so we
  1286. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1287. in Racket.
  1288. Suppose
  1289. \[
  1290. n = 999999999999999999
  1291. \]
  1292. which indeed fits in $63$-bits. What happens when we run the
  1293. following program in our interpreter?
  1294. \begin{lstlisting}
  1295. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1296. \end{lstlisting}
  1297. It produces an error:
  1298. \begin{lstlisting}
  1299. fx+: result is not a fixnum
  1300. \end{lstlisting}
  1301. We establish the convention that if running the definitional
  1302. interpreter on a program produces an error then the meaning of that
  1303. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1304. error is a \code{trapped-error}. A compiler for the language is under
  1305. no obligations regarding programs with unspecified behavior; it does
  1306. not have to produce an executable, and if it does, that executable can
  1307. do anything. On the other hand, if the error is a
  1308. \code{trapped-error}, then the compiler must produce an executable and
  1309. it is required to report that an error occurred. To signal an error,
  1310. exit with a return code of \code{255}. The interpreters in chapters
  1311. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1312. \code{trapped-error}.
  1313. \fi}
  1314. % TODO: how to deal with too-large integers in the Python interpreter?
  1315. %% This convention applies to the languages defined in this
  1316. %% book, as a way to simplify the student's task of implementing them,
  1317. %% but this convention is not applicable to all programming languages.
  1318. %%
  1319. Moving on to the last feature of the \LangInt{} language, the
  1320. \READOP{} operation prompts the user of the program for an integer.
  1321. Recall that program \eqref{eq:arith-prog} requests an integer input
  1322. and then subtracts \code{8}. So if we run
  1323. {\if\edition\racketEd
  1324. \begin{lstlisting}
  1325. (interp_Lint (Program '() ast1_1))
  1326. \end{lstlisting}
  1327. \fi}
  1328. {\if\edition\pythonEd
  1329. \begin{lstlisting}
  1330. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1331. \end{lstlisting}
  1332. \fi}
  1333. \noindent and if the input is \code{50}, the result is \code{42}.
  1334. We include the \READOP{} operation in \LangInt{} so a clever student
  1335. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1336. during compilation to obtain the output and then generates the trivial
  1337. code to produce the output.\footnote{Yes, a clever student did this in the
  1338. first instance of this course!}
  1339. The job of a compiler is to translate a program in one language into a
  1340. program in another language so that the output program behaves the
  1341. same way as the input program. This idea is depicted in the
  1342. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1343. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1344. Given a compiler that translates from language $\mathcal{L}_1$ to
  1345. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1346. compiler must translate it into some program $P_2$ such that
  1347. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1348. same input $i$ yields the same output $o$.
  1349. \begin{equation} \label{eq:compile-correct}
  1350. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1351. \node (p1) at (0, 0) {$P_1$};
  1352. \node (p2) at (3, 0) {$P_2$};
  1353. \node (o) at (3, -2.5) {$o$};
  1354. \path[->] (p1) edge [above] node {compile} (p2);
  1355. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1356. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1357. \end{tikzpicture}
  1358. \end{equation}
  1359. In the next section we see our first example of a compiler.
  1360. \section{Example Compiler: a Partial Evaluator}
  1361. \label{sec:partial-evaluation}
  1362. In this section we consider a compiler that translates \LangInt{}
  1363. programs into \LangInt{} programs that may be more efficient. The
  1364. compiler eagerly computes the parts of the program that do not depend
  1365. on any inputs, a process known as \emph{partial
  1366. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1367. For example, given the following program
  1368. {\if\edition\racketEd
  1369. \begin{lstlisting}
  1370. (+ (read) (- (+ 5 3)))
  1371. \end{lstlisting}
  1372. \fi}
  1373. {\if\edition\pythonEd
  1374. \begin{lstlisting}
  1375. print(input_int() + -(5 + 3) )
  1376. \end{lstlisting}
  1377. \fi}
  1378. \noindent our compiler translates it into the program
  1379. {\if\edition\racketEd
  1380. \begin{lstlisting}
  1381. (+ (read) -8)
  1382. \end{lstlisting}
  1383. \fi}
  1384. {\if\edition\pythonEd
  1385. \begin{lstlisting}
  1386. print(input_int() + -8)
  1387. \end{lstlisting}
  1388. \fi}
  1389. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1390. evaluator for the \LangInt{} language. The output of the partial evaluator
  1391. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1392. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1393. whereas the code for partially evaluating the negation and addition
  1394. operations is factored into three auxiliary functions:
  1395. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1396. functions is the output of partially evaluating the children.
  1397. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1398. arguments are integers and if they are, perform the appropriate
  1399. arithmetic. Otherwise, they create an AST node for the arithmetic
  1400. operation.
  1401. \begin{figure}[tp]
  1402. {\if\edition\racketEd
  1403. \begin{lstlisting}[frame=single]
  1404. (define (pe_neg r)
  1405. (match r
  1406. [(Int n) (Int (fx- 0 n))]
  1407. [else (Prim '- (list r))]))
  1408. (define (pe_add r1 r2)
  1409. (match* (r1 r2)
  1410. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1411. [(_ _) (Prim '+ (list r1 r2))]))
  1412. (define (pe_sub r1 r2)
  1413. (match* (r1 r2)
  1414. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1415. [(_ _) (Prim '- (list r1 r2))]))
  1416. (define (pe_exp e)
  1417. (match e
  1418. [(Int n) (Int n)]
  1419. [(Prim 'read '()) (Prim 'read '())]
  1420. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1421. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1422. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1423. (define (pe_Lint p)
  1424. (match p
  1425. [(Program '() e) (Program '() (pe_exp e))]))
  1426. \end{lstlisting}
  1427. \fi}
  1428. {\if\edition\pythonEd
  1429. \begin{lstlisting}[frame=single]
  1430. def pe_neg(r):
  1431. match r:
  1432. case Constant(n):
  1433. return Constant(-n)
  1434. case _:
  1435. return UnaryOp(USub(), r)
  1436. def pe_add(r1, r2):
  1437. match (r1, r2):
  1438. case (Constant(n1), Constant(n2)):
  1439. return Constant(n1 + n2)
  1440. case _:
  1441. return BinOp(r1, Add(), r2)
  1442. def pe_sub(r1, r2):
  1443. match (r1, r2):
  1444. case (Constant(n1), Constant(n2)):
  1445. return Constant(n1 - n2)
  1446. case _:
  1447. return BinOp(r1, Sub(), r2)
  1448. def pe_exp(e):
  1449. match e:
  1450. case BinOp(left, Add(), right):
  1451. return pe_add(pe_exp(left), pe_exp(right))
  1452. case BinOp(left, Sub(), right):
  1453. return pe_sub(pe_exp(left), pe_exp(right))
  1454. case UnaryOp(USub(), v):
  1455. return pe_neg(pe_exp(v))
  1456. case Constant(value):
  1457. return e
  1458. case Call(Name('input_int'), []):
  1459. return e
  1460. def pe_stmt(s):
  1461. match s:
  1462. case Expr(Call(Name('print'), [arg])):
  1463. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1464. case Expr(value):
  1465. return Expr(pe_exp(value))
  1466. def pe_P_int(p):
  1467. match p:
  1468. case Module(body):
  1469. new_body = [pe_stmt(s) for s in body]
  1470. return Module(new_body)
  1471. \end{lstlisting}
  1472. \fi}
  1473. \caption{A partial evaluator for \LangInt{}.}
  1474. \label{fig:pe-arith}
  1475. \end{figure}
  1476. To gain some confidence that the partial evaluator is correct, we can
  1477. test whether it produces programs that produce the same result as the
  1478. input programs. That is, we can test whether it satisfies Diagram
  1479. \ref{eq:compile-correct}.
  1480. %
  1481. {\if\edition\racketEd
  1482. The following code runs the partial evaluator on several examples and
  1483. tests the output program. The \texttt{parse-program} and
  1484. \texttt{assert} functions are defined in
  1485. Appendix~\ref{appendix:utilities}.\\
  1486. \begin{minipage}{1.0\textwidth}
  1487. \begin{lstlisting}
  1488. (define (test_pe p)
  1489. (assert "testing pe_Lint"
  1490. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1491. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1492. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1493. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1494. \end{lstlisting}
  1495. \end{minipage}
  1496. \fi}
  1497. % TODO: python version of testing the PE
  1498. \begin{exercise}\normalfont\normalsize
  1499. Create three programs in the \LangInt{} language and test whether
  1500. partially evaluating them with \code{pe\_Lint} and then
  1501. interpreting them with \code{interp\_Lint} gives the same result
  1502. as directly interpreting them with \code{interp\_Lint}.
  1503. \end{exercise}
  1504. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1505. \chapter{Integers and Variables}
  1506. \label{ch:Lvar}
  1507. This chapter is about compiling a subset of
  1508. \racket{Racket}\python{Python} to x86-64 assembly
  1509. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1510. integer arithmetic and local variables. We often refer to x86-64
  1511. simply as x86. The chapter begins with a description of the
  1512. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1513. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1514. large so we discuss only the instructions needed for compiling
  1515. \LangVar{}. We introduce more x86 instructions in later chapters.
  1516. After introducing \LangVar{} and x86, we reflect on their differences
  1517. and come up with a plan to break down the translation from \LangVar{}
  1518. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1519. rest of the sections in this chapter give detailed hints regarding
  1520. each step. We hope to give enough hints that the well-prepared
  1521. reader, together with a few friends, can implement a compiler from
  1522. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1523. the scale of this first compiler, the instructor solution for the
  1524. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1525. code.
  1526. \section{The \LangVar{} Language}
  1527. \label{sec:s0}
  1528. \index{subject}{variable}
  1529. The \LangVar{} language extends the \LangInt{} language with
  1530. variables. The concrete syntax of the \LangVar{} language is defined
  1531. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1532. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1533. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1534. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1535. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1536. syntax of \LangVar{} includes the \racket{\key{Program}
  1537. struct}\python{\key{Module} instance} to mark the top of the
  1538. program.
  1539. %% The $\itm{info}$
  1540. %% field of the \key{Program} structure contains an \emph{association
  1541. %% list} (a list of key-value pairs) that is used to communicate
  1542. %% auxiliary data from one compiler pass the next.
  1543. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1544. exhibit several compilation techniques.
  1545. \newcommand{\LvarGrammarRacket}{
  1546. \begin{array}{rcl}
  1547. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1548. \end{array}
  1549. }
  1550. \newcommand{\LvarASTRacket}{
  1551. \begin{array}{rcl}
  1552. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1553. \end{array}
  1554. }
  1555. \newcommand{\LvarGrammarPython}{
  1556. \begin{array}{rcl}
  1557. \Exp &::=& \Var{} \\
  1558. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1559. \end{array}
  1560. }
  1561. \newcommand{\LvarASTPython}{
  1562. \begin{array}{rcl}
  1563. \Exp{} &::=& \VAR{\Var{}} \\
  1564. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1565. \end{array}
  1566. }
  1567. \begin{figure}[tp]
  1568. \centering
  1569. \fbox{
  1570. \begin{minipage}{0.96\textwidth}
  1571. {\if\edition\racketEd
  1572. \[
  1573. \begin{array}{l}
  1574. \gray{\LintGrammarRacket{}} \\ \hline
  1575. \LvarGrammarRacket{} \\
  1576. \begin{array}{rcl}
  1577. \LangVarM{} &::=& \Exp
  1578. \end{array}
  1579. \end{array}
  1580. \]
  1581. \fi}
  1582. {\if\edition\pythonEd
  1583. \[
  1584. \begin{array}{l}
  1585. \gray{\LintGrammarPython} \\ \hline
  1586. \LvarGrammarPython \\
  1587. \begin{array}{rcl}
  1588. \LangVarM{} &::=& \Stmt^{*}
  1589. \end{array}
  1590. \end{array}
  1591. \]
  1592. \fi}
  1593. \end{minipage}
  1594. }
  1595. \caption{The concrete syntax of \LangVar{}.}
  1596. \label{fig:Lvar-concrete-syntax}
  1597. \end{figure}
  1598. \begin{figure}[tp]
  1599. \centering
  1600. \fbox{
  1601. \begin{minipage}{0.96\textwidth}
  1602. {\if\edition\racketEd
  1603. \[
  1604. \begin{array}{l}
  1605. \gray{\LintASTRacket{}} \\ \hline
  1606. \LvarASTRacket \\
  1607. \begin{array}{rcl}
  1608. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1609. \end{array}
  1610. \end{array}
  1611. \]
  1612. \fi}
  1613. {\if\edition\pythonEd
  1614. \[
  1615. \begin{array}{l}
  1616. \gray{\LintASTPython}\\ \hline
  1617. \LvarASTPython \\
  1618. \begin{array}{rcl}
  1619. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1620. \end{array}
  1621. \end{array}
  1622. \]
  1623. \fi}
  1624. \end{minipage}
  1625. }
  1626. \caption{The abstract syntax of \LangVar{}.}
  1627. \label{fig:Lvar-syntax}
  1628. \end{figure}
  1629. {\if\edition\racketEd
  1630. Let us dive further into the syntax and semantics of the \LangVar{}
  1631. language. The \key{let} feature defines a variable for use within its
  1632. body and initializes the variable with the value of an expression.
  1633. The abstract syntax for \key{let} is defined in
  1634. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1635. \begin{lstlisting}
  1636. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1637. \end{lstlisting}
  1638. For example, the following program initializes \code{x} to $32$ and then
  1639. evaluates the body \code{(+ 10 x)}, producing $42$.
  1640. \begin{lstlisting}
  1641. (let ([x (+ 12 20)]) (+ 10 x))
  1642. \end{lstlisting}
  1643. \fi}
  1644. %
  1645. {\if\edition\pythonEd
  1646. %
  1647. The \LangVar{} language includes assignment statements, which define a
  1648. variable for use in later statements and initializes the variable with
  1649. the value of an expression. The abstract syntax for assignment is
  1650. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1651. assignment is
  1652. \begin{lstlisting}
  1653. |$\itm{var}$| = |$\itm{exp}$|
  1654. \end{lstlisting}
  1655. For example, the following program initializes the variable \code{x}
  1656. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1657. \begin{lstlisting}
  1658. x = 12 + 20
  1659. print(10 + x)
  1660. \end{lstlisting}
  1661. \fi}
  1662. {\if\edition\racketEd
  1663. %
  1664. When there are multiple \key{let}'s for the same variable, the closest
  1665. enclosing \key{let} is used. That is, variable definitions overshadow
  1666. prior definitions. Consider the following program with two \key{let}'s
  1667. that define two variables named \code{x}. Can you figure out the
  1668. result?
  1669. \begin{lstlisting}
  1670. (let ([x 32]) (+ (let ([x 10]) x) x))
  1671. \end{lstlisting}
  1672. For the purposes of depicting which variable occurrences correspond to
  1673. which definitions, the following shows the \code{x}'s annotated with
  1674. subscripts to distinguish them. Double check that your answer for the
  1675. above is the same as your answer for this annotated version of the
  1676. program.
  1677. \begin{lstlisting}
  1678. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1679. \end{lstlisting}
  1680. The initializing expression is always evaluated before the body of the
  1681. \key{let}, so in the following, the \key{read} for \code{x} is
  1682. performed before the \key{read} for \code{y}. Given the input
  1683. $52$ then $10$, the following produces $42$ (not $-42$).
  1684. \begin{lstlisting}
  1685. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1686. \end{lstlisting}
  1687. \fi}
  1688. \subsection{Extensible Interpreters via Method Overriding}
  1689. \label{sec:extensible-interp}
  1690. To prepare for discussing the interpreter of \LangVar{}, we explain
  1691. why we implement it in an object-oriented style. Throughout this book
  1692. we define many interpreters, one for each of language that we
  1693. study. Because each language builds on the prior one, there is a lot
  1694. of commonality between these interpreters. We want to write down the
  1695. common parts just once instead of many times. A naive
  1696. interpreter for \LangVar{} would handle the
  1697. \racket{cases for variables and \code{let}}
  1698. \python{case for variables}
  1699. but dispatch to an interpreter for \LangInt{}
  1700. in the rest of the cases. The following code sketches this idea. (We
  1701. explain the \code{env} parameter soon, in
  1702. Section~\ref{sec:interp-Lvar}.)
  1703. \begin{center}
  1704. {\if\edition\racketEd
  1705. \begin{minipage}{0.45\textwidth}
  1706. \begin{lstlisting}
  1707. (define ((interp_Lint env) e)
  1708. (match e
  1709. [(Prim '- (list e1))
  1710. (fx- 0 ((interp_Lint env) e1))]
  1711. ...))
  1712. \end{lstlisting}
  1713. \end{minipage}
  1714. \begin{minipage}{0.45\textwidth}
  1715. \begin{lstlisting}
  1716. (define ((interp_Lvar env) e)
  1717. (match e
  1718. [(Var x)
  1719. (dict-ref env x)]
  1720. [(Let x e body)
  1721. (define v ((interp_exp env) e))
  1722. (define env^ (dict-set env x v))
  1723. ((interp_exp env^) body)]
  1724. [else ((interp_Lint env) e)]))
  1725. \end{lstlisting}
  1726. \end{minipage}
  1727. \fi}
  1728. {\if\edition\pythonEd
  1729. \begin{minipage}{0.45\textwidth}
  1730. \begin{lstlisting}
  1731. def interp_Lint(e, env):
  1732. match e:
  1733. case UnaryOp(USub(), e1):
  1734. return - interp_Lint(e1, env)
  1735. ...
  1736. \end{lstlisting}
  1737. \end{minipage}
  1738. \begin{minipage}{0.45\textwidth}
  1739. \begin{lstlisting}
  1740. def interp_Lvar(e, env):
  1741. match e:
  1742. case Name(id):
  1743. return env[id]
  1744. case _:
  1745. return interp_Lint(e, env)
  1746. \end{lstlisting}
  1747. \end{minipage}
  1748. \fi}
  1749. \end{center}
  1750. The problem with this naive approach is that it does not handle
  1751. situations in which an \LangVar{} feature, such as a variable, is
  1752. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1753. the following program.
  1754. %
  1755. {\if\edition\racketEd
  1756. \begin{lstlisting}
  1757. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1758. \end{lstlisting}
  1759. \fi}
  1760. {\if\edition\pythonEd
  1761. \begin{lstlisting}
  1762. y = 10
  1763. print(-y)
  1764. \end{lstlisting}
  1765. \fi}
  1766. %
  1767. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1768. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1769. then it recursively calls \code{interp\_Lint} again on its argument.
  1770. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1771. an error!
  1772. To make our interpreters extensible we need something called
  1773. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1774. recursive knot is delayed to when the functions are
  1775. composed. Object-oriented languages provide open recursion via
  1776. method overriding\index{subject}{method overriding}. The
  1777. following code uses method overriding to interpret \LangInt{} and
  1778. \LangVar{} using
  1779. %
  1780. \racket{the
  1781. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1782. \index{subject}{class} feature of Racket.}
  1783. %
  1784. \python{a Python \code{class} definition.}
  1785. %
  1786. We define one class for each language and define a method for
  1787. interpreting expressions inside each class. The class for \LangVar{}
  1788. inherits from the class for \LangInt{} and the method
  1789. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1790. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1791. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1792. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1793. \code{interp\_exp} in \LangInt{}.
  1794. \begin{center}
  1795. \hspace{-20pt}
  1796. {\if\edition\racketEd
  1797. \begin{minipage}{0.45\textwidth}
  1798. \begin{lstlisting}
  1799. (define interp-Lint-class
  1800. (class object%
  1801. (define/public ((interp_exp env) e)
  1802. (match e
  1803. [(Prim '- (list e))
  1804. (fx- 0 ((interp_exp env) e))]
  1805. ...))
  1806. ...))
  1807. \end{lstlisting}
  1808. \end{minipage}
  1809. \begin{minipage}{0.45\textwidth}
  1810. \begin{lstlisting}
  1811. (define interp-Lvar-class
  1812. (class interp-Lint-class
  1813. (define/override ((interp_exp env) e)
  1814. (match e
  1815. [(Var x)
  1816. (dict-ref env x)]
  1817. [(Let x e body)
  1818. (define v ((interp_exp env) e))
  1819. (define env^ (dict-set env x v))
  1820. ((interp_exp env^) body)]
  1821. [else
  1822. (super (interp_exp env) e)]))
  1823. ...
  1824. ))
  1825. \end{lstlisting}
  1826. \end{minipage}
  1827. \fi}
  1828. {\if\edition\pythonEd
  1829. \begin{minipage}{0.45\textwidth}
  1830. \begin{lstlisting}
  1831. class InterpLint:
  1832. def interp_exp(e):
  1833. match e:
  1834. case UnaryOp(USub(), e1):
  1835. return -self.interp_exp(e1)
  1836. ...
  1837. ...
  1838. \end{lstlisting}
  1839. \end{minipage}
  1840. \begin{minipage}{0.45\textwidth}
  1841. \begin{lstlisting}
  1842. def InterpLvar(InterpLint):
  1843. def interp_exp(e):
  1844. match e:
  1845. case Name(id):
  1846. return env[id]
  1847. case _:
  1848. return super().interp_exp(e)
  1849. ...
  1850. \end{lstlisting}
  1851. \end{minipage}
  1852. \fi}
  1853. \end{center}
  1854. Getting back to the troublesome example, repeated here:
  1855. {\if\edition\racketEd
  1856. \begin{lstlisting}
  1857. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1858. \end{lstlisting}
  1859. \fi}
  1860. {\if\edition\pythonEd
  1861. \begin{lstlisting}
  1862. y = 10
  1863. print(-y)
  1864. \end{lstlisting}
  1865. \fi}
  1866. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1867. \racket{on this expression,}
  1868. \python{on the \code{-y} expression,}
  1869. %
  1870. call it \code{e0}, by creating an object of the \LangVar{} class
  1871. and calling the \code{interp\_exp} method.
  1872. {\if\edition\racketEd
  1873. \begin{lstlisting}
  1874. ((send (new interp-Lvar-class) interp_exp '()) e0)
  1875. \end{lstlisting}
  1876. \fi}
  1877. {\if\edition\pythonEd
  1878. \begin{lstlisting}
  1879. InterpLvar().interp_exp(e0)
  1880. \end{lstlisting}
  1881. \fi}
  1882. \noindent To process the \code{-} operator, the default case of
  1883. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1884. method in \LangInt{}. But then for the recursive method call, it
  1885. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1886. \code{Var} node is handled correctly. Thus, method overriding gives us
  1887. the open recursion that we need to implement our interpreters in an
  1888. extensible way.
  1889. \subsection{Definitional Interpreter for \LangVar{}}
  1890. \label{sec:interp-Lvar}
  1891. {\if\edition\racketEd
  1892. \begin{figure}[tp]
  1893. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1894. \small
  1895. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1896. An \emph{association list} (alist) is a list of key-value pairs.
  1897. For example, we can map people to their ages with an alist.
  1898. \index{subject}{alist}\index{subject}{association list}
  1899. \begin{lstlisting}[basicstyle=\ttfamily]
  1900. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1901. \end{lstlisting}
  1902. The \emph{dictionary} interface is for mapping keys to values.
  1903. Every alist implements this interface. \index{subject}{dictionary} The package
  1904. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1905. provides many functions for working with dictionaries. Here
  1906. are a few of them:
  1907. \begin{description}
  1908. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1909. returns the value associated with the given $\itm{key}$.
  1910. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1911. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1912. but otherwise is the same as $\itm{dict}$.
  1913. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1914. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1915. of keys and values in $\itm{dict}$. For example, the following
  1916. creates a new alist in which the ages are incremented.
  1917. \end{description}
  1918. \vspace{-10pt}
  1919. \begin{lstlisting}[basicstyle=\ttfamily]
  1920. (for/list ([(k v) (in-dict ages)])
  1921. (cons k (add1 v)))
  1922. \end{lstlisting}
  1923. \end{tcolorbox}
  1924. %\end{wrapfigure}
  1925. \caption{Association lists implement the dictionary interface.}
  1926. \label{fig:alist}
  1927. \end{figure}
  1928. \fi}
  1929. Having justified the use of classes and methods to implement
  1930. interpreters, we revisit the definitional interpreter for \LangInt{}
  1931. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1932. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1933. interpreter for \LangVar{} adds two new \key{match} cases for
  1934. variables and \racket{\key{let}}\python{assignment}. For
  1935. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1936. value bound to a variable to all the uses of the variable. To
  1937. accomplish this, we maintain a mapping from variables to values
  1938. called an \emph{environment}\index{subject}{environment}.
  1939. %
  1940. We use
  1941. %
  1942. \racket{an association list (alist) }%
  1943. %
  1944. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1945. %
  1946. to represent the environment.
  1947. %
  1948. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1949. and the \code{racket/dict} package.}
  1950. %
  1951. The \code{interp\_exp} function takes the current environment,
  1952. \code{env}, as an extra parameter. When the interpreter encounters a
  1953. variable, it looks up the corresponding value in the dictionary.
  1954. %
  1955. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1956. initializing expression, extends the environment with the result
  1957. value bound to the variable, using \code{dict-set}, then evaluates
  1958. the body of the \key{Let}.}
  1959. %
  1960. \python{When the interpreter encounters an assignment, it evaluates
  1961. the initializing expression and then associates the resulting value
  1962. with the variable in the environment.}
  1963. \begin{figure}[tp]
  1964. {\if\edition\racketEd
  1965. \begin{lstlisting}[frame=single]
  1966. (define interp-Lint-class
  1967. (class object%
  1968. (super-new)
  1969. (define/public ((interp_exp env) e)
  1970. (match e
  1971. [(Int n) n]
  1972. [(Prim 'read '())
  1973. (define r (read))
  1974. (cond [(fixnum? r) r]
  1975. [else (error 'interp_exp "expected an integer" r)])]
  1976. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1977. [(Prim '+ (list e1 e2))
  1978. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1979. [(Prim '- (list e1 e2))
  1980. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1981. (define/public (interp_program p)
  1982. (match p
  1983. [(Program '() e) ((interp_exp '()) e)]))
  1984. ))
  1985. \end{lstlisting}
  1986. \fi}
  1987. {\if\edition\pythonEd
  1988. \begin{lstlisting}[frame=single]
  1989. class InterpLint:
  1990. def interp_exp(self, e, env):
  1991. match e:
  1992. case BinOp(left, Add(), right):
  1993. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1994. case BinOp(left, Sub(), right):
  1995. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1996. case UnaryOp(USub(), v):
  1997. return - self.interp_exp(v, env)
  1998. case Constant(value):
  1999. return value
  2000. case Call(Name('input_int'), []):
  2001. return int(input())
  2002. def interp_stmts(self, ss, env):
  2003. if len(ss) == 0:
  2004. return
  2005. match ss[0]:
  2006. case Expr(Call(Name('print'), [arg])):
  2007. print(self.interp_exp(arg, env), end='')
  2008. return self.interp_stmts(ss[1:], env)
  2009. case Expr(value):
  2010. self.interp_exp(value, env)
  2011. return self.interp_stmts(ss[1:], env)
  2012. def interp(self, p):
  2013. match p:
  2014. case Module(body):
  2015. self.interp_stmts(body, {})
  2016. def interp_Lint(p):
  2017. return InterpLint().interp(p)
  2018. \end{lstlisting}
  2019. \fi}
  2020. \caption{Interpreter for \LangInt{} as a class.}
  2021. \label{fig:interp-Lint-class}
  2022. \end{figure}
  2023. \begin{figure}[tp]
  2024. {\if\edition\racketEd
  2025. \begin{lstlisting}[frame=single]
  2026. (define interp-Lvar-class
  2027. (class interp-Lint-class
  2028. (super-new)
  2029. (define/override ((interp_exp env) e)
  2030. (match e
  2031. [(Var x) (dict-ref env x)]
  2032. [(Let x e body)
  2033. (define new-env (dict-set env x ((interp_exp env) e)))
  2034. ((interp_exp new-env) body)]
  2035. [else ((super interp-exp env) e)]))
  2036. ))
  2037. (define (interp_Lvar p)
  2038. (send (new interp-Lvar-class) interp_program p))
  2039. \end{lstlisting}
  2040. \fi}
  2041. {\if\edition\pythonEd
  2042. \begin{lstlisting}[frame=single]
  2043. class InterpLvar(InterpLint):
  2044. def interp_exp(self, e, env):
  2045. match e:
  2046. case Name(id):
  2047. return env[id]
  2048. case _:
  2049. return super().interp_exp(e, env)
  2050. def interp_stmts(self, ss, env):
  2051. if len(ss) == 0:
  2052. return
  2053. match ss[0]:
  2054. case Assign([lhs], value):
  2055. env[lhs.id] = self.interp_exp(value, env)
  2056. return self.interp_stmts(ss[1:], env)
  2057. case _:
  2058. return super().interp_stmts(ss, env)
  2059. def interp_Lvar(p):
  2060. return InterpLvar().interp(p)
  2061. \end{lstlisting}
  2062. \fi}
  2063. \caption{Interpreter for the \LangVar{} language.}
  2064. \label{fig:interp-Lvar}
  2065. \end{figure}
  2066. The goal for this chapter is to implement a compiler that translates
  2067. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2068. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2069. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2070. That is, they output the same integer $n$. We depict this correctness
  2071. criteria in the following diagram.
  2072. \[
  2073. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2074. \node (p1) at (0, 0) {$P_1$};
  2075. \node (p2) at (4, 0) {$P_2$};
  2076. \node (o) at (4, -2) {$n$};
  2077. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2078. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2079. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2080. \end{tikzpicture}
  2081. \]
  2082. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2083. compiling \LangVar{}.
  2084. \section{The \LangXInt{} Assembly Language}
  2085. \label{sec:x86}
  2086. \index{subject}{x86}
  2087. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2088. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2089. assembler.
  2090. %
  2091. A program begins with a \code{main} label followed by a sequence of
  2092. instructions. The \key{globl} directive says that the \key{main}
  2093. procedure is externally visible, which is necessary so that the
  2094. operating system can call it.
  2095. %
  2096. An x86 program is stored in the computer's memory. For our purposes,
  2097. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2098. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2099. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2100. the address of the next instruction to be executed. For most
  2101. instructions, the program counter is incremented after the instruction
  2102. is executed, so it points to the next instruction in memory. Most x86
  2103. instructions take two operands, where each operand is either an
  2104. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2105. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2106. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2107. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2108. && \key{r8} \MID \key{r9} \MID \key{r10}
  2109. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2110. \MID \key{r14} \MID \key{r15}}
  2111. \newcommand{\GrammarXInt}{
  2112. \begin{array}{rcl}
  2113. \Reg &::=& \allregisters{} \\
  2114. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2115. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2116. \key{subq} \; \Arg\key{,} \Arg \MID
  2117. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2118. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2119. \key{callq} \; \mathit{label} \MID
  2120. \key{retq} \MID
  2121. \key{jmp}\,\itm{label} \MID \\
  2122. && \itm{label}\key{:}\; \Instr
  2123. \end{array}
  2124. }
  2125. \begin{figure}[tp]
  2126. \fbox{
  2127. \begin{minipage}{0.96\textwidth}
  2128. {\if\edition\racketEd
  2129. \[
  2130. \begin{array}{l}
  2131. \GrammarXInt \\
  2132. \begin{array}{lcl}
  2133. \LangXIntM{} &::= & \key{.globl main}\\
  2134. & & \key{main:} \; \Instr\ldots
  2135. \end{array}
  2136. \end{array}
  2137. \]
  2138. \fi}
  2139. {\if\edition\pythonEd
  2140. \[
  2141. \begin{array}{lcl}
  2142. \Reg &::=& \allregisters{} \\
  2143. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2144. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2145. \key{subq} \; \Arg\key{,} \Arg \MID
  2146. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2147. && \key{callq} \; \mathit{label} \MID
  2148. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2149. \LangXIntM{} &::= & \key{.globl main}\\
  2150. & & \key{main:} \; \Instr^{*}
  2151. \end{array}
  2152. \]
  2153. \fi}
  2154. \end{minipage}
  2155. }
  2156. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2157. \label{fig:x86-int-concrete}
  2158. \end{figure}
  2159. A register is a special kind of variable that holds a 64-bit
  2160. value. There are 16 general-purpose registers in the computer and
  2161. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2162. is written with a \key{\%} followed by the register name, such as
  2163. \key{\%rax}.
  2164. An immediate value is written using the notation \key{\$}$n$ where $n$
  2165. is an integer.
  2166. %
  2167. %
  2168. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2169. which obtains the address stored in register $r$ and then adds $n$
  2170. bytes to the address. The resulting address is used to load or store
  2171. to memory depending on whether it occurs as a source or destination
  2172. argument of an instruction.
  2173. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2174. source $s$ and destination $d$, applies the arithmetic operation, then
  2175. writes the result back to the destination $d$. \index{subject}{instruction}
  2176. %
  2177. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2178. stores the result in $d$.
  2179. %
  2180. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2181. specified by the label and $\key{retq}$ returns from a procedure to
  2182. its caller.
  2183. %
  2184. We discuss procedure calls in more detail later in this chapter and in
  2185. Chapter~\ref{ch:Lfun}.
  2186. %
  2187. The last letter \key{q} indicates that these instructions operate on
  2188. quadwords, i.e., 64-bit values.
  2189. %
  2190. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2191. counter to the address of the instruction after the specified
  2192. label.}
  2193. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2194. all of the x86 instructions used in this book.
  2195. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2196. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2197. \lstinline{movq $10, %rax}
  2198. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2199. adds $32$ to the $10$ in \key{rax} and
  2200. puts the result, $42$, back into \key{rax}.
  2201. %
  2202. The last instruction \key{retq} finishes the \key{main} function by
  2203. returning the integer in \key{rax} to the operating system. The
  2204. operating system interprets this integer as the program's exit
  2205. code. By convention, an exit code of 0 indicates that a program
  2206. completed successfully, and all other exit codes indicate various
  2207. errors.
  2208. %
  2209. \racket{Nevertheless, in this book we return the result of the program
  2210. as the exit code.}
  2211. \begin{figure}[tbp]
  2212. \begin{minipage}{0.45\textwidth}
  2213. \begin{lstlisting}[frame=single]
  2214. .globl main
  2215. main:
  2216. movq $10, %rax
  2217. addq $32, %rax
  2218. retq
  2219. \end{lstlisting}
  2220. \end{minipage}
  2221. \caption{An x86 program that computes
  2222. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2223. \label{fig:p0-x86}
  2224. \end{figure}
  2225. We exhibit the use of memory for storing intermediate results in the
  2226. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2227. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2228. uses a region of memory called the \emph{procedure call stack} (or
  2229. \emph{stack} for
  2230. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2231. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2232. for each procedure call. The memory layout for an individual frame is
  2233. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2234. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2235. address of the item at the top of the stack. In general, we use the
  2236. term \emph{pointer}\index{subject}{pointer} for something that
  2237. contains an address. The stack grows downward in memory, so we
  2238. increase the size of the stack by subtracting from the stack pointer.
  2239. In the context of a procedure call, the \emph{return
  2240. address}\index{subject}{return address} is the instruction after the
  2241. call instruction on the caller side. The function call instruction,
  2242. \code{callq}, pushes the return address onto the stack prior to
  2243. jumping to the procedure. The register \key{rbp} is the \emph{base
  2244. pointer}\index{subject}{base pointer} and is used to access
  2245. variables that are stored in the frame of the current procedure call.
  2246. The base pointer of the caller is stored after the return address. In
  2247. Figure~\ref{fig:frame} we number the variables from $1$ to
  2248. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2249. at $-16\key{(\%rbp)}$, etc.
  2250. \begin{figure}[tbp]
  2251. \begin{minipage}{0.66\textwidth}
  2252. {\if\edition\racketEd
  2253. \begin{lstlisting}[frame=single]
  2254. start:
  2255. movq $10, -8(%rbp)
  2256. negq -8(%rbp)
  2257. movq -8(%rbp), %rax
  2258. addq $52, %rax
  2259. jmp conclusion
  2260. .globl main
  2261. main:
  2262. pushq %rbp
  2263. movq %rsp, %rbp
  2264. subq $16, %rsp
  2265. jmp start
  2266. conclusion:
  2267. addq $16, %rsp
  2268. popq %rbp
  2269. retq
  2270. \end{lstlisting}
  2271. \fi}
  2272. {\if\edition\pythonEd
  2273. \begin{lstlisting}[frame=single]
  2274. .globl main
  2275. main:
  2276. pushq %rbp
  2277. movq %rsp, %rbp
  2278. subq $16, %rsp
  2279. movq $10, -8(%rbp)
  2280. negq -8(%rbp)
  2281. movq -8(%rbp), %rax
  2282. addq $52, %rax
  2283. addq $16, %rsp
  2284. popq %rbp
  2285. retq
  2286. \end{lstlisting}
  2287. \fi}
  2288. \end{minipage}
  2289. \caption{An x86 program that computes
  2290. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2291. \label{fig:p1-x86}
  2292. \end{figure}
  2293. \begin{figure}[tbp]
  2294. \centering
  2295. \begin{tabular}{|r|l|} \hline
  2296. Position & Contents \\ \hline
  2297. 8(\key{\%rbp}) & return address \\
  2298. 0(\key{\%rbp}) & old \key{rbp} \\
  2299. -8(\key{\%rbp}) & variable $1$ \\
  2300. -16(\key{\%rbp}) & variable $2$ \\
  2301. \ldots & \ldots \\
  2302. 0(\key{\%rsp}) & variable $n$\\ \hline
  2303. \end{tabular}
  2304. \caption{Memory layout of a frame.}
  2305. \label{fig:frame}
  2306. \end{figure}
  2307. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2308. control is transferred from the operating system to the \code{main}
  2309. function. The operating system issues a \code{callq main} instruction
  2310. which pushes its return address on the stack and then jumps to
  2311. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2312. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2313. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2314. alignment (because the \code{callq} pushed the return address). The
  2315. first three instructions are the typical
  2316. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2317. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2318. pointer \code{rsp} and then saves the base pointer of the caller at
  2319. address \code{rsp} on the stack. The next instruction \code{movq
  2320. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2321. which is pointing at the location of the old base pointer. The
  2322. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2323. make enough room for storing variables. This program needs one
  2324. variable ($8$ bytes) but we round up to 16 bytes so that \code{rsp} is
  2325. 16-byte aligned and we're ready to make calls to other functions.
  2326. \racket{The last instruction of the prelude is \code{jmp start}, which
  2327. transfers control to the instructions that were generated from the
  2328. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2329. \racket{The first instruction under the \code{start} label is}
  2330. %
  2331. \python{The first instruction after the prelude is}
  2332. %
  2333. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2334. %
  2335. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2336. $1$ to $-10$.
  2337. %
  2338. The next instruction moves the $-10$ from variable $1$ into the
  2339. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2340. the value in \code{rax}, updating its contents to $42$.
  2341. \racket{The three instructions under the label \code{conclusion} are the
  2342. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2343. %
  2344. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2345. \code{main} function consists of the last three instructions.}
  2346. %
  2347. The first two restore the \code{rsp} and \code{rbp} registers to the
  2348. state they were in at the beginning of the procedure. In particular,
  2349. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2350. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2351. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2352. \key{retq}, jumps back to the procedure that called this one and adds
  2353. $8$ to the stack pointer.
  2354. Our compiler needs a convenient representation for manipulating x86
  2355. programs, so we define an abstract syntax for x86 in
  2356. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2357. \LangXInt{}.
  2358. %
  2359. {\if\edition\pythonEd%
  2360. The main difference compared to the concrete syntax of \LangXInt{}
  2361. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2362. names, and register names are explicitly represented by strings.
  2363. \fi} %
  2364. {\if\edition\racketEd
  2365. The main difference compared to the concrete syntax of \LangXInt{}
  2366. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2367. front of every instruction. Instead instructions are grouped into
  2368. \emph{basic blocks}\index{subject}{basic block} with a
  2369. label associated with every basic block, which is why the \key{X86Program}
  2370. struct includes an alist mapping labels to basic blocks. The reason for this
  2371. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2372. introduce conditional branching. The \code{Block} structure includes
  2373. an $\itm{info}$ field that is not needed for this chapter but becomes
  2374. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2375. $\itm{info}$ field should contain an empty list.
  2376. \fi}
  2377. %
  2378. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2379. node includes an integer for representing the arity of the function,
  2380. i.e., the number of arguments, which is helpful to know during
  2381. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2382. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2383. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2384. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2385. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2386. \MID \skey{r14} \MID \skey{r15}}
  2387. \newcommand{\ASTXIntRacket}{
  2388. \begin{array}{lcl}
  2389. \Reg &::=& \allregisters{} \\
  2390. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2391. \MID \DEREF{\Reg}{\Int} \\
  2392. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2393. \MID \BININSTR{\code{subq}}{\Arg}{\Arg}
  2394. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2395. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2396. \MID \PUSHQ{\Arg}
  2397. \MID \POPQ{\Arg} \\
  2398. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2399. \MID \RETQ{}
  2400. \MID \JMP{\itm{label}} \\
  2401. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}
  2402. \end{array}
  2403. }
  2404. \begin{figure}[tp]
  2405. \fbox{
  2406. \begin{minipage}{0.94\textwidth}
  2407. \small
  2408. {\if\edition\racketEd
  2409. \[
  2410. \begin{array}{l}
  2411. \ASTXIntRacket \\
  2412. \begin{array}{lcl}
  2413. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2414. \end{array}
  2415. \end{array}
  2416. \]
  2417. \fi}
  2418. {\if\edition\pythonEd
  2419. \[
  2420. \begin{array}{lcl}
  2421. \Reg &::=& \allastregisters{} \\
  2422. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2423. \MID \DEREF{\Reg}{\Int} \\
  2424. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2425. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2426. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2427. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2428. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2429. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2430. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2431. \end{array}
  2432. \]
  2433. \fi}
  2434. \end{minipage}
  2435. }
  2436. \caption{The abstract syntax of \LangXInt{} assembly.}
  2437. \label{fig:x86-int-ast}
  2438. \end{figure}
  2439. \section{Planning the trip to x86}
  2440. \label{sec:plan-s0-x86}
  2441. To compile one language to another it helps to focus on the
  2442. differences between the two languages because the compiler will need
  2443. to bridge those differences. What are the differences between \LangVar{}
  2444. and x86 assembly? Here are some of the most important ones:
  2445. \begin{enumerate}
  2446. \item x86 arithmetic instructions typically have two arguments and
  2447. update the second argument in place. In contrast, \LangVar{}
  2448. arithmetic operations take two arguments and produce a new value.
  2449. An x86 instruction may have at most one memory-accessing argument.
  2450. Furthermore, some x86 instructions place special restrictions on
  2451. their arguments.
  2452. \item An argument of an \LangVar{} operator can be a deeply-nested
  2453. expression, whereas x86 instructions restrict their arguments to be
  2454. integer constants, registers, and memory locations.
  2455. {\if\edition\racketEd
  2456. \item The order of execution in x86 is explicit in the syntax: a
  2457. sequence of instructions and jumps to labeled positions, whereas in
  2458. \LangVar{} the order of evaluation is a left-to-right depth-first
  2459. traversal of the abstract syntax tree.
  2460. \fi}
  2461. \item A program in \LangVar{} can have any number of variables
  2462. whereas x86 has 16 registers and the procedure call stack.
  2463. {\if\edition\racketEd
  2464. \item Variables in \LangVar{} can shadow other variables with the
  2465. same name. In x86, registers have unique names and memory locations
  2466. have unique addresses.
  2467. \fi}
  2468. \end{enumerate}
  2469. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2470. down the problem into several steps, dealing with the above
  2471. differences one at a time. Each of these steps is called a \emph{pass}
  2472. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2473. %
  2474. This terminology comes from the way each step passes over, or
  2475. traverses, the AST of the program.
  2476. %
  2477. Furthermore, we follow the nanopass approach, which means we strive
  2478. for each pass to accomplish one clear objective (not two or three at
  2479. the same time).
  2480. %
  2481. We begin by sketching how we might implement each pass, and give them
  2482. names. We then figure out an ordering of the passes and the
  2483. input/output language for each pass. The very first pass has
  2484. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2485. its output language. In between we can choose whichever language is
  2486. most convenient for expressing the output of each pass, whether that
  2487. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2488. our own design. Finally, to implement each pass we write one
  2489. recursive function per non-terminal in the grammar of the input
  2490. language of the pass. \index{subject}{intermediate language}
  2491. Our compiler for \LangVar{} consists of the following passes.
  2492. %
  2493. \begin{description}
  2494. {\if\edition\racketEd
  2495. \item[\key{uniquify}] deals with the shadowing of variables by
  2496. renaming every variable to a unique name.
  2497. \fi}
  2498. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2499. of a primitive operation or function call is a variable or integer,
  2500. that is, an \emph{atomic} expression. We refer to non-atomic
  2501. expressions as \emph{complex}. This pass introduces temporary
  2502. variables to hold the results of complex
  2503. subexpressions.\index{subject}{atomic
  2504. expression}\index{subject}{complex expression}%
  2505. {\if\edition\racketEd
  2506. \item[\key{explicate\_control}] makes the execution order of the
  2507. program explicit. It converts the abstract syntax tree
  2508. representation into a graph in which each node is a labeled sequence
  2509. of statements and the edges are \code{goto} statements.
  2510. \fi}
  2511. \item[\key{select\_instructions}] handles the difference between
  2512. \LangVar{} operations and x86 instructions. This pass converts each
  2513. \LangVar{} operation to a short sequence of instructions that
  2514. accomplishes the same task.
  2515. \item[\key{assign\_homes}] replaces variables with registers or stack
  2516. locations.
  2517. \end{description}
  2518. %
  2519. {\if\edition\racketEd
  2520. %
  2521. Our treatment of \code{remove\_complex\_operands} and
  2522. \code{explicate\_control} as separate passes is an example of the
  2523. nanopass approach\footnote{For analogous decompositions of the
  2524. translation into continuation passing style, see the work of
  2525. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2526. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2527. %
  2528. \fi}
  2529. The next question is: in what order should we apply these passes? This
  2530. question can be challenging because it is difficult to know ahead of
  2531. time which orderings will be better (easier to implement, produce more
  2532. efficient code, etc.) so oftentimes trial-and-error is
  2533. involved. Nevertheless, we can plan ahead and make educated choices
  2534. regarding the ordering.
  2535. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2536. \key{uniquify}? The \key{uniquify} pass should come first because
  2537. \key{explicate\_control} changes all the \key{let}-bound variables to
  2538. become local variables whose scope is the entire program, which would
  2539. confuse variables with the same name.}
  2540. %
  2541. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2542. because the later removes the \key{let} form, but it is convenient to
  2543. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2544. %
  2545. \racket{The ordering of \key{uniquify} with respect to
  2546. \key{remove\_complex\_operands} does not matter so we arbitrarily choose
  2547. \key{uniquify} to come first.}
  2548. The \key{select\_instructions} and \key{assign\_homes} passes are
  2549. intertwined.
  2550. %
  2551. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2552. passing arguments to functions and it is preferable to assign
  2553. parameters to their corresponding registers. This suggests that it
  2554. would be better to start with the \key{select\_instructions} pass,
  2555. which generates the instructions for argument passing, before
  2556. performing register allocation.
  2557. %
  2558. On the other hand, by selecting instructions first we may run into a
  2559. dead end in \key{assign\_homes}. Recall that only one argument of an
  2560. x86 instruction may be a memory access but \key{assign\_homes} might
  2561. be forced to assign both arguments to memory locations.
  2562. %
  2563. A sophisticated approach is to repeat the two passes until a solution
  2564. is found. However, to reduce implementation complexity we recommend
  2565. placing \key{select\_instructions} first, followed by the
  2566. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2567. that uses a reserved register to fix outstanding problems.
  2568. \begin{figure}[tbp]
  2569. \fbox{
  2570. \begin{minipage}{0.96\textwidth}
  2571. {\if\edition\racketEd
  2572. \begin{tikzpicture}[baseline=(current bounding box.center),scale=0.95]
  2573. \node (Lvar) at (0,2) {\large \LangVar{}};
  2574. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2575. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2576. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2577. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2578. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2579. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2580. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2581. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2582. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2583. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2584. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2585. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2586. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2587. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2588. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2589. \end{tikzpicture}
  2590. \fi}
  2591. {\if\edition\pythonEd
  2592. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2593. \node (Lvar) at (0,2) {\large \LangVar{}};
  2594. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2595. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2596. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2597. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2598. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2599. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2600. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2601. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2602. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2603. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2604. \end{tikzpicture}
  2605. \fi}
  2606. \end{minipage}
  2607. }
  2608. \caption{Diagram of the passes for compiling \LangVar{}. }
  2609. \label{fig:Lvar-passes}
  2610. \end{figure}
  2611. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2612. passes and identifies the input and output language of each pass.
  2613. %
  2614. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2615. language, which extends \LangXInt{} with an unbounded number of
  2616. program-scope variables and removes the restrictions regarding
  2617. instruction arguments.
  2618. %
  2619. The last pass, \key{prelude\_and\_conclusion}, places the program
  2620. instructions inside a \code{main} function with instructions for the
  2621. prelude and conclusion.
  2622. %
  2623. \racket{In the next section we discuss the \LangCVar{} intermediate
  2624. language that serves as the output of \code{explicate\_control}.}
  2625. %
  2626. The remainder of this chapter provides guidance on the implementation
  2627. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2628. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2629. %% are programs that are still in the \LangVar{} language, though the
  2630. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2631. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2632. %% %
  2633. %% The output of \code{explicate\_control} is in an intermediate language
  2634. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2635. %% syntax, which we introduce in the next section. The
  2636. %% \key{select-instruction} pass translates from \LangCVar{} to
  2637. %% \LangXVar{}. The \key{assign-homes} and
  2638. %% \key{patch-instructions}
  2639. %% passes input and output variants of x86 assembly.
  2640. \newcommand{\CvarGrammarRacket}{
  2641. \begin{array}{lcl}
  2642. \Atm &::=& \Int \MID \Var \\
  2643. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2644. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2645. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2646. \end{array}
  2647. }
  2648. \newcommand{\CvarASTRacket}{
  2649. \begin{array}{lcl}
  2650. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2651. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2652. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2653. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2654. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2655. \end{array}
  2656. }
  2657. {\if\edition\racketEd
  2658. \subsection{The \LangCVar{} Intermediate Language}
  2659. The output of \code{explicate\_control} is similar to the $C$
  2660. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2661. categories for expressions and statements, so we name it \LangCVar{}.
  2662. This style of intermediate language is also known as
  2663. \emph{three-address code}, to emphasize that the typical form of a
  2664. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2665. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2666. The concrete syntax for \LangCVar{} is defined in
  2667. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2668. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2669. %
  2670. The \LangCVar{} language supports the same operators as \LangVar{} but
  2671. the arguments of operators are restricted to atomic
  2672. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2673. assignment statements which can be executed in sequence using the
  2674. \key{Seq} form. A sequence of statements always ends with
  2675. \key{Return}, a guarantee that is baked into the grammar rules for
  2676. \itm{tail}. The naming of this non-terminal comes from the term
  2677. \emph{tail position}\index{subject}{tail position}, which refers to an
  2678. expression that is the last one to execute within a function or
  2679. program.
  2680. A \LangCVar{} program consists of an alist mapping labels to
  2681. tails. This is more general than necessary for the present chapter, as
  2682. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2683. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2684. there will be just one label, \key{start}, and the whole program is
  2685. its tail.
  2686. %
  2687. The $\itm{info}$ field of the \key{CProgram} form, after the
  2688. \code{explicate\_control} pass, contains a mapping from the symbol
  2689. \key{locals} to a list of variables, that is, a list of all the
  2690. variables used in the program. At the start of the program, these
  2691. variables are uninitialized; they become initialized on their first
  2692. assignment.
  2693. \begin{figure}[tbp]
  2694. \fbox{
  2695. \begin{minipage}{0.96\textwidth}
  2696. \[
  2697. \begin{array}{l}
  2698. \CvarGrammarRacket \\
  2699. \begin{array}{lcl}
  2700. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2701. \end{array}
  2702. \end{array}
  2703. \]
  2704. \end{minipage}
  2705. }
  2706. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2707. \label{fig:c0-concrete-syntax}
  2708. \end{figure}
  2709. \begin{figure}[tbp]
  2710. \fbox{
  2711. \begin{minipage}{0.96\textwidth}
  2712. \[
  2713. \begin{array}{l}
  2714. \CvarASTRacket \\
  2715. \begin{array}{lcl}
  2716. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2717. \end{array}
  2718. \end{array}
  2719. \]
  2720. \end{minipage}
  2721. }
  2722. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2723. \label{fig:c0-syntax}
  2724. \end{figure}
  2725. The definitional interpreter for \LangCVar{} is in the support code,
  2726. in the file \code{interp-Cvar.rkt}.
  2727. \fi}
  2728. {\if\edition\racketEd
  2729. \section{Uniquify Variables}
  2730. \label{sec:uniquify-Lvar}
  2731. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2732. programs in which every \key{let} binds a unique variable name. For
  2733. example, the \code{uniquify} pass should translate the program on the
  2734. left into the program on the right.
  2735. \begin{transformation}
  2736. \begin{lstlisting}
  2737. (let ([x 32])
  2738. (+ (let ([x 10]) x) x))
  2739. \end{lstlisting}
  2740. \compilesto
  2741. \begin{lstlisting}
  2742. (let ([x.1 32])
  2743. (+ (let ([x.2 10]) x.2) x.1))
  2744. \end{lstlisting}
  2745. \end{transformation}
  2746. The following is another example translation, this time of a program
  2747. with a \key{let} nested inside the initializing expression of another
  2748. \key{let}.
  2749. \begin{transformation}
  2750. \begin{lstlisting}
  2751. (let ([x (let ([x 4])
  2752. (+ x 1))])
  2753. (+ x 2))
  2754. \end{lstlisting}
  2755. \compilesto
  2756. \begin{lstlisting}
  2757. (let ([x.2 (let ([x.1 4])
  2758. (+ x.1 1))])
  2759. (+ x.2 2))
  2760. \end{lstlisting}
  2761. \end{transformation}
  2762. We recommend implementing \code{uniquify} by creating a structurally
  2763. recursive function named \code{uniquify\_exp} that mostly just copies
  2764. an expression. However, when encountering a \key{let}, it should
  2765. generate a unique name for the variable and associate the old name
  2766. with the new name in an alist.\footnote{The Racket function
  2767. \code{gensym} is handy for generating unique variable names.} The
  2768. \code{uniquify\_exp} function needs to access this alist when it gets
  2769. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2770. for the alist.
  2771. The skeleton of the \code{uniquify\_exp} function is shown in
  2772. Figure~\ref{fig:uniquify-Lvar}.
  2773. %% The function is curried so that it is
  2774. %% convenient to partially apply it to an alist and then apply it to
  2775. %% different expressions, as in the last case for primitive operations in
  2776. %% Figure~\ref{fig:uniquify-Lvar}.
  2777. The
  2778. %
  2779. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2780. %
  2781. form of Racket is useful for transforming the element of a list to
  2782. produce a new list.\index{subject}{for/list}
  2783. \begin{figure}[tbp]
  2784. \begin{lstlisting}[frame=single]
  2785. (define (uniquify_exp env)
  2786. (lambda (e)
  2787. (match e
  2788. [(Var x) ___]
  2789. [(Int n) (Int n)]
  2790. [(Let x e body) ___]
  2791. [(Prim op es)
  2792. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2793. (define (uniquify p)
  2794. (match p
  2795. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2796. \end{lstlisting}
  2797. \caption{Skeleton for the \key{uniquify} pass.}
  2798. \label{fig:uniquify-Lvar}
  2799. \end{figure}
  2800. \begin{exercise}
  2801. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2802. Complete the \code{uniquify} pass by filling in the blanks in
  2803. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2804. variables and for the \key{let} form in the file \code{compiler.rkt}
  2805. in the support code.
  2806. \end{exercise}
  2807. \begin{exercise}
  2808. \normalfont\normalsize
  2809. \label{ex:Lvar}
  2810. Create five \LangVar{} programs that exercise the most interesting
  2811. parts of the \key{uniquify} pass, that is, the programs should include
  2812. \key{let} forms, variables, and variables that shadow each other.
  2813. The five programs should be placed in the subdirectory named
  2814. \key{tests} and the file names should start with \code{var\_test\_}
  2815. followed by a unique integer and end with the file extension
  2816. \key{.rkt}.
  2817. %
  2818. The \key{run-tests.rkt} script in the support code checks whether the
  2819. output programs produce the same result as the input programs. The
  2820. script uses the \key{interp-tests} function
  2821. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2822. your \key{uniquify} pass on the example programs. The \code{passes}
  2823. parameter of \key{interp-tests} is a list that should have one entry
  2824. for each pass in your compiler. For now, define \code{passes} to
  2825. contain just one entry for \code{uniquify} as shown below.
  2826. \begin{lstlisting}
  2827. (define passes
  2828. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2829. \end{lstlisting}
  2830. Run the \key{run-tests.rkt} script in the support code to check
  2831. whether the output programs produce the same result as the input
  2832. programs.
  2833. \end{exercise}
  2834. \fi}
  2835. \section{Remove Complex Operands}
  2836. \label{sec:remove-complex-opera-Lvar}
  2837. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2838. into a restricted form in which the arguments of operations are atomic
  2839. expressions. Put another way, this pass removes complex
  2840. operands\index{subject}{complex operand}, such as the expression
  2841. \racket{\code{(- 10)}}\python{\code{-10}}
  2842. in the program below. This is accomplished by introducing a new
  2843. temporary variable, assigning the complex operand to the new
  2844. variable, and then using the new variable in place of the complex
  2845. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2846. right.
  2847. {\if\edition\racketEd
  2848. \begin{transformation}
  2849. % var_test_19.rkt
  2850. \begin{lstlisting}
  2851. (let ([x (+ 42 (- 10))])
  2852. (+ x 10))
  2853. \end{lstlisting}
  2854. \compilesto
  2855. \begin{lstlisting}
  2856. (let ([x (let ([tmp.1 (- 10)])
  2857. (+ 42 tmp.1))])
  2858. (+ x 10))
  2859. \end{lstlisting}
  2860. \end{transformation}
  2861. \fi}
  2862. {\if\edition\pythonEd
  2863. \begin{transformation}
  2864. \begin{lstlisting}
  2865. x = 42 + -10
  2866. print(x + 10)
  2867. \end{lstlisting}
  2868. \compilesto
  2869. \begin{lstlisting}
  2870. tmp_0 = -10
  2871. x = 42 + tmp_0
  2872. tmp_1 = x + 10
  2873. print(tmp_1)
  2874. \end{lstlisting}
  2875. \end{transformation}
  2876. \fi}
  2877. \newcommand{\LvarMonadASTRacket}{
  2878. \begin{array}{rcl}
  2879. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2880. \Exp &::=& \Atm \MID \READ{} \\
  2881. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2882. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2883. \end{array}
  2884. }
  2885. \newcommand{\LvarMonadASTPython}{
  2886. \begin{array}{rcl}
  2887. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2888. \Exp{} &::=& \Atm \MID \READ{} \\
  2889. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2890. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2891. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2892. \end{array}
  2893. }
  2894. \begin{figure}[tp]
  2895. \centering
  2896. \fbox{
  2897. \begin{minipage}{0.96\textwidth}
  2898. {\if\edition\racketEd
  2899. \[
  2900. \begin{array}{l}
  2901. \LvarMonadASTRacket \\
  2902. \begin{array}{rcl}
  2903. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2904. \end{array}
  2905. \end{array}
  2906. \]
  2907. \fi}
  2908. {\if\edition\pythonEd
  2909. \[
  2910. \begin{array}{l}
  2911. \LvarMonadASTPython \\
  2912. \begin{array}{rcl}
  2913. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2914. \end{array}
  2915. \end{array}
  2916. \]
  2917. \fi}
  2918. \end{minipage}
  2919. }
  2920. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2921. atomic expressions.}
  2922. \label{fig:Lvar-anf-syntax}
  2923. \end{figure}
  2924. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2925. of this pass, the language \LangVarANF{}. The only difference is that
  2926. operator arguments are restricted to be atomic expressions that are
  2927. defined by the \Atm{} non-terminal. In particular, integer constants
  2928. and variables are atomic.
  2929. The atomic expressions are pure (they do not cause or depend on
  2930. side-effects) whereas complex expressions may have side effects, such
  2931. as \READ{}. A language with this separation between pure versus
  2932. side-effecting expressions is said to be in monadic normal
  2933. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2934. in the name \LangVarANF{}. An important invariant of the
  2935. \code{remove\_complex\_operands} pass is that the relative ordering
  2936. among complex expressions is not changed, but the relative ordering
  2937. between atomic expressions and complex expressions can change and
  2938. often does. The reason that these changes are behavior preserving is
  2939. that the atomic expressions are pure.
  2940. Another well-known form for intermediate languages is the
  2941. \emph{administrative normal form}
  2942. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2943. \index{subject}{administrative normal form} \index{subject}{ANF}
  2944. %
  2945. The \LangVarANF{} language is not quite in ANF because we allow the
  2946. right-hand side of a \code{let} to be a complex expression.
  2947. {\if\edition\racketEd
  2948. We recommend implementing this pass with two mutually recursive
  2949. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2950. \code{rco\_atom} to subexpressions that need to become atomic and to
  2951. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2952. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2953. returns an expression. The \code{rco\_atom} function returns two
  2954. things: an atomic expression and an alist mapping temporary variables to
  2955. complex subexpressions. You can return multiple things from a function
  2956. using Racket's \key{values} form and you can receive multiple things
  2957. from a function call using the \key{define-values} form.
  2958. \fi}
  2959. %
  2960. {\if\edition\pythonEd
  2961. %
  2962. We recommend implementing this pass with an auxiliary method named
  2963. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2964. Boolean that specifies whether the expression needs to become atomic
  2965. or not. The \code{rco\_exp} method should return a pair consisting of
  2966. the new expression and a list of pairs, associating new temporary
  2967. variables with their initializing expressions.
  2968. %
  2969. \fi}
  2970. {\if\edition\racketEd
  2971. %
  2972. Returning to the example program with the expression \code{(+ 42 (-
  2973. 10))}, the subexpression \code{(- 10)} should be processed using the
  2974. \code{rco\_atom} function because it is an argument of the \code{+}
  2975. operator and therefore needs to become atomic. The output of
  2976. \code{rco\_atom} applied to \code{(- 10)} is as follows.
  2977. \begin{transformation}
  2978. \begin{lstlisting}
  2979. (- 10)
  2980. \end{lstlisting}
  2981. \compilesto
  2982. \begin{lstlisting}
  2983. tmp.1
  2984. ((tmp.1 . (- 10)))
  2985. \end{lstlisting}
  2986. \end{transformation}
  2987. \fi}
  2988. %
  2989. {\if\edition\pythonEd
  2990. %
  2991. Returning to the example program with the expression \code{42 + -10},
  2992. the subexpression \code{-10} should be processed using the
  2993. \code{rco\_exp} function with \code{True} as the second argument
  2994. because \code{-10} is an argument of the \code{+} operator and
  2995. therefore needs to become atomic. The output of \code{rco\_exp}
  2996. applied to \code{-10} is as follows.
  2997. \begin{transformation}
  2998. \begin{lstlisting}
  2999. -10
  3000. \end{lstlisting}
  3001. \compilesto
  3002. \begin{lstlisting}
  3003. tmp_1
  3004. [(tmp_1, -10)]
  3005. \end{lstlisting}
  3006. \end{transformation}
  3007. %
  3008. \fi}
  3009. Take special care of programs such as the following that
  3010. %
  3011. \racket{bind a variable to an atomic expression.}
  3012. %
  3013. \python{assign an atomic expression to a variable.}
  3014. %
  3015. You should leave such \racket{variable bindings}\python{assignments}
  3016. unchanged, as shown in the program on the right\\
  3017. %
  3018. {\if\edition\racketEd
  3019. \begin{transformation}
  3020. % var_test_20.rkt
  3021. \begin{lstlisting}
  3022. (let ([a 42])
  3023. (let ([b a])
  3024. b))
  3025. \end{lstlisting}
  3026. \compilesto
  3027. \begin{lstlisting}
  3028. (let ([a 42])
  3029. (let ([b a])
  3030. b))
  3031. \end{lstlisting}
  3032. \end{transformation}
  3033. \fi}
  3034. {\if\edition\pythonEd
  3035. \begin{transformation}
  3036. \begin{lstlisting}
  3037. a = 42
  3038. b = a
  3039. print(b)
  3040. \end{lstlisting}
  3041. \compilesto
  3042. \begin{lstlisting}
  3043. a = 42
  3044. b = a
  3045. print(b)
  3046. \end{lstlisting}
  3047. \end{transformation}
  3048. \fi}
  3049. %
  3050. \noindent A careless implementation might produce the following output with
  3051. unnecessary temporary variables.
  3052. \begin{center}
  3053. \begin{minipage}{0.4\textwidth}
  3054. {\if\edition\racketEd
  3055. \begin{lstlisting}
  3056. (let ([tmp.1 42])
  3057. (let ([a tmp.1])
  3058. (let ([tmp.2 a])
  3059. (let ([b tmp.2])
  3060. b))))
  3061. \end{lstlisting}
  3062. \fi}
  3063. {\if\edition\pythonEd
  3064. \begin{lstlisting}
  3065. tmp_1 = 42
  3066. a = tmp_1
  3067. tmp_2 = a
  3068. b = tmp_2
  3069. print(b)
  3070. \end{lstlisting}
  3071. \fi}
  3072. \end{minipage}
  3073. \end{center}
  3074. \begin{exercise}
  3075. \normalfont\normalsize
  3076. {\if\edition\racketEd
  3077. Implement the \code{remove\_complex\_operands} function in
  3078. \code{compiler.rkt}.
  3079. %
  3080. Create three new \LangVar{} programs that exercise the interesting
  3081. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3082. regarding file names described in Exercise~\ref{ex:Lvar}.
  3083. %
  3084. In the \code{run-tests.rkt} script, add the following entry to the
  3085. list of \code{passes} and then run the script to test your compiler.
  3086. \begin{lstlisting}
  3087. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3088. \end{lstlisting}
  3089. While debugging your compiler, it is often useful to see the
  3090. intermediate programs that are output from each pass. To print the
  3091. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3092. \code{interp-tests} in \code{run-tests.rkt}.
  3093. \fi}
  3094. %
  3095. {\if\edition\pythonEd
  3096. Implement the \code{remove\_complex\_operands} pass in
  3097. \code{compiler.py}, creating auxiliary functions for each
  3098. non-terminal in the grammar, i.e., \code{rco\_exp}
  3099. and \code{rco\_stmt}. We recommend you use the function
  3100. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3101. \fi}
  3102. \end{exercise}
  3103. {\if\edition\pythonEd
  3104. \begin{exercise}
  3105. \normalfont\normalsize
  3106. \label{ex:Lvar}
  3107. Create five \LangVar{} programs that exercise the most interesting
  3108. parts of the \code{remove\_complex\_operands} pass. The five programs
  3109. should be placed in the subdirectory named \key{tests} and the file
  3110. names should start with \code{var\_test\_} followed by a unique
  3111. integer and end with the file extension \key{.py}.
  3112. %% The \key{run-tests.rkt} script in the support code checks whether the
  3113. %% output programs produce the same result as the input programs. The
  3114. %% script uses the \key{interp-tests} function
  3115. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3116. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3117. %% parameter of \key{interp-tests} is a list that should have one entry
  3118. %% for each pass in your compiler. For now, define \code{passes} to
  3119. %% contain just one entry for \code{uniquify} as shown below.
  3120. %% \begin{lstlisting}
  3121. %% (define passes
  3122. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3123. %% \end{lstlisting}
  3124. Run the \key{run-tests.py} script in the support code to check
  3125. whether the output programs produce the same result as the input
  3126. programs.
  3127. \end{exercise}
  3128. \fi}
  3129. {\if\edition\racketEd
  3130. \section{Explicate Control}
  3131. \label{sec:explicate-control-Lvar}
  3132. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3133. programs that make the order of execution explicit in their
  3134. syntax. For now this amounts to flattening \key{let} constructs into a
  3135. sequence of assignment statements. For example, consider the following
  3136. \LangVar{} program.\\
  3137. % var_test_11.rkt
  3138. \begin{minipage}{0.96\textwidth}
  3139. \begin{lstlisting}
  3140. (let ([y (let ([x 20])
  3141. (+ x (let ([x 22]) x)))])
  3142. y)
  3143. \end{lstlisting}
  3144. \end{minipage}\\
  3145. %
  3146. The output of the previous pass is shown below, on the left, and the
  3147. output of \code{explicate\_control} is on the right. Recall that the
  3148. right-hand-side of a \key{let} executes before its body, so the order
  3149. of evaluation for this program is to assign \code{20} to \code{x.1},
  3150. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, then
  3151. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3152. this ordering explicit.
  3153. \begin{transformation}
  3154. \begin{lstlisting}
  3155. (let ([y (let ([x.1 20])
  3156. (let ([x.2 22])
  3157. (+ x.1 x.2)))])
  3158. y)
  3159. \end{lstlisting}
  3160. \compilesto
  3161. \begin{lstlisting}[language=C]
  3162. start:
  3163. x.1 = 20;
  3164. x.2 = 22;
  3165. y = (+ x.1 x.2);
  3166. return y;
  3167. \end{lstlisting}
  3168. \end{transformation}
  3169. \begin{figure}[tbp]
  3170. \begin{lstlisting}[frame=single]
  3171. (define (explicate_tail e)
  3172. (match e
  3173. [(Var x) ___]
  3174. [(Int n) (Return (Int n))]
  3175. [(Let x rhs body) ___]
  3176. [(Prim op es) ___]
  3177. [else (error "explicate_tail unhandled case" e)]))
  3178. (define (explicate_assign e x cont)
  3179. (match e
  3180. [(Var x) ___]
  3181. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3182. [(Let y rhs body) ___]
  3183. [(Prim op es) ___]
  3184. [else (error "explicate_assign unhandled case" e)]))
  3185. (define (explicate_control p)
  3186. (match p
  3187. [(Program info body) ___]))
  3188. \end{lstlisting}
  3189. \caption{Skeleton for the \code{explicate\_control} pass.}
  3190. \label{fig:explicate-control-Lvar}
  3191. \end{figure}
  3192. The organization of this pass depends on the notion of tail position
  3193. that we have alluded to earlier. Here is the definition.
  3194. \begin{definition}
  3195. The following rules define when an expression is in \textbf{\emph{tail
  3196. position}}\index{subject}{tail position} for the language \LangVar{}.
  3197. \begin{enumerate}
  3198. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3199. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3200. \end{enumerate}
  3201. \end{definition}
  3202. We recommend implementing \code{explicate\_control} using two
  3203. recursive functions, \code{explicate\_tail} and
  3204. \code{explicate\_assign}, as suggested in the skeleton code in
  3205. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3206. function should be applied to expressions in tail position whereas the
  3207. \code{explicate\_assign} should be applied to expressions that occur on
  3208. the right-hand-side of a \key{let}.
  3209. %
  3210. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3211. input and produces a \Tail{} in \LangCVar{} (see
  3212. Figure~\ref{fig:c0-syntax}).
  3213. %
  3214. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3215. the variable that it is to be assigned to, and a \Tail{} in
  3216. \LangCVar{} for the code that comes after the assignment. The
  3217. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3218. The \code{explicate\_assign} function is in accumulator-passing style:
  3219. the \code{cont} parameter is used for accumulating the output. This
  3220. accumulator-passing style plays an important role in how we generate
  3221. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3222. The abbreviation \code{cont} is for continuation because it contains
  3223. the generated code that should come after the current assignment.
  3224. This code organization is also related to continuation-passing style,
  3225. except that \code{cont} is not what happens next during compilation,
  3226. but what happens next in the generated code.
  3227. \begin{exercise}\normalfont\normalsize
  3228. %
  3229. Implement the \code{explicate\_control} function in
  3230. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3231. exercise the code in \code{explicate\_control}.
  3232. %
  3233. In the \code{run-tests.rkt} script, add the following entry to the
  3234. list of \code{passes} and then run the script to test your compiler.
  3235. \begin{lstlisting}
  3236. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3237. \end{lstlisting}
  3238. \end{exercise}
  3239. \fi}
  3240. \section{Select Instructions}
  3241. \label{sec:select-Lvar}
  3242. \index{subject}{instruction selection}
  3243. In the \code{select\_instructions} pass we begin the work of
  3244. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3245. language of this pass is a variant of x86 that still uses variables,
  3246. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3247. non-terminal of the \LangXInt{} abstract syntax
  3248. (Figure~\ref{fig:x86-int-ast}).
  3249. \racket{We recommend implementing the
  3250. \code{select\_instructions} with three auxiliary functions, one for
  3251. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3252. $\Tail$.}
  3253. \python{We recommend implementing an auxiliary function
  3254. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3255. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3256. same and integer constants change to immediates, that is, $\INT{n}$
  3257. changes to $\IMM{n}$.}
  3258. Next consider the cases for the $\Stmt$ non-terminal, starting with
  3259. arithmetic operations. For example, consider the addition operation
  3260. below, on the left side. There is an \key{addq} instruction in x86,
  3261. but it performs an in-place update. So we could move $\Arg_1$
  3262. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3263. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3264. $\Atm_1$ and $\Atm_2$ respectively.
  3265. \begin{transformation}
  3266. {\if\edition\racketEd
  3267. \begin{lstlisting}
  3268. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3269. \end{lstlisting}
  3270. \fi}
  3271. {\if\edition\pythonEd
  3272. \begin{lstlisting}
  3273. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3274. \end{lstlisting}
  3275. \fi}
  3276. \compilesto
  3277. \begin{lstlisting}
  3278. movq |$\Arg_1$|, |$\itm{var}$|
  3279. addq |$\Arg_2$|, |$\itm{var}$|
  3280. \end{lstlisting}
  3281. \end{transformation}
  3282. There are also cases that require special care to avoid generating
  3283. needlessly complicated code. For example, if one of the arguments of
  3284. the addition is the same variable as the left-hand side of the
  3285. assignment, as shown below, then there is no need for the extra move
  3286. instruction. The assignment statement can be translated into a single
  3287. \key{addq} instruction as follows.
  3288. \begin{transformation}
  3289. {\if\edition\racketEd
  3290. \begin{lstlisting}
  3291. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3292. \end{lstlisting}
  3293. \fi}
  3294. {\if\edition\pythonEd
  3295. \begin{lstlisting}
  3296. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3297. \end{lstlisting}
  3298. \fi}
  3299. \compilesto
  3300. \begin{lstlisting}
  3301. addq |$\Arg_1$|, |$\itm{var}$|
  3302. \end{lstlisting}
  3303. \end{transformation}
  3304. The \READOP{} operation does not have a direct counterpart in x86
  3305. assembly, so we provide this functionality with the function
  3306. \code{read\_int} in the file \code{runtime.c}, written in
  3307. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3308. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3309. system}, or simply the \emph{runtime} for short. When compiling your
  3310. generated x86 assembly code, you need to compile \code{runtime.c} to
  3311. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3312. \code{-c}) and link it into the executable. For our purposes of code
  3313. generation, all you need to do is translate an assignment of
  3314. \READOP{} into a call to the \code{read\_int} function followed by a
  3315. move from \code{rax} to the left-hand-side variable. (Recall that the
  3316. return value of a function goes into \code{rax}.)
  3317. \begin{transformation}
  3318. {\if\edition\racketEd
  3319. \begin{lstlisting}
  3320. |$\itm{var}$| = (read);
  3321. \end{lstlisting}
  3322. \fi}
  3323. {\if\edition\pythonEd
  3324. \begin{lstlisting}
  3325. |$\itm{var}$| = input_int();
  3326. \end{lstlisting}
  3327. \fi}
  3328. \compilesto
  3329. \begin{lstlisting}
  3330. callq read_int
  3331. movq %rax, |$\itm{var}$|
  3332. \end{lstlisting}
  3333. \end{transformation}
  3334. {\if\edition\pythonEd
  3335. %
  3336. Similarly, we translate the \code{print} operation, shown below, into
  3337. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3338. In x86, the first six arguments to functions are passed in registers,
  3339. with the first argument passed in register \code{rdi}. So we move the
  3340. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3341. \code{callq} instruction.
  3342. \begin{transformation}
  3343. \begin{lstlisting}
  3344. print(|$\Atm$|)
  3345. \end{lstlisting}
  3346. \compilesto
  3347. \begin{lstlisting}
  3348. movq |$\Arg$|, %rdi
  3349. callq print_int
  3350. \end{lstlisting}
  3351. \end{transformation}
  3352. %
  3353. \fi}
  3354. {\if\edition\racketEd
  3355. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3356. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3357. assignment to the \key{rax} register followed by a jump to the
  3358. conclusion of the program (so the conclusion needs to be labeled).
  3359. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3360. recursively and then append the resulting instructions.
  3361. \fi}
  3362. {\if\edition\pythonEd
  3363. We recommend that you use the function \code{utils.label\_name()} to
  3364. transform a string into an label argument suitably suitable for, e.g.,
  3365. the target of the \code{callq} instruction. This practice makes your
  3366. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3367. all labels.
  3368. \fi}
  3369. \begin{exercise}
  3370. \normalfont\normalsize
  3371. {\if\edition\racketEd
  3372. Implement the \code{select\_instructions} pass in
  3373. \code{compiler.rkt}. Create three new example programs that are
  3374. designed to exercise all of the interesting cases in this pass.
  3375. %
  3376. In the \code{run-tests.rkt} script, add the following entry to the
  3377. list of \code{passes} and then run the script to test your compiler.
  3378. \begin{lstlisting}
  3379. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3380. \end{lstlisting}
  3381. \fi}
  3382. {\if\edition\pythonEd
  3383. Implement the \key{select\_instructions} pass in
  3384. \code{compiler.py}. Create three new example programs that are
  3385. designed to exercise all of the interesting cases in this pass.
  3386. Run the \code{run-tests.py} script to to check
  3387. whether the output programs produce the same result as the input
  3388. programs.
  3389. \fi}
  3390. \end{exercise}
  3391. \section{Assign Homes}
  3392. \label{sec:assign-Lvar}
  3393. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3394. \LangXVar{} programs that no longer use program variables.
  3395. Thus, the \code{assign\_homes} pass is responsible for placing all of
  3396. the program variables in registers or on the stack. For runtime
  3397. efficiency, it is better to place variables in registers, but as there
  3398. are only 16 registers, some programs must necessarily resort to
  3399. placing some variables on the stack. In this chapter we focus on the
  3400. mechanics of placing variables on the stack. We study an algorithm for
  3401. placing variables in registers in
  3402. Chapter~\ref{ch:register-allocation-Lvar}.
  3403. Consider again the following \LangVar{} program from
  3404. Section~\ref{sec:remove-complex-opera-Lvar}.
  3405. % var_test_20.rkt
  3406. {\if\edition\racketEd
  3407. \begin{lstlisting}
  3408. (let ([a 42])
  3409. (let ([b a])
  3410. b))
  3411. \end{lstlisting}
  3412. \fi}
  3413. {\if\edition\pythonEd
  3414. \begin{lstlisting}
  3415. a = 42
  3416. b = a
  3417. print(b)
  3418. \end{lstlisting}
  3419. \fi}
  3420. %
  3421. The output of \code{select\_instructions} is shown below, on the left,
  3422. and the output of \code{assign\_homes} is on the right. In this
  3423. example, we assign variable \code{a} to stack location
  3424. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3425. \begin{transformation}
  3426. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3427. movq $42, a
  3428. movq a, b
  3429. movq b, %rax
  3430. \end{lstlisting}
  3431. \compilesto
  3432. %stack-space: 16
  3433. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3434. movq $42, -8(%rbp)
  3435. movq -8(%rbp), -16(%rbp)
  3436. movq -16(%rbp), %rax
  3437. \end{lstlisting}
  3438. \end{transformation}
  3439. \racket{
  3440. The \code{assign\_homes} pass should replace all variables
  3441. with stack locations.
  3442. The list of variables can be obtain from
  3443. the \code{locals-types} entry in the $\itm{info}$ of the
  3444. \code{X86Program} node. The \code{locals-types} entry is an alist
  3445. mapping all the variables in the program to their types
  3446. (for now just \code{Integer}).
  3447. As an aside, the \code{locals-types} entry is
  3448. computed by \code{type-check-Cvar} in the support code, which
  3449. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3450. which you should propagate to the \code{X86Program} node.}
  3451. %
  3452. \python{The \code{assign\_homes} pass should replace all uses of
  3453. variables with stack locations.}
  3454. %
  3455. In the process of assigning variables to stack locations, it is
  3456. convenient for you to compute and store the size of the frame (in
  3457. bytes) in
  3458. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3459. %
  3460. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3461. %
  3462. which is needed later to generate the conclusion of the \code{main}
  3463. procedure. The x86-64 standard requires the frame size to be a
  3464. multiple of 16 bytes.\index{subject}{frame}
  3465. % TODO: store the number of variables instead? -Jeremy
  3466. \begin{exercise}\normalfont\normalsize
  3467. Implement the \code{assign\_homes} pass in
  3468. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3469. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3470. grammar. We recommend that the auxiliary functions take an extra
  3471. parameter that maps variable names to homes (stack locations for now).
  3472. %
  3473. {\if\edition\racketEd
  3474. In the \code{run-tests.rkt} script, add the following entry to the
  3475. list of \code{passes} and then run the script to test your compiler.
  3476. \begin{lstlisting}
  3477. (list "assign homes" assign-homes interp_x86-0)
  3478. \end{lstlisting}
  3479. \fi}
  3480. {\if\edition\pythonEd
  3481. Run the \code{run-tests.py} script to to check
  3482. whether the output programs produce the same result as the input
  3483. programs.
  3484. \fi}
  3485. \end{exercise}
  3486. \section{Patch Instructions}
  3487. \label{sec:patch-s0}
  3488. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3489. \LangXInt{} by making sure that each instruction adheres to the
  3490. restriction that at most one argument of an instruction may be a
  3491. memory reference.
  3492. We return to the following example.\\
  3493. \begin{minipage}{0.5\textwidth}
  3494. % var_test_20.rkt
  3495. {\if\edition\racketEd
  3496. \begin{lstlisting}
  3497. (let ([a 42])
  3498. (let ([b a])
  3499. b))
  3500. \end{lstlisting}
  3501. \fi}
  3502. {\if\edition\pythonEd
  3503. \begin{lstlisting}
  3504. a = 42
  3505. b = a
  3506. print(b)
  3507. \end{lstlisting}
  3508. \fi}
  3509. \end{minipage}\\
  3510. The \code{assign\_homes} pass produces the following translation. \\
  3511. \begin{minipage}{0.5\textwidth}
  3512. {\if\edition\racketEd
  3513. \begin{lstlisting}
  3514. movq $42, -8(%rbp)
  3515. movq -8(%rbp), -16(%rbp)
  3516. movq -16(%rbp), %rax
  3517. \end{lstlisting}
  3518. \fi}
  3519. {\if\edition\pythonEd
  3520. \begin{lstlisting}
  3521. movq 42, -8(%rbp)
  3522. movq -8(%rbp), -16(%rbp)
  3523. movq -16(%rbp), %rdi
  3524. callq print_int
  3525. \end{lstlisting}
  3526. \fi}
  3527. \end{minipage}\\
  3528. The second \key{movq} instruction is problematic because both
  3529. arguments are stack locations. We suggest fixing this problem by
  3530. moving from the source location to the register \key{rax} and then
  3531. from \key{rax} to the destination location, as follows.
  3532. \begin{lstlisting}
  3533. movq -8(%rbp), %rax
  3534. movq %rax, -16(%rbp)
  3535. \end{lstlisting}
  3536. \begin{exercise}
  3537. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3538. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3539. Create three new example programs that are
  3540. designed to exercise all of the interesting cases in this pass.
  3541. %
  3542. {\if\edition\racketEd
  3543. In the \code{run-tests.rkt} script, add the following entry to the
  3544. list of \code{passes} and then run the script to test your compiler.
  3545. \begin{lstlisting}
  3546. (list "patch instructions" patch_instructions interp_x86-0)
  3547. \end{lstlisting}
  3548. \fi}
  3549. {\if\edition\pythonEd
  3550. Run the \code{run-tests.py} script to to check
  3551. whether the output programs produce the same result as the input
  3552. programs.
  3553. \fi}
  3554. \end{exercise}
  3555. \section{Generate Prelude and Conclusion}
  3556. \label{sec:print-x86}
  3557. \index{subject}{prelude}\index{subject}{conclusion}
  3558. The last step of the compiler from \LangVar{} to x86 is to generate
  3559. the \code{main} function with a prelude and conclusion wrapped around
  3560. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3561. discussed in Section~\ref{sec:x86}.
  3562. When running on Mac OS X, your compiler should prefix an underscore to
  3563. all labels, e.g., changing \key{main} to \key{\_main}.
  3564. %
  3565. \racket{The Racket call \code{(system-type 'os)} is useful for
  3566. determining which operating system the compiler is running on. It
  3567. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3568. %
  3569. \python{The Python \code{platform} library includes a \code{system()}
  3570. function that returns \code{'Linux'}, \code{'Windows'}, or
  3571. \code{'Darwin'} (for Mac).}
  3572. \begin{exercise}\normalfont\normalsize
  3573. %
  3574. Implement the \key{prelude\_and\_conclusion} pass in
  3575. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3576. %
  3577. {\if\edition\racketEd
  3578. In the \code{run-tests.rkt} script, add the following entry to the
  3579. list of \code{passes} and then run the script to test your compiler.
  3580. \begin{lstlisting}
  3581. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3582. \end{lstlisting}
  3583. %
  3584. Uncomment the call to the \key{compiler-tests} function
  3585. (Appendix~\ref{appendix:utilities}), which tests your complete
  3586. compiler by executing the generated x86 code. It translates the x86
  3587. AST that you produce into a string by invoking the \code{print-x86}
  3588. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3589. the provided \key{runtime.c} file to \key{runtime.o} using
  3590. \key{gcc}. Run the script to test your compiler.
  3591. %
  3592. \fi}
  3593. {\if\edition\pythonEd
  3594. %
  3595. Run the \code{run-tests.py} script to to check whether the output
  3596. programs produce the same result as the input programs. That script
  3597. translates the x86 AST that you produce into a string by invoking the
  3598. \code{repr} method that is implemented by the x86 AST classes in
  3599. \code{x86\_ast.py}.
  3600. %
  3601. \fi}
  3602. \end{exercise}
  3603. \section{Challenge: Partial Evaluator for \LangVar{}}
  3604. \label{sec:pe-Lvar}
  3605. \index{subject}{partial evaluation}
  3606. This section describes two optional challenge exercises that involve
  3607. adapting and improving the partial evaluator for \LangInt{} that was
  3608. introduced in Section~\ref{sec:partial-evaluation}.
  3609. \begin{exercise}\label{ex:pe-Lvar}
  3610. \normalfont\normalsize
  3611. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3612. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3613. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3614. %
  3615. \racket{\key{let} binding}\python{assignment}
  3616. %
  3617. to the \LangInt{} language, so you will need to add cases for them in
  3618. the \code{pe\_exp}
  3619. %
  3620. \racket{function.}
  3621. %
  3622. \python{and \code{pe\_stmt} functions.}
  3623. %
  3624. Once complete, add the partial evaluation pass to the front of your
  3625. compiler and make sure that your compiler still passes all of the
  3626. tests.
  3627. \end{exercise}
  3628. \begin{exercise}
  3629. \normalfont\normalsize
  3630. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3631. \code{pe\_add} auxiliary functions with functions that know more about
  3632. arithmetic. For example, your partial evaluator should translate
  3633. {\if\edition\racketEd
  3634. \[
  3635. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3636. \code{(+ 2 (read))}
  3637. \]
  3638. \fi}
  3639. {\if\edition\pythonEd
  3640. \[
  3641. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3642. \code{2 + input\_int()}
  3643. \]
  3644. \fi}
  3645. To accomplish this, the \code{pe\_exp} function should produce output
  3646. in the form of the $\itm{residual}$ non-terminal of the following
  3647. grammar. The idea is that when processing an addition expression, we
  3648. can always produce either 1) an integer constant, 2) an addition
  3649. expression with an integer constant on the left-hand side but not the
  3650. right-hand side, or 3) or an addition expression in which neither
  3651. subexpression is a constant.
  3652. {\if\edition\racketEd
  3653. \[
  3654. \begin{array}{lcl}
  3655. \itm{inert} &::=& \Var
  3656. \MID \LP\key{read}\RP
  3657. \MID \LP\key{-} ~\Var\RP
  3658. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3659. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3660. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3661. \itm{residual} &::=& \Int
  3662. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3663. \MID \itm{inert}
  3664. \end{array}
  3665. \]
  3666. \fi}
  3667. {\if\edition\pythonEd
  3668. \[
  3669. \begin{array}{lcl}
  3670. \itm{inert} &::=& \Var
  3671. \MID \key{input\_int}\LP\RP
  3672. \MID \key{-} \Var
  3673. \MID \key{-} \key{input\_int}\LP\RP
  3674. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3675. \itm{residual} &::=& \Int
  3676. \MID \Int ~ \key{+} ~ \itm{inert}
  3677. \MID \itm{inert}
  3678. \end{array}
  3679. \]
  3680. \fi}
  3681. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3682. inputs are $\itm{residual}$ expressions and they should return
  3683. $\itm{residual}$ expressions. Once the improvements are complete,
  3684. make sure that your compiler still passes all of the tests. After
  3685. all, fast code is useless if it produces incorrect results!
  3686. \end{exercise}
  3687. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3688. \chapter{Register Allocation}
  3689. \label{ch:register-allocation-Lvar}
  3690. \index{subject}{register allocation}
  3691. In Chapter~\ref{ch:Lvar} we compiled \LangVar{} to x86, storing
  3692. variables on the procedure call stack. It can take 10s to 100s of
  3693. cycles for the CPU to access locations on the stack whereas accessing
  3694. a register takes only a single cycle. In this chapter we improve the
  3695. efficiency of our generated code by storing some variables in
  3696. registers. The goal of register allocation is to fit as many variables
  3697. into registers as possible. Some programs have more variables than
  3698. registers so we cannot always map each variable to a different
  3699. register. Fortunately, it is common for different variables to be
  3700. in-use during different periods of time during program execution, and
  3701. in those cases we can map multiple variables to the same register.
  3702. The program in Figure~\ref{fig:reg-eg} serves as a running
  3703. example. The source program is on the left and the output of
  3704. instruction selection is on the right. The program is almost in the
  3705. x86 assembly language but it still uses variables. Consider variables
  3706. \code{x} and \code{z}. After the variable \code{x} is moved to
  3707. \code{z} it is no longer in-use. Variable \code{z}, on the other
  3708. hand, is used only after this point, so \code{x} and \code{z} could
  3709. share the same register.
  3710. \begin{figure}
  3711. \begin{minipage}{0.45\textwidth}
  3712. Example \LangVar{} program:
  3713. % var_test_28.rkt
  3714. {\if\edition\racketEd
  3715. \begin{lstlisting}
  3716. (let ([v 1])
  3717. (let ([w 42])
  3718. (let ([x (+ v 7)])
  3719. (let ([y x])
  3720. (let ([z (+ x w)])
  3721. (+ z (- y)))))))
  3722. \end{lstlisting}
  3723. \fi}
  3724. {\if\edition\pythonEd
  3725. \begin{lstlisting}
  3726. v = 1
  3727. w = 42
  3728. x = v + 7
  3729. y = x
  3730. z = x + w
  3731. print(z + (- y))
  3732. \end{lstlisting}
  3733. \fi}
  3734. \end{minipage}
  3735. \begin{minipage}{0.45\textwidth}
  3736. After instruction selection:
  3737. {\if\edition\racketEd
  3738. \begin{lstlisting}[frame=single]
  3739. locals-types:
  3740. x : Integer, y : Integer,
  3741. z : Integer, t : Integer,
  3742. v : Integer, w : Integer
  3743. start:
  3744. movq $1, v
  3745. movq $42, w
  3746. movq v, x
  3747. addq $7, x
  3748. movq x, y
  3749. movq x, z
  3750. addq w, z
  3751. movq y, t
  3752. negq t
  3753. movq z, %rax
  3754. addq t, %rax
  3755. jmp conclusion
  3756. \end{lstlisting}
  3757. \fi}
  3758. {\if\edition\pythonEd
  3759. \begin{lstlisting}[frame=single]
  3760. movq $1, v
  3761. movq $42, w
  3762. movq v, x
  3763. addq $7, x
  3764. movq x, y
  3765. movq x, z
  3766. addq w, z
  3767. movq y, tmp_0
  3768. negq tmp_0
  3769. movq z, tmp_1
  3770. addq tmp_0, tmp_1
  3771. movq tmp_1, %rdi
  3772. callq print_int
  3773. \end{lstlisting}
  3774. \fi}
  3775. \end{minipage}
  3776. \caption{A running example for register allocation.}
  3777. \label{fig:reg-eg}
  3778. \end{figure}
  3779. The topic of Section~\ref{sec:liveness-analysis-Lvar} is how to
  3780. compute where a variable is in-use. Once we have that information, we
  3781. compute which variables are in-use at the same time, i.e., which ones
  3782. \emph{interfere}\index{subject}{interfere} with each other, and
  3783. represent this relation as an undirected graph whose vertices are
  3784. variables and edges indicate when two variables interfere
  3785. (Section~\ref{sec:build-interference}). We then model register
  3786. allocation as a graph coloring problem
  3787. (Section~\ref{sec:graph-coloring}).
  3788. If we run out of registers despite these efforts, we place the
  3789. remaining variables on the stack, similar to what we did in
  3790. Chapter~\ref{ch:Lvar}. It is common to use the verb
  3791. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3792. location. The decision to spill a variable is handled as part of the
  3793. graph coloring process.
  3794. We make the simplifying assumption that each variable is assigned to
  3795. one location (a register or stack address). A more sophisticated
  3796. approach is to assign a variable to one or more locations in different
  3797. regions of the program. For example, if a variable is used many times
  3798. in short sequence and then only used again after many other
  3799. instructions, it could be more efficient to assign the variable to a
  3800. register during the initial sequence and then move it to the stack for
  3801. the rest of its lifetime. We refer the interested reader to
  3802. \citet{Cooper:2011aa} (Chapter 13) for more information about that
  3803. approach.
  3804. % discuss prioritizing variables based on how much they are used.
  3805. \section{Registers and Calling Conventions}
  3806. \label{sec:calling-conventions}
  3807. \index{subject}{calling conventions}
  3808. As we perform register allocation, we must be aware of the
  3809. \emph{calling conventions} \index{subject}{calling conventions} that
  3810. govern how functions calls are performed in x86.
  3811. %
  3812. Even though \LangVar{} does not include programmer-defined functions,
  3813. our generated code includes a \code{main} function that is called by
  3814. the operating system and our generated code contains calls to the
  3815. \code{read\_int} function.
  3816. Function calls require coordination between two pieces of code that
  3817. may be written by different programmers or generated by different
  3818. compilers. Here we follow the System V calling conventions that are
  3819. used by the GNU C compiler on Linux and
  3820. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3821. %
  3822. The calling conventions include rules about how functions share the
  3823. use of registers. In particular, the caller is responsible for freeing
  3824. up some registers prior to the function call for use by the callee.
  3825. These are called the \emph{caller-saved registers}
  3826. \index{subject}{caller-saved registers}
  3827. and they are
  3828. \begin{lstlisting}
  3829. rax rcx rdx rsi rdi r8 r9 r10 r11
  3830. \end{lstlisting}
  3831. On the other hand, the callee is responsible for preserving the values
  3832. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3833. which are
  3834. \begin{lstlisting}
  3835. rsp rbp rbx r12 r13 r14 r15
  3836. \end{lstlisting}
  3837. We can think about this caller/callee convention from two points of
  3838. view, the caller view and the callee view:
  3839. \begin{itemize}
  3840. \item The caller should assume that all the caller-saved registers get
  3841. overwritten with arbitrary values by the callee. On the other hand,
  3842. the caller can safely assume that all the callee-saved registers
  3843. retain their original values.
  3844. \item The callee can freely use any of the caller-saved registers.
  3845. However, if the callee wants to use a callee-saved register, the
  3846. callee must arrange to put the original value back in the register
  3847. prior to returning to the caller. This can be accomplished by saving
  3848. the value to the stack in the prelude of the function and restoring
  3849. the value in the conclusion of the function.
  3850. \end{itemize}
  3851. In x86, registers are also used for passing arguments to a function
  3852. and for the return value. In particular, the first six arguments of a
  3853. function are passed in the following six registers, in this order.
  3854. \index{subject}{argument-passing registers}
  3855. \index{subject}{parameter-passing registers}
  3856. \begin{lstlisting}
  3857. rdi rsi rdx rcx r8 r9
  3858. \end{lstlisting}
  3859. If there are more than six arguments, then the convention is to use
  3860. space on the frame of the caller for the rest of the
  3861. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3862. need more than six arguments.
  3863. %
  3864. \racket{For now, the only function we care about is \code{read\_int}
  3865. and it takes zero arguments.}
  3866. %
  3867. \python{For now, the only functions we care about are \code{read\_int}
  3868. and \code{print\_int}, which take zero and one argument, respectively.}
  3869. %
  3870. The register \code{rax} is used for the return value of a function.
  3871. The next question is how these calling conventions impact register
  3872. allocation. Consider the \LangVar{} program in
  3873. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3874. example from the caller point of view and then from the callee point
  3875. of view. We refer to a variable that is in-use during a function call
  3876. as being a \emph{call-live variable}\index{subject}{call-live
  3877. variable}.
  3878. The program makes two calls to \READOP{}. The variable \code{x} is
  3879. call-live because it is in-use during the second call to \READOP{}; we
  3880. must ensure that the value in \code{x} does not get overwritten during
  3881. the call to \READOP{}. One obvious approach is to save all the values
  3882. that reside in caller-saved registers to the stack prior to each
  3883. function call, and restore them after each call. That way, if the
  3884. register allocator chooses to assign \code{x} to a caller-saved
  3885. register, its value will be preserved across the call to \READOP{}.
  3886. However, saving and restoring to the stack is relatively slow. If
  3887. \code{x} is not used many times, it may be better to assign \code{x}
  3888. to a stack location in the first place. Or better yet, if we can
  3889. arrange for \code{x} to be placed in a callee-saved register, then it
  3890. won't need to be saved and restored during function calls.
  3891. The approach that we recommend for call-live variables is to either
  3892. assign them to callee-saved registers or to spill them to the
  3893. stack. On the other hand, for variables that are not call-live, we try
  3894. the following alternatives in order 1) look for an available
  3895. caller-saved register (to leave room for other variables in the
  3896. callee-saved register), 2) look for a callee-saved register, and 3)
  3897. spill the variable to the stack.
  3898. It is straightforward to implement this approach in a graph coloring
  3899. register allocator. First, we know which variables are call-live
  3900. because we already need to compute which variables are in-use at every
  3901. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3902. we build the interference graph
  3903. (Section~\ref{sec:build-interference}), we can place an edge between
  3904. each of the call-live variables and the caller-saved registers in the
  3905. interference graph. This will prevent the graph coloring algorithm
  3906. from assigning them to caller-saved registers.
  3907. Returning to the example in
  3908. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3909. generated x86 code on the right-hand side. Notice that variable
  3910. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3911. is already in a safe place during the second call to
  3912. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3913. \code{rcx}, a caller-saved register, because \code{y} is not a
  3914. call-live variable.
  3915. Next we analyze the example from the callee point of view, focusing on
  3916. the prelude and conclusion of the \code{main} function. As usual the
  3917. prelude begins with saving the \code{rbp} register to the stack and
  3918. setting the \code{rbp} to the current stack pointer. We now know why
  3919. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3920. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3921. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3922. (\code{x}). The other callee-saved registers are not saved in the
  3923. prelude because they are not used. The prelude subtracts 8 bytes from
  3924. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3925. conclusion, we see that \code{rbx} is restored from the stack with a
  3926. \code{popq} instruction.
  3927. \index{subject}{prelude}\index{subject}{conclusion}
  3928. \begin{figure}[tp]
  3929. \begin{minipage}{0.45\textwidth}
  3930. Example \LangVar{} program:
  3931. %var_test_14.rkt
  3932. {\if\edition\racketEd
  3933. \begin{lstlisting}
  3934. (let ([x (read)])
  3935. (let ([y (read)])
  3936. (+ (+ x y) 42)))
  3937. \end{lstlisting}
  3938. \fi}
  3939. {\if\edition\pythonEd
  3940. \begin{lstlisting}
  3941. x = input_int()
  3942. y = input_int()
  3943. print((x + y) + 42)
  3944. \end{lstlisting}
  3945. \fi}
  3946. \end{minipage}
  3947. \begin{minipage}{0.45\textwidth}
  3948. Generated x86 assembly:
  3949. {\if\edition\racketEd
  3950. \begin{lstlisting}
  3951. start:
  3952. callq read_int
  3953. movq %rax, %rbx
  3954. callq read_int
  3955. movq %rax, %rcx
  3956. addq %rcx, %rbx
  3957. movq %rbx, %rax
  3958. addq $42, %rax
  3959. jmp _conclusion
  3960. .globl main
  3961. main:
  3962. pushq %rbp
  3963. movq %rsp, %rbp
  3964. pushq %rbx
  3965. subq $8, %rsp
  3966. jmp start
  3967. conclusion:
  3968. addq $8, %rsp
  3969. popq %rbx
  3970. popq %rbp
  3971. retq
  3972. \end{lstlisting}
  3973. \fi}
  3974. {\if\edition\pythonEd
  3975. \begin{lstlisting}
  3976. .globl main
  3977. main:
  3978. pushq %rbp
  3979. movq %rsp, %rbp
  3980. pushq %rbx
  3981. subq $8, %rsp
  3982. callq read_int
  3983. movq %rax, %rbx
  3984. callq read_int
  3985. movq %rax, %rcx
  3986. movq %rbx, %rdx
  3987. addq %rcx, %rdx
  3988. movq %rdx, %rcx
  3989. addq $42, %rcx
  3990. movq %rcx, %rdi
  3991. callq print_int
  3992. addq $8, %rsp
  3993. popq %rbx
  3994. popq %rbp
  3995. retq
  3996. \end{lstlisting}
  3997. \fi}
  3998. \end{minipage}
  3999. \caption{An example with function calls.}
  4000. \label{fig:example-calling-conventions}
  4001. \end{figure}
  4002. %\clearpage
  4003. \section{Liveness Analysis}
  4004. \label{sec:liveness-analysis-Lvar}
  4005. \index{subject}{liveness analysis}
  4006. The \code{uncover\_live} \racket{pass}\python{function} performs
  4007. \emph{liveness analysis}, that is, it discovers which variables are
  4008. in-use in different regions of a program.
  4009. %
  4010. A variable or register is \emph{live} at a program point if its
  4011. current value is used at some later point in the program. We refer to
  4012. variables, stack locations, and registers collectively as
  4013. \emph{locations}.
  4014. %
  4015. Consider the following code fragment in which there are two writes to
  4016. \code{b}. Are variables \code{a} and \code{b} both live at the same
  4017. time?
  4018. \begin{center}
  4019. \begin{minipage}{0.96\textwidth}
  4020. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4021. movq $5, a
  4022. movq $30, b
  4023. movq a, c
  4024. movq $10, b
  4025. addq b, c
  4026. \end{lstlisting}
  4027. \end{minipage}
  4028. \end{center}
  4029. The answer is no because \code{a} is live from line 1 to 3 and
  4030. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4031. line 2 is never used because it is overwritten (line 4) before the
  4032. next read (line 5).
  4033. The live locations for each instruction can be computed by traversing
  4034. the instruction sequence back to front (i.e., backwards in execution
  4035. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4036. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4037. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  4038. locations before instruction $I_k$. \racket{We recommend representing
  4039. these sets with the Racket \code{set} data structure described in
  4040. Figure~\ref{fig:set}.} \python{We recommend representing these sets
  4041. with the Python
  4042. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4043. data structure.}
  4044. {\if\edition\racketEd
  4045. \begin{figure}[tp]
  4046. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4047. \small
  4048. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4049. A \emph{set} is an unordered collection of elements without duplicates.
  4050. Here are some of the operations defined on sets.
  4051. \index{subject}{set}
  4052. \begin{description}
  4053. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4054. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4055. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4056. difference of the two sets.
  4057. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4058. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4059. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4060. \end{description}
  4061. \end{tcolorbox}
  4062. %\end{wrapfigure}
  4063. \caption{The \code{set} data structure.}
  4064. \label{fig:set}
  4065. \end{figure}
  4066. \fi}
  4067. The live locations after an instruction are always the same as the
  4068. live locations before the next instruction.
  4069. \index{subject}{live-after} \index{subject}{live-before}
  4070. \begin{equation} \label{eq:live-after-before-next}
  4071. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4072. \end{equation}
  4073. To start things off, there are no live locations after the last
  4074. instruction, so
  4075. \begin{equation}\label{eq:live-last-empty}
  4076. L_{\mathsf{after}}(n) = \emptyset
  4077. \end{equation}
  4078. We then apply the following rule repeatedly, traversing the
  4079. instruction sequence back to front.
  4080. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4081. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4082. \end{equation}
  4083. where $W(k)$ are the locations written to by instruction $I_k$ and
  4084. $R(k)$ are the locations read by instruction $I_k$.
  4085. {\if\edition\racketEd
  4086. %
  4087. There is a special case for \code{jmp} instructions. The locations
  4088. that are live before a \code{jmp} should be the locations in
  4089. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4090. maintaining an alist named \code{label->live} that maps each label to
  4091. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4092. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4093. conclusion. (For example, see Figure~\ref{fig:reg-eg}.) The
  4094. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4095. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4096. %
  4097. \fi}
  4098. Let us walk through the above example, applying these formulas
  4099. starting with the instruction on line 5. We collect the answers in
  4100. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4101. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4102. instruction (formula~\ref{eq:live-last-empty}). The
  4103. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4104. because it reads from variables \code{b} and \code{c}
  4105. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4106. \[
  4107. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4108. \]
  4109. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4110. the live-before set from line 5 to be the live-after set for this
  4111. instruction (formula~\ref{eq:live-after-before-next}).
  4112. \[
  4113. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4114. \]
  4115. This move instruction writes to \code{b} and does not read from any
  4116. variables, so we have the following live-before set
  4117. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4118. \[
  4119. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4120. \]
  4121. The live-before for instruction \code{movq a, c}
  4122. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4123. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4124. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4125. variable that is not live and does not read from a variable.
  4126. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4127. because it writes to variable \code{a}.
  4128. \begin{figure}[tbp]
  4129. \begin{minipage}{0.45\textwidth}
  4130. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4131. movq $5, a
  4132. movq $30, b
  4133. movq a, c
  4134. movq $10, b
  4135. addq b, c
  4136. \end{lstlisting}
  4137. \end{minipage}
  4138. \vrule\hspace{10pt}
  4139. \begin{minipage}{0.45\textwidth}
  4140. \begin{align*}
  4141. L_{\mathsf{before}}(1)= \emptyset,
  4142. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4143. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4144. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4145. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4146. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4147. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4148. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4149. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4150. L_{\mathsf{after}}(5)= \emptyset
  4151. \end{align*}
  4152. \end{minipage}
  4153. \caption{Example output of liveness analysis on a short example.}
  4154. \label{fig:liveness-example-0}
  4155. \end{figure}
  4156. \begin{exercise}\normalfont\normalsize
  4157. Perform liveness analysis by hand on the running example in
  4158. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4159. sets for each instruction. Compare your answers to the solution
  4160. shown in Figure~\ref{fig:live-eg}.
  4161. \end{exercise}
  4162. \begin{figure}[tp]
  4163. \hspace{20pt}
  4164. \begin{minipage}{0.45\textwidth}
  4165. {\if\edition\racketEd
  4166. \begin{lstlisting}
  4167. |$\{\ttm{rsp}\}$|
  4168. movq $1, v
  4169. |$\{\ttm{v},\ttm{rsp}\}$|
  4170. movq $42, w
  4171. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4172. movq v, x
  4173. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4174. addq $7, x
  4175. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4176. movq x, y
  4177. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4178. movq x, z
  4179. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4180. addq w, z
  4181. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4182. movq y, t
  4183. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4184. negq t
  4185. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4186. movq z, %rax
  4187. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4188. addq t, %rax
  4189. |$\{\ttm{rax},\ttm{rsp}\}$|
  4190. jmp conclusion
  4191. \end{lstlisting}
  4192. \fi}
  4193. {\if\edition\pythonEd
  4194. \begin{lstlisting}
  4195. movq $1, v
  4196. |$\{\ttm{v}\}$|
  4197. movq $42, w
  4198. |$\{\ttm{w}, \ttm{v}\}$|
  4199. movq v, x
  4200. |$\{\ttm{w}, \ttm{x}\}$|
  4201. addq $7, x
  4202. |$\{\ttm{w}, \ttm{x}\}$|
  4203. movq x, y
  4204. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4205. movq x, z
  4206. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4207. addq w, z
  4208. |$\{\ttm{y}, \ttm{z}\}$|
  4209. movq y, tmp_0
  4210. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4211. negq tmp_0
  4212. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4213. movq z, tmp_1
  4214. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4215. addq tmp_0, tmp_1
  4216. |$\{\ttm{tmp\_1}\}$|
  4217. movq tmp_1, %rdi
  4218. |$\{\ttm{rdi}\}$|
  4219. callq print_int
  4220. |$\{\}$|
  4221. \end{lstlisting}
  4222. \fi}
  4223. \end{minipage}
  4224. \caption{The running example annotated with live-after sets.}
  4225. \label{fig:live-eg}
  4226. \end{figure}
  4227. \begin{exercise}\normalfont\normalsize
  4228. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4229. %
  4230. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4231. field of the \code{Block} structure.}
  4232. %
  4233. \python{Return a dictionary that maps each instruction to its
  4234. live-after set.}
  4235. %
  4236. \racket{We recommend creating an auxiliary function that takes a list
  4237. of instructions and an initial live-after set (typically empty) and
  4238. returns the list of live-after sets.}
  4239. %
  4240. We recommend creating auxiliary functions to 1) compute the set
  4241. of locations that appear in an \Arg{}, 2) compute the locations read
  4242. by an instruction (the $R$ function), and 3) the locations written by
  4243. an instruction (the $W$ function). The \code{callq} instruction should
  4244. include all of the caller-saved registers in its write-set $W$ because
  4245. the calling convention says that those registers may be written to
  4246. during the function call. Likewise, the \code{callq} instruction
  4247. should include the appropriate argument-passing registers in its
  4248. read-set $R$, depending on the arity of the function being
  4249. called. (This is why the abstract syntax for \code{callq} includes the
  4250. arity.)
  4251. \end{exercise}
  4252. %\clearpage
  4253. \section{Build the Interference Graph}
  4254. \label{sec:build-interference}
  4255. {\if\edition\racketEd
  4256. \begin{figure}[tp]
  4257. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4258. \small
  4259. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4260. A \emph{graph} is a collection of vertices and edges where each
  4261. edge connects two vertices. A graph is \emph{directed} if each
  4262. edge points from a source to a target. Otherwise the graph is
  4263. \emph{undirected}.
  4264. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4265. \begin{description}
  4266. %% We currently don't use directed graphs. We instead use
  4267. %% directed multi-graphs. -Jeremy
  4268. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4269. directed graph from a list of edges. Each edge is a list
  4270. containing the source and target vertex.
  4271. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4272. undirected graph from a list of edges. Each edge is represented by
  4273. a list containing two vertices.
  4274. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4275. inserts a vertex into the graph.
  4276. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4277. inserts an edge between the two vertices.
  4278. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4279. returns a sequence of vertices adjacent to the vertex.
  4280. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4281. returns a sequence of all vertices in the graph.
  4282. \end{description}
  4283. \end{tcolorbox}
  4284. %\end{wrapfigure}
  4285. \caption{The Racket \code{graph} package.}
  4286. \label{fig:graph}
  4287. \end{figure}
  4288. \fi}
  4289. Based on the liveness analysis, we know where each location is live.
  4290. However, during register allocation, we need to answer questions of
  4291. the specific form: are locations $u$ and $v$ live at the same time?
  4292. (And therefore cannot be assigned to the same register.) To make this
  4293. question more efficient to answer, we create an explicit data
  4294. structure, an \emph{interference graph}\index{subject}{interference
  4295. graph}. An interference graph is an undirected graph that has an
  4296. edge between two locations if they are live at the same time, that is,
  4297. if they interfere with each other.
  4298. %
  4299. \racket{We recommend using the Racket \code{graph} package
  4300. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4301. %
  4302. \python{We provide implementations of directed and undirected graph
  4303. data structures in the file \code{graph.py} of the support code.}
  4304. A straightforward way to compute the interference graph is to look at
  4305. the set of live locations between each instruction and add an edge to
  4306. the graph for every pair of variables in the same set. This approach
  4307. is less than ideal for two reasons. First, it can be expensive because
  4308. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4309. locations. Second, in the special case where two locations hold the
  4310. same value (because one was assigned to the other), they can be live
  4311. at the same time without interfering with each other.
  4312. A better way to compute the interference graph is to focus on
  4313. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4314. must not overwrite something in a live location. So for each
  4315. instruction, we create an edge between the locations being written to
  4316. and the live locations. (Except that a location never interferes with
  4317. itself.) For the \key{callq} instruction, we consider all of the
  4318. caller-saved registers as being written to, so an edge is added
  4319. between every live variable and every caller-saved register. Also, for
  4320. \key{movq} there is the special case of two variables holding the same
  4321. value. If a live variable $v$ is the same as the source of the
  4322. \key{movq}, then there is no need to add an edge between $v$ and the
  4323. destination, because they both hold the same value.
  4324. %
  4325. So we have the following two rules.
  4326. \begin{enumerate}
  4327. \item If instruction $I_k$ is a move instruction of the form
  4328. \key{movq} $s$\key{,} $d$, then for every $v \in
  4329. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4330. $(d,v)$.
  4331. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4332. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4333. $(d,v)$.
  4334. \end{enumerate}
  4335. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4336. the above rules to each instruction. We highlight a few of the
  4337. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4338. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4339. so \code{v} interferes with \code{rsp}.}
  4340. %
  4341. \python{The first instruction is \lstinline{movq $1, v} and the
  4342. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4343. no interference because $\ttm{v}$ is the destination of the move.}
  4344. %
  4345. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4346. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4347. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4348. %
  4349. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4350. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4351. $\ttm{x}$ interferes with \ttm{w}.}
  4352. %
  4353. \racket{The next instruction is \lstinline{movq x, y} and the
  4354. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4355. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4356. \ttm{x} because \ttm{x} is the source of the move and therefore
  4357. \ttm{x} and \ttm{y} hold the same value.}
  4358. %
  4359. \python{The next instruction is \lstinline{movq x, y} and the
  4360. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4361. applies, so \ttm{y} interferes with \ttm{w} but not
  4362. \ttm{x} because \ttm{x} is the source of the move and therefore
  4363. \ttm{x} and \ttm{y} hold the same value.}
  4364. %
  4365. Figure~\ref{fig:interference-results} lists the interference results
  4366. for all of the instructions and the resulting interference graph is
  4367. shown in Figure~\ref{fig:interfere}.
  4368. \begin{figure}[tbp]
  4369. \begin{quote}
  4370. {\if\edition\racketEd
  4371. \begin{tabular}{ll}
  4372. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4373. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4374. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4375. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4376. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4377. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4378. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4379. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4380. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4381. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4382. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4383. \lstinline!jmp conclusion!& no interference.
  4384. \end{tabular}
  4385. \fi}
  4386. {\if\edition\pythonEd
  4387. \begin{tabular}{ll}
  4388. \lstinline!movq $1, v!& no interference\\
  4389. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4390. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4391. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4392. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4393. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4394. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4395. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4396. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4397. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4398. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4399. \lstinline!movq tmp_1, %rdi! & no interference \\
  4400. \lstinline!callq print_int!& no interference.
  4401. \end{tabular}
  4402. \fi}
  4403. \end{quote}
  4404. \caption{Interference results for the running example.}
  4405. \label{fig:interference-results}
  4406. \end{figure}
  4407. \begin{figure}[tbp]
  4408. \large
  4409. {\if\edition\racketEd
  4410. \[
  4411. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4412. \node (rax) at (0,0) {$\ttm{rax}$};
  4413. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4414. \node (t1) at (0,2) {$\ttm{t}$};
  4415. \node (z) at (3,2) {$\ttm{z}$};
  4416. \node (x) at (6,2) {$\ttm{x}$};
  4417. \node (y) at (3,0) {$\ttm{y}$};
  4418. \node (w) at (6,0) {$\ttm{w}$};
  4419. \node (v) at (9,0) {$\ttm{v}$};
  4420. \draw (t1) to (rax);
  4421. \draw (t1) to (z);
  4422. \draw (z) to (y);
  4423. \draw (z) to (w);
  4424. \draw (x) to (w);
  4425. \draw (y) to (w);
  4426. \draw (v) to (w);
  4427. \draw (v) to (rsp);
  4428. \draw (w) to (rsp);
  4429. \draw (x) to (rsp);
  4430. \draw (y) to (rsp);
  4431. \path[-.,bend left=15] (z) edge node {} (rsp);
  4432. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4433. \draw (rax) to (rsp);
  4434. \end{tikzpicture}
  4435. \]
  4436. \fi}
  4437. {\if\edition\pythonEd
  4438. \[
  4439. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4440. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4441. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  4442. \node (z) at (3,2) {$\ttm{z}$};
  4443. \node (x) at (6,2) {$\ttm{x}$};
  4444. \node (y) at (3,0) {$\ttm{y}$};
  4445. \node (w) at (6,0) {$\ttm{w}$};
  4446. \node (v) at (9,0) {$\ttm{v}$};
  4447. \draw (t0) to (t1);
  4448. \draw (t0) to (z);
  4449. \draw (z) to (y);
  4450. \draw (z) to (w);
  4451. \draw (x) to (w);
  4452. \draw (y) to (w);
  4453. \draw (v) to (w);
  4454. \end{tikzpicture}
  4455. \]
  4456. \fi}
  4457. \caption{The interference graph of the example program.}
  4458. \label{fig:interfere}
  4459. \end{figure}
  4460. %% Our next concern is to choose a data structure for representing the
  4461. %% interference graph. There are many choices for how to represent a
  4462. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4463. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4464. %% data structure is to study the algorithm that uses the data structure,
  4465. %% determine what operations need to be performed, and then choose the
  4466. %% data structure that provide the most efficient implementations of
  4467. %% those operations. Often times the choice of data structure can have an
  4468. %% effect on the time complexity of the algorithm, as it does here. If
  4469. %% you skim the next section, you will see that the register allocation
  4470. %% algorithm needs to ask the graph for all of its vertices and, given a
  4471. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4472. %% correct choice of graph representation is that of an adjacency
  4473. %% list. There are helper functions in \code{utilities.rkt} for
  4474. %% representing graphs using the adjacency list representation:
  4475. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4476. %% (Appendix~\ref{appendix:utilities}).
  4477. %% %
  4478. %% \margincomment{\footnotesize To do: change to use the
  4479. %% Racket graph library. \\ --Jeremy}
  4480. %% %
  4481. %% In particular, those functions use a hash table to map each vertex to
  4482. %% the set of adjacent vertices, and the sets are represented using
  4483. %% Racket's \key{set}, which is also a hash table.
  4484. \begin{exercise}\normalfont\normalsize
  4485. \racket{Implement the compiler pass named \code{build\_interference} according
  4486. to the algorithm suggested above. We recommend using the Racket
  4487. \code{graph} package to create and inspect the interference graph.
  4488. The output graph of this pass should be stored in the $\itm{info}$ field of
  4489. the program, under the key \code{conflicts}.}
  4490. %
  4491. \python{Implement a function named \code{build\_interference}
  4492. according to the algorithm suggested above that
  4493. returns the interference graph.}
  4494. \end{exercise}
  4495. \section{Graph Coloring via Sudoku}
  4496. \label{sec:graph-coloring}
  4497. \index{subject}{graph coloring}
  4498. \index{subject}{Sudoku}
  4499. \index{subject}{color}
  4500. We come to the main event of this chapter, mapping variables to
  4501. registers and stack locations. Variables that interfere with each
  4502. other must be mapped to different locations. In terms of the
  4503. interference graph, this means that adjacent vertices must be mapped
  4504. to different locations. If we think of locations as colors, the
  4505. register allocation problem becomes the graph coloring
  4506. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4507. The reader may be more familiar with the graph coloring problem than he
  4508. or she realizes; the popular game of Sudoku is an instance of the
  4509. graph coloring problem. The following describes how to build a graph
  4510. out of an initial Sudoku board.
  4511. \begin{itemize}
  4512. \item There is one vertex in the graph for each Sudoku square.
  4513. \item There is an edge between two vertices if the corresponding squares
  4514. are in the same row, in the same column, or if the squares are in
  4515. the same $3\times 3$ region.
  4516. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4517. \item Based on the initial assignment of numbers to squares in the
  4518. Sudoku board, assign the corresponding colors to the corresponding
  4519. vertices in the graph.
  4520. \end{itemize}
  4521. If you can color the remaining vertices in the graph with the nine
  4522. colors, then you have also solved the corresponding game of Sudoku.
  4523. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4524. the corresponding graph with colored vertices. We map the Sudoku
  4525. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4526. sampling of the vertices (the colored ones) because showing edges for
  4527. all of the vertices would make the graph unreadable.
  4528. \begin{figure}[tbp]
  4529. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4530. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4531. \caption{A Sudoku game board and the corresponding colored graph.}
  4532. \label{fig:sudoku-graph}
  4533. \end{figure}
  4534. Some techniques for playing Sudoku correspond to heuristics used in
  4535. graph coloring algorithms. For example, one of the basic techniques
  4536. for Sudoku is called Pencil Marks. The idea is to use a process of
  4537. elimination to determine what numbers are no longer available for a
  4538. square and write down those numbers in the square (writing very
  4539. small). For example, if the number $1$ is assigned to a square, then
  4540. write the pencil mark $1$ in all the squares in the same row, column,
  4541. and region to indicate that $1$ is no longer an option for those other
  4542. squares.
  4543. %
  4544. The Pencil Marks technique corresponds to the notion of
  4545. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4546. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4547. are no longer available. In graph terminology, we have the following
  4548. definition:
  4549. \begin{equation*}
  4550. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4551. \text{ and } \mathrm{color}(v) = c \}
  4552. \end{equation*}
  4553. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4554. edge with $u$.
  4555. The Pencil Marks technique leads to a simple strategy for filling in
  4556. numbers: if there is a square with only one possible number left, then
  4557. choose that number! But what if there are no squares with only one
  4558. possibility left? One brute-force approach is to try them all: choose
  4559. the first one and if that ultimately leads to a solution, great. If
  4560. not, backtrack and choose the next possibility. One good thing about
  4561. Pencil Marks is that it reduces the degree of branching in the search
  4562. tree. Nevertheless, backtracking can be terribly time consuming. One
  4563. way to reduce the amount of backtracking is to use the
  4564. most-constrained-first heuristic (aka. minimum remaining
  4565. values)~\citep{Russell2003}. That is, when choosing a square, always
  4566. choose one with the fewest possibilities left (the vertex with the
  4567. highest saturation). The idea is that choosing highly constrained
  4568. squares earlier rather than later is better because later on there may
  4569. not be any possibilities left in the highly saturated squares.
  4570. However, register allocation is easier than Sudoku because the
  4571. register allocator can fall back to assigning variables to stack
  4572. locations when the registers run out. Thus, it makes sense to replace
  4573. backtracking with greedy search: make the best choice at the time and
  4574. keep going. We still wish to minimize the number of colors needed, so
  4575. we use the most-constrained-first heuristic in the greedy search.
  4576. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4577. algorithm for register allocation based on saturation and the
  4578. most-constrained-first heuristic. It is roughly equivalent to the
  4579. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4580. %,Gebremedhin:1999fk,Omari:2006uq
  4581. Just as in Sudoku, the algorithm represents colors with integers. The
  4582. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4583. for register allocation. The integers $k$ and larger correspond to
  4584. stack locations. The registers that are not used for register
  4585. allocation, such as \code{rax}, are assigned to negative integers. In
  4586. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4587. %% One might wonder why we include registers at all in the liveness
  4588. %% analysis and interference graph. For example, we never allocate a
  4589. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4590. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4591. %% to use register for passing arguments to functions, it will be
  4592. %% necessary for those registers to appear in the interference graph
  4593. %% because those registers will also be assigned to variables, and we
  4594. %% don't want those two uses to encroach on each other. Regarding
  4595. %% registers such as \code{rax} and \code{rsp} that are not used for
  4596. %% variables, we could omit them from the interference graph but that
  4597. %% would require adding special cases to our algorithm, which would
  4598. %% complicate the logic for little gain.
  4599. \begin{figure}[btp]
  4600. \centering
  4601. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4602. Algorithm: DSATUR
  4603. Input: a graph |$G$|
  4604. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4605. |$W \gets \mathrm{vertices}(G)$|
  4606. while |$W \neq \emptyset$| do
  4607. pick a vertex |$u$| from |$W$| with the highest saturation,
  4608. breaking ties randomly
  4609. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4610. |$\mathrm{color}[u] \gets c$|
  4611. |$W \gets W - \{u\}$|
  4612. \end{lstlisting}
  4613. \caption{The saturation-based greedy graph coloring algorithm.}
  4614. \label{fig:satur-algo}
  4615. \end{figure}
  4616. {\if\edition\racketEd
  4617. With the DSATUR algorithm in hand, let us return to the running
  4618. example and consider how to color the interference graph in
  4619. Figure~\ref{fig:interfere}.
  4620. %
  4621. We start by assigning the register nodes to their own color. For
  4622. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4623. assigned $-2$. The variables are not yet colored, so they are
  4624. annotated with a dash. We then update the saturation for vertices that
  4625. are adjacent to a register, obtaining the following annotated
  4626. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4627. it interferes with both \code{rax} and \code{rsp}.
  4628. \[
  4629. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4630. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4631. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4632. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4633. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4634. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4635. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4636. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4637. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4638. \draw (t1) to (rax);
  4639. \draw (t1) to (z);
  4640. \draw (z) to (y);
  4641. \draw (z) to (w);
  4642. \draw (x) to (w);
  4643. \draw (y) to (w);
  4644. \draw (v) to (w);
  4645. \draw (v) to (rsp);
  4646. \draw (w) to (rsp);
  4647. \draw (x) to (rsp);
  4648. \draw (y) to (rsp);
  4649. \path[-.,bend left=15] (z) edge node {} (rsp);
  4650. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4651. \draw (rax) to (rsp);
  4652. \end{tikzpicture}
  4653. \]
  4654. The algorithm says to select a maximally saturated vertex. So we pick
  4655. $\ttm{t}$ and color it with the first available integer, which is
  4656. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4657. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4658. \[
  4659. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4660. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4661. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4662. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4663. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4664. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4665. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4666. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4667. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4668. \draw (t1) to (rax);
  4669. \draw (t1) to (z);
  4670. \draw (z) to (y);
  4671. \draw (z) to (w);
  4672. \draw (x) to (w);
  4673. \draw (y) to (w);
  4674. \draw (v) to (w);
  4675. \draw (v) to (rsp);
  4676. \draw (w) to (rsp);
  4677. \draw (x) to (rsp);
  4678. \draw (y) to (rsp);
  4679. \path[-.,bend left=15] (z) edge node {} (rsp);
  4680. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4681. \draw (rax) to (rsp);
  4682. \end{tikzpicture}
  4683. \]
  4684. We repeat the process, selecting a maximally saturated vertex,
  4685. choosing is \code{z}, and color it with the first available number, which
  4686. is $1$. We add $1$ to the saturation for the neighboring vertices
  4687. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4688. \[
  4689. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4690. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4691. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4692. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4693. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4694. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4695. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4696. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4697. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4698. \draw (t1) to (rax);
  4699. \draw (t1) to (z);
  4700. \draw (z) to (y);
  4701. \draw (z) to (w);
  4702. \draw (x) to (w);
  4703. \draw (y) to (w);
  4704. \draw (v) to (w);
  4705. \draw (v) to (rsp);
  4706. \draw (w) to (rsp);
  4707. \draw (x) to (rsp);
  4708. \draw (y) to (rsp);
  4709. \path[-.,bend left=15] (z) edge node {} (rsp);
  4710. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4711. \draw (rax) to (rsp);
  4712. \end{tikzpicture}
  4713. \]
  4714. The most saturated vertices are now \code{w} and \code{y}. We color
  4715. \code{w} with the first available color, which is $0$.
  4716. \[
  4717. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4718. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4719. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4720. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4721. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4722. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4723. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4724. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4725. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4726. \draw (t1) to (rax);
  4727. \draw (t1) to (z);
  4728. \draw (z) to (y);
  4729. \draw (z) to (w);
  4730. \draw (x) to (w);
  4731. \draw (y) to (w);
  4732. \draw (v) to (w);
  4733. \draw (v) to (rsp);
  4734. \draw (w) to (rsp);
  4735. \draw (x) to (rsp);
  4736. \draw (y) to (rsp);
  4737. \path[-.,bend left=15] (z) edge node {} (rsp);
  4738. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4739. \draw (rax) to (rsp);
  4740. \end{tikzpicture}
  4741. \]
  4742. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4743. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4744. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4745. and \code{z}, whose colors are $0$ and $1$ respectively.
  4746. \[
  4747. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4748. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4749. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4750. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4751. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4752. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4753. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4754. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4755. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4756. \draw (t1) to (rax);
  4757. \draw (t1) to (z);
  4758. \draw (z) to (y);
  4759. \draw (z) to (w);
  4760. \draw (x) to (w);
  4761. \draw (y) to (w);
  4762. \draw (v) to (w);
  4763. \draw (v) to (rsp);
  4764. \draw (w) to (rsp);
  4765. \draw (x) to (rsp);
  4766. \draw (y) to (rsp);
  4767. \path[-.,bend left=15] (z) edge node {} (rsp);
  4768. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4769. \draw (rax) to (rsp);
  4770. \end{tikzpicture}
  4771. \]
  4772. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  4773. \[
  4774. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4775. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4776. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4777. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4778. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4779. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4780. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4781. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4782. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4783. \draw (t1) to (rax);
  4784. \draw (t1) to (z);
  4785. \draw (z) to (y);
  4786. \draw (z) to (w);
  4787. \draw (x) to (w);
  4788. \draw (y) to (w);
  4789. \draw (v) to (w);
  4790. \draw (v) to (rsp);
  4791. \draw (w) to (rsp);
  4792. \draw (x) to (rsp);
  4793. \draw (y) to (rsp);
  4794. \path[-.,bend left=15] (z) edge node {} (rsp);
  4795. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4796. \draw (rax) to (rsp);
  4797. \end{tikzpicture}
  4798. \]
  4799. In the last step of the algorithm, we color \code{x} with $1$.
  4800. \[
  4801. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4802. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4803. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4804. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4805. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4806. \node (x) at (6,2) {$\ttm{x}:1,\{0,-2\}$};
  4807. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4808. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4809. \node (v) at (10,0) {$\ttm{v}:1,\{0,-2\}$};
  4810. \draw (t1) to (rax);
  4811. \draw (t1) to (z);
  4812. \draw (z) to (y);
  4813. \draw (z) to (w);
  4814. \draw (x) to (w);
  4815. \draw (y) to (w);
  4816. \draw (v) to (w);
  4817. \draw (v) to (rsp);
  4818. \draw (w) to (rsp);
  4819. \draw (x) to (rsp);
  4820. \draw (y) to (rsp);
  4821. \path[-.,bend left=15] (z) edge node {} (rsp);
  4822. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4823. \draw (rax) to (rsp);
  4824. \end{tikzpicture}
  4825. \]
  4826. So we obtain the following coloring:
  4827. \[
  4828. \{
  4829. \ttm{rax} \mapsto -1,
  4830. \ttm{rsp} \mapsto -2,
  4831. \ttm{t} \mapsto 0,
  4832. \ttm{z} \mapsto 1,
  4833. \ttm{x} \mapsto 1,
  4834. \ttm{y} \mapsto 2,
  4835. \ttm{w} \mapsto 0,
  4836. \ttm{v} \mapsto 1
  4837. \}
  4838. \]
  4839. \fi}
  4840. %
  4841. {\if\edition\pythonEd
  4842. %
  4843. With the DSATUR algorithm in hand, let us return to the running
  4844. example and consider how to color the interference graph in
  4845. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4846. to indicate that it has not yet been assigned a color. The saturation
  4847. sets are also shown for each node; all of them start as the empty set.
  4848. (We do not include the register nodes in the graph below because there
  4849. were no interference edges involving registers in this program, but in
  4850. general there can be.)
  4851. %
  4852. \[
  4853. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4854. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4855. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4856. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4857. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4858. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4859. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4860. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4861. \draw (t0) to (t1);
  4862. \draw (t0) to (z);
  4863. \draw (z) to (y);
  4864. \draw (z) to (w);
  4865. \draw (x) to (w);
  4866. \draw (y) to (w);
  4867. \draw (v) to (w);
  4868. \end{tikzpicture}
  4869. \]
  4870. The algorithm says to select a maximally saturated vertex, but they
  4871. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4872. then color it with the first available integer, which is $0$. We mark
  4873. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4874. they interfere with $\ttm{tmp\_0}$.
  4875. \[
  4876. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4877. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4878. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4879. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4880. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4881. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4882. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4883. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4884. \draw (t0) to (t1);
  4885. \draw (t0) to (z);
  4886. \draw (z) to (y);
  4887. \draw (z) to (w);
  4888. \draw (x) to (w);
  4889. \draw (y) to (w);
  4890. \draw (v) to (w);
  4891. \end{tikzpicture}
  4892. \]
  4893. We repeat the process. The most saturated vertices are \code{z} and
  4894. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4895. available number, which is $1$. We add $1$ to the saturation for the
  4896. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4897. \[
  4898. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4899. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4900. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4901. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4902. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4903. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4904. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4905. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4906. \draw (t0) to (t1);
  4907. \draw (t0) to (z);
  4908. \draw (z) to (y);
  4909. \draw (z) to (w);
  4910. \draw (x) to (w);
  4911. \draw (y) to (w);
  4912. \draw (v) to (w);
  4913. \end{tikzpicture}
  4914. \]
  4915. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4916. \code{y}. We color \code{w} with the first available color, which
  4917. is $0$.
  4918. \[
  4919. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4920. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4921. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4922. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4923. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4924. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4925. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4926. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4927. \draw (t0) to (t1);
  4928. \draw (t0) to (z);
  4929. \draw (z) to (y);
  4930. \draw (z) to (w);
  4931. \draw (x) to (w);
  4932. \draw (y) to (w);
  4933. \draw (v) to (w);
  4934. \end{tikzpicture}
  4935. \]
  4936. Now \code{y} is the most saturated, so we color it with $2$.
  4937. \[
  4938. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4939. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4940. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4941. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4942. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4943. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4944. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4945. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4946. \draw (t0) to (t1);
  4947. \draw (t0) to (z);
  4948. \draw (z) to (y);
  4949. \draw (z) to (w);
  4950. \draw (x) to (w);
  4951. \draw (y) to (w);
  4952. \draw (v) to (w);
  4953. \end{tikzpicture}
  4954. \]
  4955. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4956. We choose to color \code{v} with $1$.
  4957. \[
  4958. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4959. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4960. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4961. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4962. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4963. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4964. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4965. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4966. \draw (t0) to (t1);
  4967. \draw (t0) to (z);
  4968. \draw (z) to (y);
  4969. \draw (z) to (w);
  4970. \draw (x) to (w);
  4971. \draw (y) to (w);
  4972. \draw (v) to (w);
  4973. \end{tikzpicture}
  4974. \]
  4975. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4976. \[
  4977. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4978. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4979. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4980. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4981. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4982. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4983. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4984. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4985. \draw (t0) to (t1);
  4986. \draw (t0) to (z);
  4987. \draw (z) to (y);
  4988. \draw (z) to (w);
  4989. \draw (x) to (w);
  4990. \draw (y) to (w);
  4991. \draw (v) to (w);
  4992. \end{tikzpicture}
  4993. \]
  4994. So we obtain the following coloring:
  4995. \[
  4996. \{ \ttm{tmp\_0} \mapsto 0,
  4997. \ttm{tmp\_1} \mapsto 1,
  4998. \ttm{z} \mapsto 1,
  4999. \ttm{x} \mapsto 1,
  5000. \ttm{y} \mapsto 2,
  5001. \ttm{w} \mapsto 0,
  5002. \ttm{v} \mapsto 1 \}
  5003. \]
  5004. \fi}
  5005. We recommend creating an auxiliary function named \code{color\_graph}
  5006. that takes an interference graph and a list of all the variables in
  5007. the program. This function should return a mapping of variables to
  5008. their colors (represented as natural numbers). By creating this helper
  5009. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  5010. when we add support for functions.
  5011. To prioritize the processing of highly saturated nodes inside the
  5012. \code{color\_graph} function, we recommend using the priority queue
  5013. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  5014. addition, you will need to maintain a mapping from variables to their
  5015. ``handles'' in the priority queue so that you can notify the priority
  5016. queue when their saturation changes.}
  5017. {\if\edition\racketEd
  5018. \begin{figure}[tp]
  5019. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  5020. \small
  5021. \begin{tcolorbox}[title=Priority Queue]
  5022. A \emph{priority queue} is a collection of items in which the
  5023. removal of items is governed by priority. In a ``min'' queue,
  5024. lower priority items are removed first. An implementation is in
  5025. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  5026. queue} \index{subject}{minimum priority queue}
  5027. \begin{description}
  5028. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5029. priority queue that uses the $\itm{cmp}$ predicate to determine
  5030. whether its first argument has lower or equal priority to its
  5031. second argument.
  5032. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5033. items in the queue.
  5034. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5035. the item into the queue and returns a handle for the item in the
  5036. queue.
  5037. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5038. the lowest priority.
  5039. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5040. notifies the queue that the priority has decreased for the item
  5041. associated with the given handle.
  5042. \end{description}
  5043. \end{tcolorbox}
  5044. %\end{wrapfigure}
  5045. \caption{The priority queue data structure.}
  5046. \label{fig:priority-queue}
  5047. \end{figure}
  5048. \fi}
  5049. With the coloring complete, we finalize the assignment of variables to
  5050. registers and stack locations. We map the first $k$ colors to the $k$
  5051. registers and the rest of the colors to stack locations. Suppose for
  5052. the moment that we have just one register to use for register
  5053. allocation, \key{rcx}. Then we have the following map from colors to
  5054. locations.
  5055. \[
  5056. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5057. \]
  5058. Composing this mapping with the coloring, we arrive at the following
  5059. assignment of variables to locations.
  5060. {\if\edition\racketEd
  5061. \begin{gather*}
  5062. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5063. \ttm{w} \mapsto \key{\%rcx}, \,
  5064. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5065. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5066. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5067. \ttm{t} \mapsto \key{\%rcx} \}
  5068. \end{gather*}
  5069. \fi}
  5070. {\if\edition\pythonEd
  5071. \begin{gather*}
  5072. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5073. \ttm{w} \mapsto \key{\%rcx}, \,
  5074. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5075. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5076. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5077. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5078. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5079. \end{gather*}
  5080. \fi}
  5081. Adapt the code from the \code{assign\_homes} pass
  5082. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5083. assigned location. Applying the above assignment to our running
  5084. example, on the left, yields the program on the right.
  5085. % why frame size of 32? -JGS
  5086. \begin{center}
  5087. {\if\edition\racketEd
  5088. \begin{minipage}{0.3\textwidth}
  5089. \begin{lstlisting}
  5090. movq $1, v
  5091. movq $42, w
  5092. movq v, x
  5093. addq $7, x
  5094. movq x, y
  5095. movq x, z
  5096. addq w, z
  5097. movq y, t
  5098. negq t
  5099. movq z, %rax
  5100. addq t, %rax
  5101. jmp conclusion
  5102. \end{lstlisting}
  5103. \end{minipage}
  5104. $\Rightarrow\qquad$
  5105. \begin{minipage}{0.45\textwidth}
  5106. \begin{lstlisting}
  5107. movq $1, -8(%rbp)
  5108. movq $42, %rcx
  5109. movq -8(%rbp), -8(%rbp)
  5110. addq $7, -8(%rbp)
  5111. movq -8(%rbp), -16(%rbp)
  5112. movq -8(%rbp), -8(%rbp)
  5113. addq %rcx, -8(%rbp)
  5114. movq -16(%rbp), %rcx
  5115. negq %rcx
  5116. movq -8(%rbp), %rax
  5117. addq %rcx, %rax
  5118. jmp conclusion
  5119. \end{lstlisting}
  5120. \end{minipage}
  5121. \fi}
  5122. {\if\edition\pythonEd
  5123. \begin{minipage}{0.3\textwidth}
  5124. \begin{lstlisting}
  5125. movq $1, v
  5126. movq $42, w
  5127. movq v, x
  5128. addq $7, x
  5129. movq x, y
  5130. movq x, z
  5131. addq w, z
  5132. movq y, tmp_0
  5133. negq tmp_0
  5134. movq z, tmp_1
  5135. addq tmp_0, tmp_1
  5136. movq tmp_1, %rdi
  5137. callq print_int
  5138. \end{lstlisting}
  5139. \end{minipage}
  5140. $\Rightarrow\qquad$
  5141. \begin{minipage}{0.45\textwidth}
  5142. \begin{lstlisting}
  5143. movq $1, -8(%rbp)
  5144. movq $42, %rcx
  5145. movq -8(%rbp), -8(%rbp)
  5146. addq $7, -8(%rbp)
  5147. movq -8(%rbp), -16(%rbp)
  5148. movq -8(%rbp), -8(%rbp)
  5149. addq %rcx, -8(%rbp)
  5150. movq -16(%rbp), %rcx
  5151. negq %rcx
  5152. movq -8(%rbp), -8(%rbp)
  5153. addq %rcx, -8(%rbp)
  5154. movq -8(%rbp), %rdi
  5155. callq print_int
  5156. \end{lstlisting}
  5157. \end{minipage}
  5158. \fi}
  5159. \end{center}
  5160. \begin{exercise}\normalfont\normalsize
  5161. Implement the \code{allocate\_registers} pass.
  5162. Create five programs that exercise all aspects of the register
  5163. allocation algorithm, including spilling variables to the stack.
  5164. %
  5165. {\if\edition\racketEd
  5166. Replace \code{assign\_homes} in the list of \code{passes} in the
  5167. \code{run-tests.rkt} script with the three new passes:
  5168. \code{uncover\_live}, \code{build\_interference}, and
  5169. \code{allocate\_registers}.
  5170. Temporarily remove the call to \code{compiler-tests}.
  5171. Run the script to test the register allocator.
  5172. \fi}
  5173. %
  5174. {\if\edition\pythonEd
  5175. Run the \code{run-tests.py} script to to check whether the
  5176. output programs produce the same result as the input programs.
  5177. \fi}
  5178. \end{exercise}
  5179. \section{Patch Instructions}
  5180. \label{sec:patch-instructions}
  5181. The remaining step in the compilation to x86 is to ensure that the
  5182. instructions have at most one argument that is a memory access.
  5183. %
  5184. In the running example, the instruction \code{movq -8(\%rbp),
  5185. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5186. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5187. then move \code{rax} into \code{-16(\%rbp)}.
  5188. %
  5189. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5190. problematic, but they can simply be deleted. In general, we recommend
  5191. deleting all the trivial moves whose source and destination are the
  5192. same location.
  5193. %
  5194. The following is the output of \code{patch\_instructions} on the
  5195. running example.
  5196. \begin{center}
  5197. {\if\edition\racketEd
  5198. \begin{minipage}{0.4\textwidth}
  5199. \begin{lstlisting}
  5200. movq $1, -8(%rbp)
  5201. movq $42, %rcx
  5202. movq -8(%rbp), -8(%rbp)
  5203. addq $7, -8(%rbp)
  5204. movq -8(%rbp), -16(%rbp)
  5205. movq -8(%rbp), -8(%rbp)
  5206. addq %rcx, -8(%rbp)
  5207. movq -16(%rbp), %rcx
  5208. negq %rcx
  5209. movq -8(%rbp), %rax
  5210. addq %rcx, %rax
  5211. jmp conclusion
  5212. \end{lstlisting}
  5213. \end{minipage}
  5214. $\Rightarrow\qquad$
  5215. \begin{minipage}{0.45\textwidth}
  5216. \begin{lstlisting}
  5217. movq $1, -8(%rbp)
  5218. movq $42, %rcx
  5219. addq $7, -8(%rbp)
  5220. movq -8(%rbp), %rax
  5221. movq %rax, -16(%rbp)
  5222. addq %rcx, -8(%rbp)
  5223. movq -16(%rbp), %rcx
  5224. negq %rcx
  5225. movq -8(%rbp), %rax
  5226. addq %rcx, %rax
  5227. jmp conclusion
  5228. \end{lstlisting}
  5229. \end{minipage}
  5230. \fi}
  5231. {\if\edition\pythonEd
  5232. \begin{minipage}{0.4\textwidth}
  5233. \begin{lstlisting}
  5234. movq $1, -8(%rbp)
  5235. movq $42, %rcx
  5236. movq -8(%rbp), -8(%rbp)
  5237. addq $7, -8(%rbp)
  5238. movq -8(%rbp), -16(%rbp)
  5239. movq -8(%rbp), -8(%rbp)
  5240. addq %rcx, -8(%rbp)
  5241. movq -16(%rbp), %rcx
  5242. negq %rcx
  5243. movq -8(%rbp), -8(%rbp)
  5244. addq %rcx, -8(%rbp)
  5245. movq -8(%rbp), %rdi
  5246. callq print_int
  5247. \end{lstlisting}
  5248. \end{minipage}
  5249. $\Rightarrow\qquad$
  5250. \begin{minipage}{0.45\textwidth}
  5251. \begin{lstlisting}
  5252. movq $1, -8(%rbp)
  5253. movq $42, %rcx
  5254. addq $7, -8(%rbp)
  5255. movq -8(%rbp), %rax
  5256. movq %rax, -16(%rbp)
  5257. addq %rcx, -8(%rbp)
  5258. movq -16(%rbp), %rcx
  5259. negq %rcx
  5260. addq %rcx, -8(%rbp)
  5261. movq -8(%rbp), %rdi
  5262. callq print_int
  5263. \end{lstlisting}
  5264. \end{minipage}
  5265. \fi}
  5266. \end{center}
  5267. \begin{exercise}\normalfont\normalsize
  5268. %
  5269. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5270. %
  5271. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5272. %in the \code{run-tests.rkt} script.
  5273. %
  5274. Run the script to test the \code{patch\_instructions} pass.
  5275. \end{exercise}
  5276. \section{Prelude and Conclusion}
  5277. \label{sec:print-x86-reg-alloc}
  5278. \index{subject}{calling conventions}
  5279. \index{subject}{prelude}\index{subject}{conclusion}
  5280. Recall that this pass generates the prelude and conclusion
  5281. instructions to satisfy the x86 calling conventions
  5282. (Section~\ref{sec:calling-conventions}). With the addition of the
  5283. register allocator, the callee-saved registers used by the register
  5284. allocator must be saved in the prelude and restored in the conclusion.
  5285. In the \code{allocate\_registers} pass,
  5286. %
  5287. \racket{add an entry to the \itm{info}
  5288. of \code{X86Program} named \code{used\_callee}}
  5289. %
  5290. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5291. %
  5292. that stores the set of callee-saved registers that were assigned to
  5293. variables. The \code{prelude\_and\_conclusion} pass can then access
  5294. this information to decide which callee-saved registers need to be
  5295. saved and restored.
  5296. %
  5297. When calculating the amount to adjust the \code{rsp} in the prelude,
  5298. make sure to take into account the space used for saving the
  5299. callee-saved registers. Also, don't forget that the frame needs to be
  5300. a multiple of 16 bytes! We recommend using the following equation for
  5301. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5302. of spilled variables and $C$ be the number of callee-saved registers
  5303. that were allocated to variables. The $\itm{align}$ function rounds a
  5304. number up to the nearest 16 bytes.
  5305. \[
  5306. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5307. \]
  5308. The reason we subtract $8\itm{C}$ in the above equation is because the
  5309. prelude uses \code{pushq} to save each of the callee-saved registers,
  5310. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5311. \racket{An overview of all of the passes involved in register
  5312. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5313. {\if\edition\racketEd
  5314. \begin{figure}[tbp]
  5315. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5316. \node (Lvar) at (0,2) {\large \LangVar{}};
  5317. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5318. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5319. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5320. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5321. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5322. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5323. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5324. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5325. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5326. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5327. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5328. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5329. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5330. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5331. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5332. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5333. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5334. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5335. \end{tikzpicture}
  5336. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5337. \label{fig:reg-alloc-passes}
  5338. \end{figure}
  5339. \fi}
  5340. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5341. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5342. use of registers and the stack, we limit the register allocator for
  5343. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5344. the prelude\index{subject}{prelude} of the \code{main} function, we
  5345. push \code{rbx} onto the stack because it is a callee-saved register
  5346. and it was assigned to a variable by the register allocator. We
  5347. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5348. reserve space for the one spilled variable. After that subtraction,
  5349. the \code{rsp} is aligned to 16 bytes.
  5350. Moving on to the program proper, we see how the registers were
  5351. allocated.
  5352. %
  5353. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5354. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5355. %
  5356. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5357. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5358. were assigned to \code{rbx}.}
  5359. %
  5360. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5361. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5362. callee-save register \code{rbx} onto the stack. The spilled variables
  5363. must be placed lower on the stack than the saved callee-save
  5364. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5365. \code{-16(\%rbp)}.
  5366. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5367. done in the prelude. We move the stack pointer up by \code{8} bytes
  5368. (the room for spilled variables), then we pop the old values of
  5369. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5370. \code{retq} to return control to the operating system.
  5371. \begin{figure}[tbp]
  5372. % var_test_28.rkt
  5373. % (use-minimal-set-of-registers! #t)
  5374. % and only rbx rcx
  5375. % tmp 0 rbx
  5376. % z 1 rcx
  5377. % y 0 rbx
  5378. % w 2 16(%rbp)
  5379. % v 0 rbx
  5380. % x 0 rbx
  5381. {\if\edition\racketEd
  5382. \begin{lstlisting}
  5383. start:
  5384. movq $1, %rbx
  5385. movq $42, -16(%rbp)
  5386. addq $7, %rbx
  5387. movq %rbx, %rcx
  5388. addq -16(%rbp), %rcx
  5389. negq %rbx
  5390. movq %rcx, %rax
  5391. addq %rbx, %rax
  5392. jmp conclusion
  5393. .globl main
  5394. main:
  5395. pushq %rbp
  5396. movq %rsp, %rbp
  5397. pushq %rbx
  5398. subq $8, %rsp
  5399. jmp start
  5400. conclusion:
  5401. addq $8, %rsp
  5402. popq %rbx
  5403. popq %rbp
  5404. retq
  5405. \end{lstlisting}
  5406. \fi}
  5407. {\if\edition\pythonEd
  5408. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5409. \begin{lstlisting}
  5410. .globl main
  5411. main:
  5412. pushq %rbp
  5413. movq %rsp, %rbp
  5414. pushq %rbx
  5415. subq $8, %rsp
  5416. movq $1, %rcx
  5417. movq $42, %rbx
  5418. addq $7, %rcx
  5419. movq %rcx, -16(%rbp)
  5420. addq %rbx, -16(%rbp)
  5421. negq %rcx
  5422. movq -16(%rbp), %rbx
  5423. addq %rcx, %rbx
  5424. movq %rbx, %rdi
  5425. callq print_int
  5426. addq $8, %rsp
  5427. popq %rbx
  5428. popq %rbp
  5429. retq
  5430. \end{lstlisting}
  5431. \fi}
  5432. \caption{The x86 output from the running example
  5433. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5434. and \code{rcx}.}
  5435. \label{fig:running-example-x86}
  5436. \end{figure}
  5437. \begin{exercise}\normalfont\normalsize
  5438. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5439. %
  5440. \racket{
  5441. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5442. list of passes and the call to \code{compiler-tests}.}
  5443. %
  5444. Run the script to test the complete compiler for \LangVar{} that
  5445. performs register allocation.
  5446. \end{exercise}
  5447. \section{Challenge: Move Biasing}
  5448. \label{sec:move-biasing}
  5449. \index{subject}{move biasing}
  5450. This section describes an enhancement to the register allocator,
  5451. called move biasing, for students who are looking for an extra
  5452. challenge.
  5453. {\if\edition\racketEd
  5454. To motivate the need for move biasing we return to the running example
  5455. but this time we use all of the general purpose registers. So we have
  5456. the following mapping of color numbers to registers.
  5457. \[
  5458. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5459. \]
  5460. Using the same assignment of variables to color numbers that was
  5461. produced by the register allocator described in the last section, we
  5462. get the following program.
  5463. \begin{center}
  5464. \begin{minipage}{0.3\textwidth}
  5465. \begin{lstlisting}
  5466. movq $1, v
  5467. movq $42, w
  5468. movq v, x
  5469. addq $7, x
  5470. movq x, y
  5471. movq x, z
  5472. addq w, z
  5473. movq y, t
  5474. negq t
  5475. movq z, %rax
  5476. addq t, %rax
  5477. jmp conclusion
  5478. \end{lstlisting}
  5479. \end{minipage}
  5480. $\Rightarrow\qquad$
  5481. \begin{minipage}{0.45\textwidth}
  5482. \begin{lstlisting}
  5483. movq $1, %rdx
  5484. movq $42, %rcx
  5485. movq %rdx, %rdx
  5486. addq $7, %rdx
  5487. movq %rdx, %rsi
  5488. movq %rdx, %rdx
  5489. addq %rcx, %rdx
  5490. movq %rsi, %rcx
  5491. negq %rcx
  5492. movq %rdx, %rax
  5493. addq %rcx, %rax
  5494. jmp conclusion
  5495. \end{lstlisting}
  5496. \end{minipage}
  5497. \end{center}
  5498. In the above output code there are two \key{movq} instructions that
  5499. can be removed because their source and target are the same. However,
  5500. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5501. register, we could instead remove three \key{movq} instructions. We
  5502. can accomplish this by taking into account which variables appear in
  5503. \key{movq} instructions with which other variables.
  5504. \fi}
  5505. {\if\edition\pythonEd
  5506. %
  5507. To motivate the need for move biasing we return to the running example
  5508. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5509. remove three trivial move instructions from the running
  5510. example. However, we could remove another trivial move if we were able
  5511. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5512. We say that two variables $p$ and $q$ are \emph{move
  5513. related}\index{subject}{move related} if they participate together in
  5514. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5515. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5516. when there are multiple variables with the same saturation, prefer
  5517. variables that can be assigned to a color that is the same as the
  5518. color of a move related variable. Furthermore, when the register
  5519. allocator chooses a color for a variable, it should prefer a color
  5520. that has already been used for a move-related variable (assuming that
  5521. they do not interfere). Of course, this preference should not override
  5522. the preference for registers over stack locations. So this preference
  5523. should be used as a tie breaker when choosing between registers or
  5524. when choosing between stack locations.
  5525. We recommend representing the move relationships in a graph, similar
  5526. to how we represented interference. The following is the \emph{move
  5527. graph} for our running example.
  5528. {\if\edition\racketEd
  5529. \[
  5530. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5531. \node (rax) at (0,0) {$\ttm{rax}$};
  5532. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5533. \node (t) at (0,2) {$\ttm{t}$};
  5534. \node (z) at (3,2) {$\ttm{z}$};
  5535. \node (x) at (6,2) {$\ttm{x}$};
  5536. \node (y) at (3,0) {$\ttm{y}$};
  5537. \node (w) at (6,0) {$\ttm{w}$};
  5538. \node (v) at (9,0) {$\ttm{v}$};
  5539. \draw (v) to (x);
  5540. \draw (x) to (y);
  5541. \draw (x) to (z);
  5542. \draw (y) to (t);
  5543. \end{tikzpicture}
  5544. \]
  5545. \fi}
  5546. %
  5547. {\if\edition\pythonEd
  5548. \[
  5549. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5550. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5551. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5552. \node (z) at (3,2) {$\ttm{z}$};
  5553. \node (x) at (6,2) {$\ttm{x}$};
  5554. \node (y) at (3,0) {$\ttm{y}$};
  5555. \node (w) at (6,0) {$\ttm{w}$};
  5556. \node (v) at (9,0) {$\ttm{v}$};
  5557. \draw (y) to (t0);
  5558. \draw (z) to (x);
  5559. \draw (z) to (t1);
  5560. \draw (x) to (y);
  5561. \draw (x) to (v);
  5562. \end{tikzpicture}
  5563. \]
  5564. \fi}
  5565. {\if\edition\racketEd
  5566. Now we replay the graph coloring, pausing to see the coloring of
  5567. \code{y}. Recall the following configuration. The most saturated vertices
  5568. were \code{w} and \code{y}.
  5569. \[
  5570. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5571. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5572. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5573. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5574. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5575. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5576. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5577. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5578. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5579. \draw (t1) to (rax);
  5580. \draw (t1) to (z);
  5581. \draw (z) to (y);
  5582. \draw (z) to (w);
  5583. \draw (x) to (w);
  5584. \draw (y) to (w);
  5585. \draw (v) to (w);
  5586. \draw (v) to (rsp);
  5587. \draw (w) to (rsp);
  5588. \draw (x) to (rsp);
  5589. \draw (y) to (rsp);
  5590. \path[-.,bend left=15] (z) edge node {} (rsp);
  5591. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5592. \draw (rax) to (rsp);
  5593. \end{tikzpicture}
  5594. \]
  5595. %
  5596. Last time we chose to color \code{w} with $0$. But this time we see
  5597. that \code{w} is not move related to any vertex, but \code{y} is move
  5598. related to \code{t}. So we choose to color \code{y} with $0$, the
  5599. same color as \code{t}.
  5600. \[
  5601. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5602. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5603. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5604. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5605. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5606. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5607. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5608. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5609. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5610. \draw (t1) to (rax);
  5611. \draw (t1) to (z);
  5612. \draw (z) to (y);
  5613. \draw (z) to (w);
  5614. \draw (x) to (w);
  5615. \draw (y) to (w);
  5616. \draw (v) to (w);
  5617. \draw (v) to (rsp);
  5618. \draw (w) to (rsp);
  5619. \draw (x) to (rsp);
  5620. \draw (y) to (rsp);
  5621. \path[-.,bend left=15] (z) edge node {} (rsp);
  5622. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5623. \draw (rax) to (rsp);
  5624. \end{tikzpicture}
  5625. \]
  5626. Now \code{w} is the most saturated, so we color it $2$.
  5627. \[
  5628. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5629. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5630. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5631. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5632. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5633. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5634. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5635. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5636. \node (v) at (9,0) {$\ttm{v}:-,\{2,-2\}$};
  5637. \draw (t1) to (rax);
  5638. \draw (t1) to (z);
  5639. \draw (z) to (y);
  5640. \draw (z) to (w);
  5641. \draw (x) to (w);
  5642. \draw (y) to (w);
  5643. \draw (v) to (w);
  5644. \draw (v) to (rsp);
  5645. \draw (w) to (rsp);
  5646. \draw (x) to (rsp);
  5647. \draw (y) to (rsp);
  5648. \path[-.,bend left=15] (z) edge node {} (rsp);
  5649. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5650. \draw (rax) to (rsp);
  5651. \end{tikzpicture}
  5652. \]
  5653. At this point, vertices \code{x} and \code{v} are most saturated, but
  5654. \code{x} is move related to \code{y} and \code{z}, so we color
  5655. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5656. \[
  5657. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5658. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5659. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5660. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5661. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5662. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5663. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5664. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5665. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5666. \draw (t1) to (rax);
  5667. \draw (t) to (z);
  5668. \draw (z) to (y);
  5669. \draw (z) to (w);
  5670. \draw (x) to (w);
  5671. \draw (y) to (w);
  5672. \draw (v) to (w);
  5673. \draw (v) to (rsp);
  5674. \draw (w) to (rsp);
  5675. \draw (x) to (rsp);
  5676. \draw (y) to (rsp);
  5677. \path[-.,bend left=15] (z) edge node {} (rsp);
  5678. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5679. \draw (rax) to (rsp);
  5680. \end{tikzpicture}
  5681. \]
  5682. \fi}
  5683. %
  5684. {\if\edition\pythonEd
  5685. Now we replay the graph coloring, pausing before the coloring of
  5686. \code{w}. Recall the following configuration. The most saturated vertices
  5687. were \code{tmp\_1}, \code{w}, and \code{y}.
  5688. \[
  5689. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5690. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5691. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5692. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5693. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5694. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5695. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5696. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5697. \draw (t0) to (t1);
  5698. \draw (t0) to (z);
  5699. \draw (z) to (y);
  5700. \draw (z) to (w);
  5701. \draw (x) to (w);
  5702. \draw (y) to (w);
  5703. \draw (v) to (w);
  5704. \end{tikzpicture}
  5705. \]
  5706. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5707. or \code{y}, but note that \code{w} is not move related to any
  5708. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5709. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5710. \code{y} and color it $0$, we can delete another move instruction.
  5711. \[
  5712. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5713. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5714. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5715. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5716. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5717. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5718. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5719. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5720. \draw (t0) to (t1);
  5721. \draw (t0) to (z);
  5722. \draw (z) to (y);
  5723. \draw (z) to (w);
  5724. \draw (x) to (w);
  5725. \draw (y) to (w);
  5726. \draw (v) to (w);
  5727. \end{tikzpicture}
  5728. \]
  5729. Now \code{w} is the most saturated, so we color it $2$.
  5730. \[
  5731. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5732. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5733. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5734. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5735. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5736. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5737. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5738. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5739. \draw (t0) to (t1);
  5740. \draw (t0) to (z);
  5741. \draw (z) to (y);
  5742. \draw (z) to (w);
  5743. \draw (x) to (w);
  5744. \draw (y) to (w);
  5745. \draw (v) to (w);
  5746. \end{tikzpicture}
  5747. \]
  5748. To finish the coloring, \code{x} and \code{v} get $0$ and
  5749. \code{tmp\_1} gets $1$.
  5750. \[
  5751. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5752. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5753. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5754. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5755. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5756. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5757. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5758. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5759. \draw (t0) to (t1);
  5760. \draw (t0) to (z);
  5761. \draw (z) to (y);
  5762. \draw (z) to (w);
  5763. \draw (x) to (w);
  5764. \draw (y) to (w);
  5765. \draw (v) to (w);
  5766. \end{tikzpicture}
  5767. \]
  5768. \fi}
  5769. So we have the following assignment of variables to registers.
  5770. {\if\edition\racketEd
  5771. \begin{gather*}
  5772. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5773. \ttm{w} \mapsto \key{\%rsi}, \,
  5774. \ttm{x} \mapsto \key{\%rcx}, \,
  5775. \ttm{y} \mapsto \key{\%rcx}, \,
  5776. \ttm{z} \mapsto \key{\%rdx}, \,
  5777. \ttm{t} \mapsto \key{\%rcx} \}
  5778. \end{gather*}
  5779. \fi}
  5780. {\if\edition\pythonEd
  5781. \begin{gather*}
  5782. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5783. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5784. \ttm{x} \mapsto \key{\%rcx}, \,
  5785. \ttm{y} \mapsto \key{\%rcx}, \\
  5786. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5787. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5788. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5789. \end{gather*}
  5790. \fi}
  5791. We apply this register assignment to the running example, on the left,
  5792. to obtain the code in the middle. The \code{patch\_instructions} then
  5793. deletes the trivial moves to obtain the code on the right.
  5794. {\if\edition\racketEd
  5795. \begin{minipage}{0.25\textwidth}
  5796. \begin{lstlisting}
  5797. movq $1, v
  5798. movq $42, w
  5799. movq v, x
  5800. addq $7, x
  5801. movq x, y
  5802. movq x, z
  5803. addq w, z
  5804. movq y, t
  5805. negq t
  5806. movq z, %rax
  5807. addq t, %rax
  5808. jmp conclusion
  5809. \end{lstlisting}
  5810. \end{minipage}
  5811. $\Rightarrow\qquad$
  5812. \begin{minipage}{0.25\textwidth}
  5813. \begin{lstlisting}
  5814. movq $1, %rcx
  5815. movq $42, %rsi
  5816. movq %rcx, %rcx
  5817. addq $7, %rcx
  5818. movq %rcx, %rcx
  5819. movq %rcx, %rdx
  5820. addq %rsi, %rdx
  5821. movq %rcx, %rcx
  5822. negq %rcx
  5823. movq %rdx, %rax
  5824. addq %rcx, %rax
  5825. jmp conclusion
  5826. \end{lstlisting}
  5827. \end{minipage}
  5828. $\Rightarrow\qquad$
  5829. \begin{minipage}{0.25\textwidth}
  5830. \begin{lstlisting}
  5831. movq $1, %rcx
  5832. movq $42, %rsi
  5833. addq $7, %rcx
  5834. movq %rcx, %rdx
  5835. addq %rsi, %rdx
  5836. negq %rcx
  5837. movq %rdx, %rax
  5838. addq %rcx, %rax
  5839. jmp conclusion
  5840. \end{lstlisting}
  5841. \end{minipage}
  5842. \fi}
  5843. {\if\edition\pythonEd
  5844. \begin{minipage}{0.20\textwidth}
  5845. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5846. movq $1, v
  5847. movq $42, w
  5848. movq v, x
  5849. addq $7, x
  5850. movq x, y
  5851. movq x, z
  5852. addq w, z
  5853. movq y, tmp_0
  5854. negq tmp_0
  5855. movq z, tmp_1
  5856. addq tmp_0, tmp_1
  5857. movq tmp_1, %rdi
  5858. callq _print_int
  5859. \end{lstlisting}
  5860. \end{minipage}
  5861. ${\Rightarrow\qquad}$
  5862. \begin{minipage}{0.30\textwidth}
  5863. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5864. movq $1, %rcx
  5865. movq $42, -16(%rbp)
  5866. movq %rcx, %rcx
  5867. addq $7, %rcx
  5868. movq %rcx, %rcx
  5869. movq %rcx, -8(%rbp)
  5870. addq -16(%rbp), -8(%rbp)
  5871. movq %rcx, %rcx
  5872. negq %rcx
  5873. movq -8(%rbp), -8(%rbp)
  5874. addq %rcx, -8(%rbp)
  5875. movq -8(%rbp), %rdi
  5876. callq _print_int
  5877. \end{lstlisting}
  5878. \end{minipage}
  5879. ${\Rightarrow\qquad}$
  5880. \begin{minipage}{0.20\textwidth}
  5881. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5882. movq $1, %rcx
  5883. movq $42, -16(%rbp)
  5884. addq $7, %rcx
  5885. movq %rcx, -8(%rbp)
  5886. movq -16(%rbp), %rax
  5887. addq %rax, -8(%rbp)
  5888. negq %rcx
  5889. addq %rcx, -8(%rbp)
  5890. movq -8(%rbp), %rdi
  5891. callq print_int
  5892. \end{lstlisting}
  5893. \end{minipage}
  5894. \fi}
  5895. \begin{exercise}\normalfont\normalsize
  5896. Change your implementation of \code{allocate\_registers} to take move
  5897. biasing into account. Create two new tests that include at least one
  5898. opportunity for move biasing and visually inspect the output x86
  5899. programs to make sure that your move biasing is working properly. Make
  5900. sure that your compiler still passes all of the tests.
  5901. \end{exercise}
  5902. %To do: another neat challenge would be to do
  5903. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5904. %% \subsection{Output of the Running Example}
  5905. %% \label{sec:reg-alloc-output}
  5906. % challenge: prioritize variables based on execution frequencies
  5907. % and the number of uses of a variable
  5908. % challenge: enhance the coloring algorithm using Chaitin's
  5909. % approach of prioritizing high-degree variables
  5910. % by removing low-degree variables (coloring them later)
  5911. % from the interference graph
  5912. \section{Further Reading}
  5913. \label{sec:register-allocation-further-reading}
  5914. Early register allocation algorithms were developed for Fortran
  5915. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5916. of graph coloring began in the late 1970s and early 1980s with the
  5917. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5918. algorithm is based on the following observation of
  5919. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5920. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5921. $v$ removed is also $k$ colorable. To see why, suppose that the
  5922. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5923. different colors, but since there are less than $k$ neighbors, there
  5924. will be one or more colors left over to use for coloring $v$ in $G$.
  5925. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5926. less than $k$ from the graph and recursively colors the rest of the
  5927. graph. Upon returning from the recursion, it colors $v$ with one of
  5928. the available colors and returns. \citet{Chaitin:1982vn} augments
  5929. this algorithm to handle spilling as follows. If there are no vertices
  5930. of degree lower than $k$ then pick a vertex at random, spill it,
  5931. remove it from the graph, and proceed recursively to color the rest of
  5932. the graph.
  5933. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5934. move-related and that don't interfere with each other, a process
  5935. called \emph{coalescing}. While coalescing decreases the number of
  5936. moves, it can make the graph more difficult to
  5937. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5938. which two variables are merged only if they have fewer than $k$
  5939. neighbors of high degree. \citet{George:1996aa} observe that
  5940. conservative coalescing is sometimes too conservative and make it more
  5941. aggressive by iterating the coalescing with the removal of low-degree
  5942. vertices.
  5943. %
  5944. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5945. also propose \emph{biased coloring} in which a variable is assigned to
  5946. the same color as another move-related variable if possible, as
  5947. discussed in Section~\ref{sec:move-biasing}.
  5948. %
  5949. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5950. performs coalescing, graph coloring, and spill code insertion until
  5951. all variables have been assigned a location.
  5952. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5953. spills variables that don't have to be: a high-degree variable can be
  5954. colorable if many of its neighbors are assigned the same color.
  5955. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5956. high-degree vertex is not immediately spilled. Instead the decision is
  5957. deferred until after the recursive call, at which point it is apparent
  5958. whether there is actually an available color or not. We observe that
  5959. this algorithm is equivalent to the smallest-last ordering
  5960. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5961. be registers and the rest to be stack locations.
  5962. %% biased coloring
  5963. Earlier editions of the compiler course at Indiana University
  5964. \citep{Dybvig:2010aa} were based on the algorithm of
  5965. \citet{Briggs:1994kx}.
  5966. The smallest-last ordering algorithm is one of many \emph{greedy}
  5967. coloring algorithms. A greedy coloring algorithm visits all the
  5968. vertices in a particular order and assigns each one the first
  5969. available color. An \emph{offline} greedy algorithm chooses the
  5970. ordering up-front, prior to assigning colors. The algorithm of
  5971. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5972. ordering does not depend on the colors assigned. Other orderings are
  5973. possible. For example, \citet{Chow:1984ys} order variables according
  5974. to an estimate of runtime cost.
  5975. An \emph{online} greedy coloring algorithm uses information about the
  5976. current assignment of colors to influence the order in which the
  5977. remaining vertices are colored. The saturation-based algorithm
  5978. described in this chapter is one such algorithm. We choose to use
  5979. saturation-based coloring because it is fun to introduce graph
  5980. coloring via Sudoku!
  5981. A register allocator may choose to map each variable to just one
  5982. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5983. variable to one or more locations. The later can be achieved by
  5984. \emph{live range splitting}, where a variable is replaced by several
  5985. variables that each handle part of its live
  5986. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5987. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5988. %% replacement algorithm, bottom-up local
  5989. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5990. %% Cooper: top-down (priority bassed), bottom-up
  5991. %% top-down
  5992. %% order variables by priority (estimated cost)
  5993. %% caveat: split variables into two groups:
  5994. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5995. %% color the constrained ones first
  5996. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5997. %% cite J. Cocke for an algorithm that colors variables
  5998. %% in a high-degree first ordering
  5999. %Register Allocation via Usage Counts, Freiburghouse CACM
  6000. \citet{Palsberg:2007si} observe that many of the interference graphs
  6001. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  6002. that is, every cycle with four or more edges has an edge which is not
  6003. part of the cycle but which connects two vertices on the cycle. Such
  6004. graphs can be optimally colored by the greedy algorithm with a vertex
  6005. ordering determined by maximum cardinality search.
  6006. In situations where compile time is of utmost importance, such as in
  6007. just-in-time compilers, graph coloring algorithms can be too expensive
  6008. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  6009. appropriate.
  6010. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  6011. \chapter{Booleans and Conditionals}
  6012. \label{ch:Lif}
  6013. \index{subject}{Boolean}
  6014. \index{subject}{control flow}
  6015. \index{subject}{conditional expression}
  6016. The \LangVar{} language only has a single kind of value, the
  6017. integers. In this chapter we add a second kind of value, the Booleans,
  6018. to create the \LangIf{} language. The Boolean values \emph{true} and
  6019. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  6020. \racket{Racket}\python{Python}. The \LangIf{} language includes
  6021. several operations that involve Booleans (\key{and}, \key{not},
  6022. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  6023. expression \python{and statement}. With the addition of \key{if},
  6024. programs can have non-trivial control flow which
  6025. %
  6026. \racket{impacts \code{explicate\_control} and liveness analysis}
  6027. %
  6028. \python{impacts liveness analysis and motivates a new pass named
  6029. \code{explicate\_control}}.
  6030. %
  6031. Also, because we now have two kinds of values, we need to handle
  6032. programs that apply an operation to the wrong kind of value, such as
  6033. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6034. There are two language design options for such situations. One option
  6035. is to signal an error and the other is to provide a wider
  6036. interpretation of the operation. \racket{The Racket
  6037. language}\python{Python} uses a mixture of these two options,
  6038. depending on the operation and the kind of value. For example, the
  6039. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6040. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6041. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6042. %
  6043. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6044. in Racket because \code{car} expects a pair.}
  6045. %
  6046. \python{On the other hand, \code{1[0]} results in a run-time error
  6047. in Python because an ``\code{int} object is not subscriptable''.}
  6048. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6049. design choices as \racket{Racket}\python{Python}, except much of the
  6050. error detection happens at compile time instead of run
  6051. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6052. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6053. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6054. Racket}\python{MyPy} reports a compile-time error
  6055. %
  6056. \racket{because Racket expects the type of the argument to be of the form
  6057. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6058. %
  6059. \python{stating that a ``value of type \code{int} is not indexable''.}
  6060. The \LangIf{} language performs type checking during compilation like
  6061. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study
  6062. the alternative choice, that is, a dynamically typed language like
  6063. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6064. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6065. restrictive, for example, rejecting \racket{\code{(not
  6066. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6067. fairly simple because the focus of this book is on compilation, not
  6068. type systems, about which there are already several excellent
  6069. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6070. This chapter is organized as follows. We begin by defining the syntax
  6071. and interpreter for the \LangIf{} language
  6072. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6073. checking and define a type checker for \LangIf{}
  6074. (Section~\ref{sec:type-check-Lif}).
  6075. %
  6076. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6077. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6078. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6079. %
  6080. The remaining sections of this chapter discuss how Booleans and
  6081. conditional control flow require changes to the existing compiler
  6082. passes and the addition of new ones. We introduce the \code{shrink}
  6083. pass to translates some operators into others, thereby reducing the
  6084. number of operators that need to be handled in later passes.
  6085. %
  6086. The main event of this chapter is the \code{explicate\_control} pass
  6087. that is responsible for translating \code{if}'s into conditional
  6088. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6089. %
  6090. Regarding register allocation, there is the interesting question of
  6091. how to handle conditional \code{goto}'s during liveness analysis.
  6092. \section{The \LangIf{} Language}
  6093. \label{sec:lang-if}
  6094. The concrete and abstract syntax of the \LangIf{} language are defined in
  6095. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6096. respectively. The \LangIf{} language includes all of
  6097. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6098. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6099. \code{if} statement}. We expand the set of operators to include
  6100. \begin{enumerate}
  6101. \item the logical operators \key{and}, \key{or}, and \key{not},
  6102. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6103. for comparing integers or Booleans for equality, and
  6104. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6105. comparing integers.
  6106. \end{enumerate}
  6107. \racket{We reorganize the abstract syntax for the primitive
  6108. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6109. rule for all of them. This means that the grammar no longer checks
  6110. whether the arity of an operators matches the number of
  6111. arguments. That responsibility is moved to the type checker for
  6112. \LangIf{} (Section~\ref{sec:type-check-Lif}).}
  6113. \newcommand{\LifGrammarRacket}{
  6114. \begin{array}{lcl}
  6115. \Type &::=& \key{Boolean} \\
  6116. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6117. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6118. \Exp &::=& \itm{bool}
  6119. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6120. \MID (\key{not}\;\Exp) \\
  6121. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6122. \end{array}
  6123. }
  6124. \newcommand{\LifASTRacket}{
  6125. \begin{array}{lcl}
  6126. \Type &::=& \key{Boolean} \\
  6127. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6128. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6129. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6130. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6131. \end{array}
  6132. }
  6133. \newcommand{\LintOpAST}{
  6134. \begin{array}{rcl}
  6135. \Type &::=& \key{Integer} \\
  6136. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6137. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6138. \end{array}
  6139. }
  6140. \newcommand{\LifGrammarPython}{
  6141. \begin{array}{rcl}
  6142. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6143. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6144. \MID \key{not}~\Exp \\
  6145. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6146. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6147. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6148. \end{array}
  6149. }
  6150. \newcommand{\LifASTPython}{
  6151. \begin{array}{lcl}
  6152. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6153. \itm{unaryop} &::=& \code{Not()} \\
  6154. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6155. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6156. \Exp &::=& \BOOL{\itm{bool}}
  6157. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6158. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6159. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6160. \end{array}
  6161. }
  6162. \begin{figure}[tp]
  6163. \centering
  6164. \fbox{
  6165. \begin{minipage}{0.96\textwidth}
  6166. {\if\edition\racketEd
  6167. \[
  6168. \begin{array}{l}
  6169. \gray{\LintGrammarRacket{}} \\ \hline
  6170. \gray{\LvarGrammarRacket{}} \\ \hline
  6171. \LifGrammarRacket{} \\
  6172. \begin{array}{lcl}
  6173. \LangIfM{} &::=& \Exp
  6174. \end{array}
  6175. \end{array}
  6176. \]
  6177. \fi}
  6178. {\if\edition\pythonEd
  6179. \[
  6180. \begin{array}{l}
  6181. \gray{\LintGrammarPython} \\ \hline
  6182. \gray{\LvarGrammarPython} \\ \hline
  6183. \LifGrammarPython \\
  6184. \begin{array}{rcl}
  6185. \LangIfM{} &::=& \Stmt^{*}
  6186. \end{array}
  6187. \end{array}
  6188. \]
  6189. \fi}
  6190. \end{minipage}
  6191. }
  6192. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6193. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6194. \label{fig:Lif-concrete-syntax}
  6195. \end{figure}
  6196. \begin{figure}[tp]
  6197. \centering
  6198. \fbox{
  6199. \begin{minipage}{0.96\textwidth}
  6200. {\if\edition\racketEd
  6201. \[
  6202. \begin{array}{l}
  6203. \gray{\LintOpAST} \\ \hline
  6204. \gray{\LvarASTRacket{}} \\ \hline
  6205. \LifASTRacket{} \\
  6206. \begin{array}{lcl}
  6207. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6208. \end{array}
  6209. \end{array}
  6210. \]
  6211. \fi}
  6212. {\if\edition\pythonEd
  6213. \[
  6214. \begin{array}{l}
  6215. \gray{\LintASTPython} \\ \hline
  6216. \gray{\LvarASTPython} \\ \hline
  6217. \LifASTPython \\
  6218. \begin{array}{lcl}
  6219. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6220. \end{array}
  6221. \end{array}
  6222. \]
  6223. \fi}
  6224. \end{minipage}
  6225. }
  6226. \caption{The abstract syntax of \LangIf{}.}
  6227. \label{fig:Lif-syntax}
  6228. \end{figure}
  6229. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6230. which inherits from the interpreter for \LangVar{}
  6231. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6232. evaluate to the corresponding Boolean values. The conditional
  6233. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6234. and then either evaluates $e_2$ or $e_3$ depending on whether
  6235. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6236. \code{and}, \code{or}, and \code{not} behave according to
  6237. propositional logic. In addition, the \code{and} and \code{or}
  6238. operations perform \emph{short-circuit evaluation}.
  6239. %
  6240. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6241. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6242. %
  6243. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6244. evaluated if $e_1$ evaluates to \TRUE{}.
  6245. \racket{With the increase in the number of primitive operations, the
  6246. interpreter would become repetitive without some care. We refactor
  6247. the case for \code{Prim}, moving the code that differs with each
  6248. operation into the \code{interp\_op} method shown in in
  6249. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6250. \code{or} operations separately because of their short-circuiting
  6251. behavior.}
  6252. \begin{figure}[tbp]
  6253. {\if\edition\racketEd
  6254. \begin{lstlisting}
  6255. (define interp-Lif-class
  6256. (class interp-Lvar-class
  6257. (super-new)
  6258. (define/public (interp_op op) ...)
  6259. (define/override ((interp_exp env) e)
  6260. (define recur (interp_exp env))
  6261. (match e
  6262. [(Bool b) b]
  6263. [(If cnd thn els)
  6264. (match (recur cnd)
  6265. [#t (recur thn)]
  6266. [#f (recur els)])]
  6267. [(Prim 'and (list e1 e2))
  6268. (match (recur e1)
  6269. [#t (match (recur e2) [#t #t] [#f #f])]
  6270. [#f #f])]
  6271. [(Prim 'or (list e1 e2))
  6272. (define v1 (recur e1))
  6273. (match v1
  6274. [#t #t]
  6275. [#f (match (recur e2) [#t #t] [#f #f])])]
  6276. [(Prim op args)
  6277. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6278. [else ((super interp_exp env) e)]))
  6279. ))
  6280. (define (interp_Lif p)
  6281. (send (new interp-Lif-class) interp_program p))
  6282. \end{lstlisting}
  6283. \fi}
  6284. {\if\edition\pythonEd
  6285. \begin{lstlisting}
  6286. class InterpLif(InterpLvar):
  6287. def interp_exp(self, e, env):
  6288. match e:
  6289. case IfExp(test, body, orelse):
  6290. if self.interp_exp(test, env):
  6291. return self.interp_exp(body, env)
  6292. else:
  6293. return self.interp_exp(orelse, env)
  6294. case UnaryOp(Not(), v):
  6295. return not self.interp_exp(v, env)
  6296. case BoolOp(And(), values):
  6297. if self.interp_exp(values[0], env):
  6298. return self.interp_exp(values[1], env)
  6299. else:
  6300. return False
  6301. case BoolOp(Or(), values):
  6302. if self.interp_exp(values[0], env):
  6303. return True
  6304. else:
  6305. return self.interp_exp(values[1], env)
  6306. case Compare(left, [cmp], [right]):
  6307. l = self.interp_exp(left, env)
  6308. r = self.interp_exp(right, env)
  6309. return self.interp_cmp(cmp)(l, r)
  6310. case _:
  6311. return super().interp_exp(e, env)
  6312. def interp_stmts(self, ss, env):
  6313. if len(ss) == 0:
  6314. return
  6315. match ss[0]:
  6316. case If(test, body, orelse):
  6317. if self.interp_exp(test, env):
  6318. return self.interp_stmts(body + ss[1:], env)
  6319. else:
  6320. return self.interp_stmts(orelse + ss[1:], env)
  6321. case _:
  6322. return super().interp_stmts(ss, env)
  6323. ...
  6324. \end{lstlisting}
  6325. \fi}
  6326. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6327. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6328. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6329. \label{fig:interp-Lif}
  6330. \end{figure}
  6331. {\if\edition\racketEd
  6332. \begin{figure}[tbp]
  6333. \begin{lstlisting}
  6334. (define/public (interp_op op)
  6335. (match op
  6336. ['+ fx+]
  6337. ['- fx-]
  6338. ['read read-fixnum]
  6339. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6340. ['eq? (lambda (v1 v2)
  6341. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6342. (and (boolean? v1) (boolean? v2))
  6343. (and (vector? v1) (vector? v2)))
  6344. (eq? v1 v2)]))]
  6345. ['< (lambda (v1 v2)
  6346. (cond [(and (fixnum? v1) (fixnum? v2))
  6347. (< v1 v2)]))]
  6348. ['<= (lambda (v1 v2)
  6349. (cond [(and (fixnum? v1) (fixnum? v2))
  6350. (<= v1 v2)]))]
  6351. ['> (lambda (v1 v2)
  6352. (cond [(and (fixnum? v1) (fixnum? v2))
  6353. (> v1 v2)]))]
  6354. ['>= (lambda (v1 v2)
  6355. (cond [(and (fixnum? v1) (fixnum? v2))
  6356. (>= v1 v2)]))]
  6357. [else (error 'interp_op "unknown operator")]))
  6358. \end{lstlisting}
  6359. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6360. \label{fig:interp-op-Lif}
  6361. \end{figure}
  6362. \fi}
  6363. {\if\edition\pythonEd
  6364. \begin{figure}
  6365. \begin{lstlisting}
  6366. class InterpLif(InterpLvar):
  6367. ...
  6368. def interp_cmp(self, cmp):
  6369. match cmp:
  6370. case Lt():
  6371. return lambda x, y: x < y
  6372. case LtE():
  6373. return lambda x, y: x <= y
  6374. case Gt():
  6375. return lambda x, y: x > y
  6376. case GtE():
  6377. return lambda x, y: x >= y
  6378. case Eq():
  6379. return lambda x, y: x == y
  6380. case NotEq():
  6381. return lambda x, y: x != y
  6382. \end{lstlisting}
  6383. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6384. \label{fig:interp-cmp-Lif}
  6385. \end{figure}
  6386. \fi}
  6387. \section{Type Checking \LangIf{} Programs}
  6388. \label{sec:type-check-Lif}
  6389. \index{subject}{type checking}
  6390. \index{subject}{semantic analysis}
  6391. It is helpful to think about type checking in two complementary
  6392. ways. A type checker predicts the type of value that will be produced
  6393. by each expression in the program. For \LangIf{}, we have just two types,
  6394. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6395. {\if\edition\racketEd
  6396. \begin{lstlisting}
  6397. (+ 10 (- (+ 12 20)))
  6398. \end{lstlisting}
  6399. \fi}
  6400. {\if\edition\pythonEd
  6401. \begin{lstlisting}
  6402. 10 + -(12 + 20)
  6403. \end{lstlisting}
  6404. \fi}
  6405. \noindent produces a value of type \INTTY{} while
  6406. {\if\edition\racketEd
  6407. \begin{lstlisting}
  6408. (and (not #f) #t)
  6409. \end{lstlisting}
  6410. \fi}
  6411. {\if\edition\pythonEd
  6412. \begin{lstlisting}
  6413. (not False) and True
  6414. \end{lstlisting}
  6415. \fi}
  6416. \noindent produces a value of type \BOOLTY{}.
  6417. A second way to think about type checking is that it enforces a set of
  6418. rules about which operators can be applied to which kinds of
  6419. values. For example, our type checker for \LangIf{} signals an error
  6420. for the below expression {\if\edition\racketEd
  6421. \begin{lstlisting}
  6422. (not (+ 10 (- (+ 12 20))))
  6423. \end{lstlisting}
  6424. \fi}
  6425. {\if\edition\pythonEd
  6426. \begin{lstlisting}
  6427. not (10 + -(12 + 20))
  6428. \end{lstlisting}
  6429. \fi}
  6430. \noindent The subexpression
  6431. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6432. \python{\code{(10 + -(12 + 20))}}
  6433. has type \INTTY{} but the type checker enforces the rule that the
  6434. argument of \code{not} must be an expression of type \BOOLTY{}.
  6435. We implement type checking using classes and methods because they
  6436. provide the open recursion needed to reuse code as we extend the type
  6437. checker in later chapters, analogous to the use of classes and methods
  6438. for the interpreters (Section~\ref{sec:extensible-interp}).
  6439. We separate the type checker for the \LangVar{} subset into its own
  6440. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6441. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6442. from the type checker for \LangVar{}. These type checkers are in the
  6443. files
  6444. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6445. and
  6446. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6447. of the support code.
  6448. %
  6449. Each type checker is a structurally recursive function over the AST.
  6450. Given an input expression \code{e}, the type checker either signals an
  6451. error or returns \racket{an expression and} its type.
  6452. %
  6453. \racket{It returns an expression because there are situations in which
  6454. we want to change or update the expression.}
  6455. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6456. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6457. \INTTY{}. To handle variables, the type checker uses the environment
  6458. \code{env} to map variables to types.
  6459. %
  6460. \racket{Consider the case for \key{let}. We type check the
  6461. initializing expression to obtain its type \key{T} and then
  6462. associate type \code{T} with the variable \code{x} in the
  6463. environment used to type check the body of the \key{let}. Thus,
  6464. when the type checker encounters a use of variable \code{x}, it can
  6465. find its type in the environment.}
  6466. %
  6467. \python{Consider the case for assignment. We type check the
  6468. initializing expression to obtain its type \key{t}. If the variable
  6469. \code{lhs.id} is already in the environment because there was a
  6470. prior assignment, we check that this initializer has the same type
  6471. as the prior one. If this is the first assignment to the variable,
  6472. we associate type \code{t} with the variable \code{lhs.id} in the
  6473. environment. Thus, when the type checker encounters a use of
  6474. variable \code{x}, it can find its type in the environment.}
  6475. %
  6476. \racket{Regarding primitive operators, we recursively analyze the
  6477. arguments and then invoke \code{type\_check\_op} to check whether
  6478. the argument types are allowed.}
  6479. %
  6480. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6481. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6482. \racket{Several auxiliary methods are used in the type checker. The
  6483. method \code{operator-types} defines a dictionary that maps the
  6484. operator names to their parameter and return types. The
  6485. \code{type-equal?} method determines whether two types are equal,
  6486. which for now simply dispatches to \code{equal?} (deep
  6487. equality). The \code{check-type-equal?} method triggers an error if
  6488. the two types are not equal. The \code{type-check-op} method looks
  6489. up the operator in the \code{operator-types} dictionary and then
  6490. checks whether the argument types are equal to the parameter types.
  6491. The result is the return type of the operator.}
  6492. %
  6493. \python{The auxiliary method \code{check\_type\_equal} triggers
  6494. an error if the two types are not equal.}
  6495. \begin{figure}[tbp]
  6496. {\if\edition\racketEd
  6497. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6498. (define type-check-Lvar-class
  6499. (class object%
  6500. (super-new)
  6501. (define/public (operator-types)
  6502. '((+ . ((Integer Integer) . Integer))
  6503. (- . ((Integer Integer) . Integer))
  6504. (read . (() . Integer))))
  6505. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6506. (define/public (check-type-equal? t1 t2 e)
  6507. (unless (type-equal? t1 t2)
  6508. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6509. (define/public (type-check-op op arg-types e)
  6510. (match (dict-ref (operator-types) op)
  6511. [`(,param-types . ,return-type)
  6512. (for ([at arg-types] [pt param-types])
  6513. (check-type-equal? at pt e))
  6514. return-type]
  6515. [else (error 'type-check-op "unrecognized ~a" op)]))
  6516. (define/public (type-check-exp env)
  6517. (lambda (e)
  6518. (match e
  6519. [(Int n) (values (Int n) 'Integer)]
  6520. [(Var x) (values (Var x) (dict-ref env x))]
  6521. [(Let x e body)
  6522. (define-values (e^ Te) ((type-check-exp env) e))
  6523. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6524. (values (Let x e^ b) Tb)]
  6525. [(Prim op es)
  6526. (define-values (new-es ts)
  6527. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6528. (values (Prim op new-es) (type-check-op op ts e))]
  6529. [else (error 'type-check-exp "couldn't match" e)])))
  6530. (define/public (type-check-program e)
  6531. (match e
  6532. [(Program info body)
  6533. (define-values (body^ Tb) ((type-check-exp '()) body))
  6534. (check-type-equal? Tb 'Integer body)
  6535. (Program info body^)]
  6536. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6537. ))
  6538. (define (type-check-Lvar p)
  6539. (send (new type-check-Lvar-class) type-check-program p))
  6540. \end{lstlisting}
  6541. \fi}
  6542. {\if\edition\pythonEd
  6543. \begin{lstlisting}[escapechar=`]
  6544. class TypeCheckLvar:
  6545. def check_type_equal(self, t1, t2, e):
  6546. if t1 != t2:
  6547. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6548. raise Exception(msg)
  6549. def type_check_exp(self, e, env):
  6550. match e:
  6551. case BinOp(left, (Add() | Sub()), right):
  6552. l = self.type_check_exp(left, env)
  6553. check_type_equal(l, int, left)
  6554. r = self.type_check_exp(right, env)
  6555. check_type_equal(r, int, right)
  6556. return int
  6557. case UnaryOp(USub(), v):
  6558. t = self.type_check_exp(v, env)
  6559. check_type_equal(t, int, v)
  6560. return int
  6561. case Name(id):
  6562. return env[id]
  6563. case Constant(value) if isinstance(value, int):
  6564. return int
  6565. case Call(Name('input_int'), []):
  6566. return int
  6567. def type_check_stmts(self, ss, env):
  6568. if len(ss) == 0:
  6569. return
  6570. match ss[0]:
  6571. case Assign([lhs], value):
  6572. t = self.type_check_exp(value, env)
  6573. if lhs.id in env:
  6574. check_type_equal(env[lhs.id], t, value)
  6575. else:
  6576. env[lhs.id] = t
  6577. return self.type_check_stmts(ss[1:], env)
  6578. case Expr(Call(Name('print'), [arg])):
  6579. t = self.type_check_exp(arg, env)
  6580. check_type_equal(t, int, arg)
  6581. return self.type_check_stmts(ss[1:], env)
  6582. case Expr(value):
  6583. self.type_check_exp(value, env)
  6584. return self.type_check_stmts(ss[1:], env)
  6585. def type_check_P(self, p):
  6586. match p:
  6587. case Module(body):
  6588. self.type_check_stmts(body, {})
  6589. \end{lstlisting}
  6590. \fi}
  6591. \caption{Type checker for the \LangVar{} language.}
  6592. \label{fig:type-check-Lvar}
  6593. \end{figure}
  6594. \begin{figure}[tbp]
  6595. {\if\edition\racketEd
  6596. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6597. (define type-check-Lif-class
  6598. (class type-check-Lvar-class
  6599. (super-new)
  6600. (inherit check-type-equal?)
  6601. (define/override (operator-types)
  6602. (append '((and . ((Boolean Boolean) . Boolean))
  6603. (or . ((Boolean Boolean) . Boolean))
  6604. (< . ((Integer Integer) . Boolean))
  6605. (<= . ((Integer Integer) . Boolean))
  6606. (> . ((Integer Integer) . Boolean))
  6607. (>= . ((Integer Integer) . Boolean))
  6608. (not . ((Boolean) . Boolean)))
  6609. (super operator-types)))
  6610. (define/override (type-check-exp env)
  6611. (lambda (e)
  6612. (match e
  6613. [(Bool b) (values (Bool b) 'Boolean)]
  6614. [(Prim 'eq? (list e1 e2))
  6615. (define-values (e1^ T1) ((type-check-exp env) e1))
  6616. (define-values (e2^ T2) ((type-check-exp env) e2))
  6617. (check-type-equal? T1 T2 e)
  6618. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6619. [(If cnd thn els)
  6620. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6621. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6622. (define-values (els^ Te) ((type-check-exp env) els))
  6623. (check-type-equal? Tc 'Boolean e)
  6624. (check-type-equal? Tt Te e)
  6625. (values (If cnd^ thn^ els^) Te)]
  6626. [else ((super type-check-exp env) e)])))
  6627. ))
  6628. (define (type-check-Lif p)
  6629. (send (new type-check-Lif-class) type-check-program p))
  6630. \end{lstlisting}
  6631. \fi}
  6632. {\if\edition\pythonEd
  6633. \begin{lstlisting}
  6634. class TypeCheckLif(TypeCheckLvar):
  6635. def type_check_exp(self, e, env):
  6636. match e:
  6637. case Constant(value) if isinstance(value, bool):
  6638. return bool
  6639. case BinOp(left, Sub(), right):
  6640. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6641. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6642. return int
  6643. case UnaryOp(Not(), v):
  6644. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6645. return bool
  6646. case BoolOp(op, values):
  6647. left = values[0] ; right = values[1]
  6648. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6649. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6650. return bool
  6651. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6652. or isinstance(cmp, NotEq):
  6653. l = self.type_check_exp(left, env)
  6654. r = self.type_check_exp(right, env)
  6655. check_type_equal(l, r, e)
  6656. return bool
  6657. case Compare(left, [cmp], [right]):
  6658. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6659. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6660. return bool
  6661. case IfExp(test, body, orelse):
  6662. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6663. b = self.type_check_exp(body, env)
  6664. o = self.type_check_exp(orelse, env)
  6665. check_type_equal(b, o, e)
  6666. return b
  6667. case _:
  6668. return super().type_check_exp(e, env)
  6669. def type_check_stmts(self, ss, env):
  6670. if len(ss) == 0:
  6671. return
  6672. match ss[0]:
  6673. case If(test, body, orelse):
  6674. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6675. b = self.type_check_stmts(body, env)
  6676. o = self.type_check_stmts(orelse, env)
  6677. check_type_equal(b, o, ss[0])
  6678. return self.type_check_stmts(ss[1:], env)
  6679. case _:
  6680. return super().type_check_stmts(ss, env)
  6681. \end{lstlisting}
  6682. \fi}
  6683. \caption{Type checker for the \LangIf{} language.}
  6684. \label{fig:type-check-Lif}
  6685. \end{figure}
  6686. The type checker for \LangIf{} is defined in
  6687. Figure~\ref{fig:type-check-Lif}.
  6688. %
  6689. The type of a Boolean constant is \BOOLTY{}.
  6690. %
  6691. \racket{The \code{operator-types} function adds dictionary entries for
  6692. the new operators.}
  6693. %
  6694. \python{Logical not requires its argument to be a \BOOLTY{} and
  6695. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6696. %
  6697. The equality operator requires the two arguments to have the same type
  6698. and therefore we handle it separately from the other operators.
  6699. %
  6700. \python{The other comparisons (less-than, etc.) require their
  6701. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6702. %
  6703. The condition of an \code{if} must
  6704. be of \BOOLTY{} type and the two branches must have the same type.
  6705. \begin{exercise}\normalfont\normalsize
  6706. Create 10 new test programs in \LangIf{}. Half of the programs should
  6707. have a type error. For those programs, create an empty file with the
  6708. same base name but with file extension \code{.tyerr}. For example, if
  6709. the test
  6710. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6711. is expected to error, then create
  6712. an empty file named \code{cond\_test\_14.tyerr}.
  6713. %
  6714. \racket{This indicates to \code{interp-tests} and
  6715. \code{compiler-tests} that a type error is expected. }
  6716. %
  6717. The other half of the test programs should not have type errors.
  6718. %
  6719. \racket{In the \code{run-tests.rkt} script, change the second argument
  6720. of \code{interp-tests} and \code{compiler-tests} to
  6721. \code{type-check-Lif}, which causes the type checker to run prior to
  6722. the compiler passes. Temporarily change the \code{passes} to an
  6723. empty list and run the script, thereby checking that the new test
  6724. programs either type check or not as intended.}
  6725. %
  6726. Run the test script to check that these test programs type check as
  6727. expected.
  6728. \end{exercise}
  6729. \clearpage
  6730. \section{The \LangCIf{} Intermediate Language}
  6731. \label{sec:Cif}
  6732. {\if\edition\racketEd
  6733. %
  6734. The \LangCIf{} language builds on \LangCVar{} by adding logical and
  6735. comparison operators to the \Exp{} non-terminal and the literals
  6736. \TRUE{} and \FALSE{} to the \Arg{} non-terminal. Regarding control
  6737. flow, \LangCIf{} adds \key{goto} and \code{if} statements to the
  6738. \Tail{} non-terminal. The condition of an \code{if} statement is a
  6739. comparison operation and the branches are \code{goto} statements,
  6740. making it straightforward to compile \code{if} statements to x86. The
  6741. \key{CProgram} construct contains an alist mapping labels to $\Tail$
  6742. expressions. A \code{goto} statement transfers control to the $\Tail$
  6743. expression corresponding to its label.
  6744. %
  6745. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6746. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6747. defines its abstract syntax.
  6748. %
  6749. \fi}
  6750. %
  6751. {\if\edition\pythonEd
  6752. %
  6753. The output of \key{explicate\_control} is a language similar to the
  6754. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6755. \code{goto} statements, so we name it \LangCIf{}.
  6756. %
  6757. The \LangCIf{} language supports the same operators as \LangIf{} but
  6758. the arguments of operators are restricted to atomic expressions. The
  6759. \LangCIf{} language does not include \code{if} expressions but it does
  6760. include a restricted form of \code{if} statement. The condition must be
  6761. a comparison and the two branches may only contain \code{goto}
  6762. statements. These restrictions make it easier to translate \code{if}
  6763. statements to x86. The \LangCIf{} language also adds a \code{return}
  6764. statement to finish the program with a specified value.
  6765. %
  6766. The \key{CProgram} construct contains a dictionary mapping labels to
  6767. lists of statements that end with a \code{return} statement, a
  6768. \code{goto}, or a conditional \code{goto}.
  6769. %% Statement lists of this
  6770. %% form are called \emph{basic blocks}\index{subject}{basic block}: there
  6771. %% is a control transfer at the end and control only enters at the
  6772. %% beginning of the list, which is marked by the label.
  6773. %
  6774. A \code{goto} statement transfers control to the sequence of statements
  6775. associated with its label.
  6776. %
  6777. The concrete syntax for \LangCIf{} is defined in
  6778. Figure~\ref{fig:c1-concrete-syntax} and the abstract syntax is defined
  6779. in Figure~\ref{fig:c1-syntax}.
  6780. %
  6781. \fi}
  6782. %
  6783. \newcommand{\CifGrammarRacket}{
  6784. \begin{array}{lcl}
  6785. \Atm &::=& \itm{bool} \\
  6786. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6787. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6788. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6789. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6790. \end{array}
  6791. }
  6792. \newcommand{\CifASTRacket}{
  6793. \begin{array}{lcl}
  6794. \Atm &::=& \BOOL{\itm{bool}} \\
  6795. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6796. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6797. \Tail &::= & \GOTO{\itm{label}} \\
  6798. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6799. \end{array}
  6800. }
  6801. \newcommand{\CifGrammarPython}{
  6802. \begin{array}{lcl}
  6803. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6804. \Exp &::= & \Atm \MID \CREAD{}
  6805. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6806. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6807. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6808. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6809. &\MID& \CASSIGN{\Var}{\Exp}
  6810. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6811. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6812. \end{array}
  6813. }
  6814. \newcommand{\CifASTPython}{
  6815. \begin{array}{lcl}
  6816. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6817. \Exp &::= & \Atm \MID \READ{} \\
  6818. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6819. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6820. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6821. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6822. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6823. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6824. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6825. \end{array}
  6826. }
  6827. \begin{figure}[tbp]
  6828. \fbox{
  6829. \begin{minipage}{0.96\textwidth}
  6830. \small
  6831. {\if\edition\racketEd
  6832. \[
  6833. \begin{array}{l}
  6834. \gray{\CvarGrammarRacket} \\ \hline
  6835. \CifGrammarRacket \\
  6836. \begin{array}{lcl}
  6837. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6838. \end{array}
  6839. \end{array}
  6840. \]
  6841. \fi}
  6842. {\if\edition\pythonEd
  6843. \[
  6844. \begin{array}{l}
  6845. \CifGrammarPython \\
  6846. \begin{array}{lcl}
  6847. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6848. \end{array}
  6849. \end{array}
  6850. \]
  6851. \fi}
  6852. \end{minipage}
  6853. }
  6854. \caption{The concrete syntax of the \LangCIf{} intermediate language,
  6855. an extension of \LangCVar{} (Figure~\ref{fig:c0-concrete-syntax}).}
  6856. \label{fig:c1-concrete-syntax}
  6857. \end{figure}
  6858. \begin{figure}[tp]
  6859. \fbox{
  6860. \begin{minipage}{0.96\textwidth}
  6861. \small
  6862. {\if\edition\racketEd
  6863. \[
  6864. \begin{array}{l}
  6865. \gray{\CvarASTRacket} \\ \hline
  6866. \CifASTRacket \\
  6867. \begin{array}{lcl}
  6868. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6869. \end{array}
  6870. \end{array}
  6871. \]
  6872. \fi}
  6873. {\if\edition\pythonEd
  6874. \[
  6875. \begin{array}{l}
  6876. \CifASTPython \\
  6877. \begin{array}{lcl}
  6878. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6879. \end{array}
  6880. \end{array}
  6881. \]
  6882. \fi}
  6883. \end{minipage}
  6884. }
  6885. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6886. (Figure~\ref{fig:c0-syntax})}.}
  6887. \label{fig:c1-syntax}
  6888. \end{figure}
  6889. \section{The \LangXIf{} Language}
  6890. \label{sec:x86-if}
  6891. \index{subject}{x86} To implement the new logical operations, the
  6892. comparison operations, and the \key{if} expression\python{ and
  6893. statement}, we delve further into the x86
  6894. language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1} define
  6895. the concrete and abstract syntax for the \LangXIf{} subset of x86,
  6896. which includes instructions for logical operations, comparisons, and
  6897. \racket{conditional} jumps.
  6898. %
  6899. \python{The abstract syntax for an \LangXIf{} program contains a
  6900. dictionary mapping labels to sequences of instructions, each of
  6901. which we refer to as a \emph{basic block}\index{subject}{basic
  6902. block}.}
  6903. One challenge is that x86 does not provide an instruction that
  6904. directly implements logical negation (\code{not} in \LangIf{} and
  6905. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6906. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6907. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6908. bit of its arguments, and writes the results into its second argument.
  6909. Recall the truth table for exclusive-or:
  6910. \begin{center}
  6911. \begin{tabular}{l|cc}
  6912. & 0 & 1 \\ \hline
  6913. 0 & 0 & 1 \\
  6914. 1 & 1 & 0
  6915. \end{tabular}
  6916. \end{center}
  6917. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6918. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6919. for the bit $1$, the result is the opposite of the second bit. Thus,
  6920. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6921. the first argument as follows, where $\Arg$ is the translation of
  6922. $\Atm$ to x86.
  6923. \[
  6924. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6925. \qquad\Rightarrow\qquad
  6926. \begin{array}{l}
  6927. \key{movq}~ \Arg\key{,} \Var\\
  6928. \key{xorq}~ \key{\$1,} \Var
  6929. \end{array}
  6930. \]
  6931. \newcommand{\GrammarXIf}{
  6932. \begin{array}{lcl}
  6933. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6934. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6935. \Arg &::=& \key{\%}\itm{bytereg}\\
  6936. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6937. \Instr &::=& \key{xorq}~\Arg\key{,}~\Arg
  6938. \MID \key{cmpq}~\Arg\key{,}~\Arg
  6939. \MID \key{set}cc~\Arg
  6940. \MID \key{movzbq}~\Arg\key{,}~\Arg \\
  6941. &\MID& \key{j}cc~\itm{label} \\
  6942. \end{array}
  6943. }
  6944. \begin{figure}[tp]
  6945. \fbox{
  6946. \begin{minipage}{0.96\textwidth}
  6947. \[
  6948. \begin{array}{l}
  6949. \gray{\GrammarXInt} \\ \hline
  6950. \GrammarXIf \\
  6951. \begin{array}{lcl}
  6952. \LangXIfM{} &::= & \key{.globl main} \\
  6953. & & \key{main:} \; \Instr\ldots
  6954. \end{array}
  6955. \end{array}
  6956. \]
  6957. \end{minipage}
  6958. }
  6959. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6960. \label{fig:x86-1-concrete}
  6961. \end{figure}
  6962. \newcommand{\ASTXIfRacket}{
  6963. \begin{array}{lcl}
  6964. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6965. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6966. \Arg &::=& \BYTEREG{\itm{bytereg}} \\
  6967. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6968. \Instr &::=& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6969. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6970. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6971. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6972. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}}
  6973. \end{array}
  6974. }
  6975. \begin{figure}[tp]
  6976. \fbox{
  6977. \begin{minipage}{0.96\textwidth}
  6978. \small
  6979. {\if\edition\racketEd
  6980. \[
  6981. \begin{array}{l}
  6982. \gray{\ASTXIntRacket} \\ \hline
  6983. \ASTXIfRacket \\
  6984. \begin{array}{lcl}
  6985. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  6986. \end{array}
  6987. \end{array}
  6988. \]
  6989. \fi}
  6990. %
  6991. {\if\edition\pythonEd
  6992. \[
  6993. \begin{array}{lcl}
  6994. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6995. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6996. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6997. \MID \BYTEREG{\itm{bytereg}} \\
  6998. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6999. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  7000. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  7001. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  7002. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  7003. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  7004. \MID \PUSHQ{\Arg}} \\
  7005. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  7006. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  7007. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  7008. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  7009. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  7010. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  7011. \Block &::= & \Instr^{+} \\
  7012. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Block \key{,} \ldots \RC }
  7013. \end{array}
  7014. \]
  7015. \fi}
  7016. \end{minipage}
  7017. }
  7018. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  7019. \label{fig:x86-1}
  7020. \end{figure}
  7021. Next we consider the x86 instructions that are relevant for compiling
  7022. the comparison operations. The \key{cmpq} instruction compares its two
  7023. arguments to determine whether one argument is less than, equal, or
  7024. greater than the other argument. The \key{cmpq} instruction is unusual
  7025. regarding the order of its arguments and where the result is
  7026. placed. The argument order is backwards: if you want to test whether
  7027. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  7028. \key{cmpq} is placed in the special EFLAGS register. This register
  7029. cannot be accessed directly but it can be queried by a number of
  7030. instructions, including the \key{set} instruction. The instruction
  7031. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7032. depending on whether the contents of the EFLAGS register matches the
  7033. condition code \itm{cc}: \key{e} for equal, \key{l} for less, \key{le}
  7034. for less-or-equal, \key{g} for greater, \key{ge} for greater-or-equal.
  7035. The \key{set} instruction has a quirk in that its destination argument
  7036. must be single byte register, such as \code{al} (L for lower bits) or
  7037. \code{ah} (H for higher bits), which are part of the \code{rax}
  7038. register. Thankfully, the \key{movzbq} instruction can be used to
  7039. move from a single byte register to a normal 64-bit register. The
  7040. abstract syntax for the \code{set} instruction differs from the
  7041. concrete syntax in that it separates the instruction name from the
  7042. condition code.
  7043. \python{The x86 instructions for jumping are relevant to the
  7044. compilation of \key{if} expressions.}
  7045. %
  7046. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7047. counter to the address of the instruction after the specified
  7048. label.}
  7049. %
  7050. \racket{The x86 instruction for conditional jump is relevant to the
  7051. compilation of \key{if} expressions.}
  7052. %
  7053. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7054. counter to point to the instruction after \itm{label} depending on
  7055. whether the result in the EFLAGS register matches the condition code
  7056. \itm{cc}, otherwise the jump instruction falls through to the next
  7057. instruction. Like the abstract syntax for \code{set}, the abstract
  7058. syntax for conditional jump separates the instruction name from the
  7059. condition code. For example, \JMPIF{\QUOTE{\code{le}}}{\QUOTE{\code{foo}}}
  7060. corresponds to \code{jle foo}. Because the conditional jump instruction
  7061. relies on the EFLAGS register, it is common for it to be immediately preceded by
  7062. a \key{cmpq} instruction to set the EFLAGS register.
  7063. \section{Shrink the \LangIf{} Language}
  7064. \label{sec:shrink-Lif}
  7065. The \LangIf{} language includes several features that are easily
  7066. expressible with other features. For example, \code{and} and \code{or}
  7067. are expressible using \code{if} as follows.
  7068. \begin{align*}
  7069. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7070. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7071. \end{align*}
  7072. By performing these translations in the front-end of the compiler,
  7073. subsequent passes of the compiler do not need to deal with these features,
  7074. making the passes shorter.
  7075. On the other hand, sometimes translations reduce the efficiency of the
  7076. generated code by increasing the number of instructions. For example,
  7077. expressing subtraction in terms of negation
  7078. \[
  7079. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7080. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7081. \]
  7082. produces code with two x86 instructions (\code{negq} and \code{addq})
  7083. instead of just one (\code{subq}).
  7084. \begin{exercise}\normalfont\normalsize
  7085. %
  7086. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7087. the language by translating them to \code{if} expressions in \LangIf{}.
  7088. %
  7089. Create four test programs that involve these operators.
  7090. %
  7091. {\if\edition\racketEd
  7092. In the \code{run-tests.rkt} script, add the following entry for
  7093. \code{shrink} to the list of passes (it should be the only pass at
  7094. this point).
  7095. \begin{lstlisting}
  7096. (list "shrink" shrink interp_Lif type-check-Lif)
  7097. \end{lstlisting}
  7098. This instructs \code{interp-tests} to run the interpreter
  7099. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7100. output of \code{shrink}.
  7101. \fi}
  7102. %
  7103. Run the script to test your compiler on all the test programs.
  7104. \end{exercise}
  7105. {\if\edition\racketEd
  7106. \section{Uniquify Variables}
  7107. \label{sec:uniquify-Lif}
  7108. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7109. \code{if} expressions.
  7110. \begin{exercise}\normalfont\normalsize
  7111. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7112. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7113. \begin{lstlisting}
  7114. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7115. \end{lstlisting}
  7116. Run the script to test your compiler.
  7117. \end{exercise}
  7118. \fi}
  7119. \section{Remove Complex Operands}
  7120. \label{sec:remove-complex-opera-Lif}
  7121. The output language of \code{remove\_complex\_operands} is
  7122. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the monadic
  7123. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7124. but the \code{if} expression is not. All three sub-expressions of an
  7125. \code{if} are allowed to be complex expressions but the operands of
  7126. \code{not} and the comparisons must be atomic.
  7127. %
  7128. \python{We add a new language form, the \code{Begin} expression, to aid
  7129. in the translation of \code{if} expressions. When we recursively
  7130. process the two branches of the \code{if}, we generate temporary
  7131. variables and their initializing expressions. However, these
  7132. expressions may contain side effects and should only be executed
  7133. when the condition of the \code{if} is true (for the ``then''
  7134. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7135. a way to initialize the temporary variables within the two branches
  7136. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7137. form execute the statements $ss$ and then returns the result of
  7138. expression $e$.}
  7139. Add cases to the \code{rco\_exp} and \code{rco\_atom} functions for
  7140. the new features in \LangIf{}. When recursively processing
  7141. subexpressions, recall that you should invoke \code{rco\_atom} when
  7142. the output needs to be an \Atm{} (as specified in the grammar for
  7143. \LangIfANF{}) and invoke \code{rco\_exp} when the output should be
  7144. \Exp{}. Regarding \code{if}, it is particularly important to
  7145. \textbf{not} replace its condition with a temporary variable because
  7146. that would interfere with the generation of high-quality output in the
  7147. upcoming \code{explicate\_control} pass.
  7148. \newcommand{\LifMonadASTRacket}{
  7149. \begin{array}{rcl}
  7150. \Atm &::=& \BOOL{\itm{bool}}\\
  7151. \Exp &::=& \UNIOP{\key{not}}{\Atm}
  7152. \MID \BINOP{\itm{cmp}}{\Atm}{\Atm}
  7153. \MID \IF{\Exp}{\Exp}{\Exp}
  7154. \end{array}
  7155. }
  7156. \newcommand{\LifMonadASTPython}{
  7157. \begin{array}{rcl}
  7158. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7159. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7160. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7161. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7162. \Atm &::=& \BOOL{\itm{bool}}\\
  7163. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7164. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7165. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7166. \end{array}
  7167. }
  7168. \begin{figure}[tp]
  7169. \centering
  7170. \fbox{
  7171. \begin{minipage}{0.96\textwidth}
  7172. {\if\edition\racketEd
  7173. \[
  7174. \begin{array}{l}
  7175. \gray{\LvarMonadASTRacket} \\ \hline
  7176. \LifMonadASTRacket \\
  7177. \begin{array}{rcl}
  7178. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7179. \end{array}
  7180. \end{array}
  7181. \]
  7182. \fi}
  7183. {\if\edition\pythonEd
  7184. \[
  7185. \begin{array}{l}
  7186. \gray{\LvarMonadASTPython} \\ \hline
  7187. \LifMonadASTPython \\
  7188. \begin{array}{rcl}
  7189. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7190. \end{array}
  7191. \end{array}
  7192. \]
  7193. \fi}
  7194. \end{minipage}
  7195. }
  7196. \caption{\LangIfANF{} is \LangIf{} in monadic normal form
  7197. (extends \LangVarANF in Figure~\ref{fig:Lvar-anf-syntax}).}
  7198. \label{fig:Lif-anf-syntax}
  7199. \end{figure}
  7200. \begin{exercise}\normalfont\normalsize
  7201. %
  7202. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7203. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7204. %
  7205. Create three new \LangIf{} programs that exercise the interesting
  7206. code in this pass.
  7207. %
  7208. {\if\edition\racketEd
  7209. In the \code{run-tests.rkt} script, add the following entry to the
  7210. list of \code{passes} and then run the script to test your compiler.
  7211. \begin{lstlisting}
  7212. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7213. \end{lstlisting}
  7214. \fi}
  7215. \end{exercise}
  7216. \section{Explicate Control}
  7217. \label{sec:explicate-control-Lif}
  7218. \racket{Recall that the purpose of \code{explicate\_control} is to
  7219. make the order of evaluation explicit in the syntax of the program.
  7220. With the addition of \key{if} this gets more interesting.}
  7221. %
  7222. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7223. %
  7224. The main challenge to overcome is that the condition of an \key{if}
  7225. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7226. condition must be a comparison.
  7227. As a motivating example, consider the following program that has an
  7228. \key{if} expression nested in the condition of another \key{if}.%
  7229. \python{\footnote{Programmers rarely write nested \code{if}
  7230. expressions, but it is not uncommon for the condition of an
  7231. \code{if} statement to be a call of a function that also contains an
  7232. \code{if} statement. When such a function is inlined, the result is
  7233. a nested \code{if} that requires the techniques discussed in this
  7234. section.}}
  7235. % cond_test_41.rkt, if_lt_eq.py
  7236. \begin{center}
  7237. \begin{minipage}{0.96\textwidth}
  7238. {\if\edition\racketEd
  7239. \begin{lstlisting}
  7240. (let ([x (read)])
  7241. (let ([y (read)])
  7242. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7243. (+ y 2)
  7244. (+ y 10))))
  7245. \end{lstlisting}
  7246. \fi}
  7247. {\if\edition\pythonEd
  7248. \begin{lstlisting}
  7249. x = input_int()
  7250. y = input_int()
  7251. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7252. \end{lstlisting}
  7253. \fi}
  7254. \end{minipage}
  7255. \end{center}
  7256. %
  7257. The naive way to compile \key{if} and the comparison operations would
  7258. be to handle each of them in isolation, regardless of their context.
  7259. Each comparison would be translated into a \key{cmpq} instruction
  7260. followed by several instructions to move the result from the EFLAGS
  7261. register into a general purpose register or stack location. Each
  7262. \key{if} would be translated into a \key{cmpq} instruction followed by
  7263. a conditional jump. The generated code for the inner \key{if} in the
  7264. above example would be as follows.
  7265. \begin{center}
  7266. \begin{minipage}{0.96\textwidth}
  7267. \begin{lstlisting}
  7268. cmpq $1, x
  7269. setl %al
  7270. movzbq %al, tmp
  7271. cmpq $1, tmp
  7272. je then_branch_1
  7273. jmp else_branch_1
  7274. \end{lstlisting}
  7275. \end{minipage}
  7276. \end{center}
  7277. Notice that the three instructions starting with \code{setl} are
  7278. redundant: the conditional jump could come immediately after the first
  7279. \code{cmpq}.
  7280. Our goal will be to compile \key{if} expressions so that the relevant
  7281. comparison instruction appears directly before the conditional jump.
  7282. For example, we want to generate the following code for the inner
  7283. \code{if}.
  7284. \begin{center}
  7285. \begin{minipage}{0.96\textwidth}
  7286. \begin{lstlisting}
  7287. cmpq $1, x
  7288. jl then_branch_1
  7289. jmp else_branch_1
  7290. \end{lstlisting}
  7291. \end{minipage}
  7292. \end{center}
  7293. One way to achieve this goal is to reorganize the code at the level of
  7294. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7295. the following code.
  7296. \begin{center}
  7297. \begin{minipage}{0.96\textwidth}
  7298. {\if\edition\racketEd
  7299. \begin{lstlisting}
  7300. (let ([x (read)])
  7301. (let ([y (read)])
  7302. (if (< x 1)
  7303. (if (eq? x 0)
  7304. (+ y 2)
  7305. (+ y 10))
  7306. (if (eq? x 2)
  7307. (+ y 2)
  7308. (+ y 10)))))
  7309. \end{lstlisting}
  7310. \fi}
  7311. {\if\edition\pythonEd
  7312. \begin{lstlisting}
  7313. x = input_int()
  7314. y = input_int()
  7315. print(((y + 2) if x == 0 else (y + 10)) \
  7316. if (x < 1) \
  7317. else ((y + 2) if (x == 2) else (y + 10)))
  7318. \end{lstlisting}
  7319. \fi}
  7320. \end{minipage}
  7321. \end{center}
  7322. Unfortunately, this approach duplicates the two branches from the
  7323. outer \code{if} and a compiler must never duplicate code! After all,
  7324. the two branches could be very large expressions.
  7325. How can we apply the above transformation but without duplicating
  7326. code? In other words, how can two different parts of a program refer
  7327. to one piece of code.
  7328. %
  7329. The answer is that we must move away from abstract syntax \emph{trees}
  7330. and instead use \emph{graphs}.
  7331. %
  7332. At the level of x86 assembly this is straightforward because we can
  7333. label the code for each branch and insert jumps in all the places that
  7334. need to execute the branch. In this way, jump instructions are edges
  7335. in the graph and the basic blocks are the nodes.
  7336. %
  7337. Likewise, our language \LangCIf{} provides the ability to label a
  7338. sequence of statements and to jump to a label via \code{goto}.
  7339. As a preview of what \code{explicate\_control} will do,
  7340. Figure~\ref{fig:explicate-control-s1-38} shows the output of
  7341. \code{explicate\_control} on the above example. Note how the condition
  7342. of every \code{if} is a comparison operation and that we have not
  7343. duplicated any code, but instead used labels and \code{goto} to enable
  7344. sharing of code.
  7345. \begin{figure}[tbp]
  7346. {\if\edition\racketEd
  7347. \begin{tabular}{lll}
  7348. \begin{minipage}{0.4\textwidth}
  7349. % cond_test_41.rkt
  7350. \begin{lstlisting}
  7351. (let ([x (read)])
  7352. (let ([y (read)])
  7353. (if (if (< x 1)
  7354. (eq? x 0)
  7355. (eq? x 2))
  7356. (+ y 2)
  7357. (+ y 10))))
  7358. \end{lstlisting}
  7359. \end{minipage}
  7360. &
  7361. $\Rightarrow$
  7362. &
  7363. \begin{minipage}{0.55\textwidth}
  7364. \begin{lstlisting}
  7365. start:
  7366. x = (read);
  7367. y = (read);
  7368. if (< x 1)
  7369. goto block_4;
  7370. else
  7371. goto block_5;
  7372. block_4:
  7373. if (eq? x 0)
  7374. goto block_2;
  7375. else
  7376. goto block_3;
  7377. block_5:
  7378. if (eq? x 2)
  7379. goto block_2;
  7380. else
  7381. goto block_3;
  7382. block_2:
  7383. return (+ y 2);
  7384. block_3:
  7385. return (+ y 10);
  7386. \end{lstlisting}
  7387. \end{minipage}
  7388. \end{tabular}
  7389. \fi}
  7390. {\if\edition\pythonEd
  7391. \begin{tabular}{lll}
  7392. \begin{minipage}{0.4\textwidth}
  7393. % cond_test_41.rkt
  7394. \begin{lstlisting}
  7395. x = input_int()
  7396. y = input_int()
  7397. print(y + 2 \
  7398. if (x == 0 \
  7399. if x < 1 \
  7400. else x == 2) \
  7401. else y + 10)
  7402. \end{lstlisting}
  7403. \end{minipage}
  7404. &
  7405. $\Rightarrow$
  7406. &
  7407. \begin{minipage}{0.55\textwidth}
  7408. \begin{lstlisting}
  7409. start:
  7410. x = input_int()
  7411. y = input_int()
  7412. if x < 1:
  7413. goto block_8
  7414. else:
  7415. goto block_9
  7416. block_8:
  7417. if x == 0:
  7418. goto block_4
  7419. else:
  7420. goto block_5
  7421. block_9:
  7422. if x == 2:
  7423. goto block_6
  7424. else:
  7425. goto block_7
  7426. block_4:
  7427. goto block_2
  7428. block_5:
  7429. goto block_3
  7430. block_6:
  7431. goto block_2
  7432. block_7:
  7433. goto block_3
  7434. block_2:
  7435. tmp_0 = y + 2
  7436. goto block_1
  7437. block_3:
  7438. tmp_0 = y + 10
  7439. goto block_1
  7440. block_1:
  7441. print(tmp_0)
  7442. return 0
  7443. \end{lstlisting}
  7444. \end{minipage}
  7445. \end{tabular}
  7446. \fi}
  7447. \caption{Translation from \LangIf{} to \LangCIf{}
  7448. via the \code{explicate\_control}.}
  7449. \label{fig:explicate-control-s1-38}
  7450. \end{figure}
  7451. {\if\edition\racketEd
  7452. %
  7453. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7454. \code{explicate\_control} for \LangVar{} using two recursive
  7455. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7456. former function translates expressions in tail position whereas the
  7457. later function translates expressions on the right-hand-side of a
  7458. \key{let}. With the addition of \key{if} expression to \LangIf{} we
  7459. have a new kind of position to deal with: the predicate position of
  7460. the \key{if}. We need another function, \code{explicate\_pred}, that
  7461. decides how to compile an \key{if} by analyzing its condition. So
  7462. \code{explicate\_pred} takes an \LangIf{} expression and two
  7463. \LangCIf{} tails for the then-branch and else-branch and outputs a
  7464. tail. In the following paragraphs we discuss specific cases in the
  7465. \code{explicate\_tail}, \code{explicate\_assign}, and
  7466. \code{explicate\_pred} functions.
  7467. %
  7468. \fi}
  7469. %
  7470. {\if\edition\pythonEd
  7471. %
  7472. We recommend implementing \code{explicate\_control} using the
  7473. following four auxiliary functions.
  7474. \begin{description}
  7475. \item[\code{explicate\_effect}] generates code for expressions as
  7476. statements, so their result is ignored and only their side effects
  7477. matter.
  7478. \item[\code{explicate\_assign}] generates code for expressions
  7479. on the right-hand side of an assignment.
  7480. \item[\code{explicate\_pred}] generates code for an \code{if}
  7481. expression or statement by analyzing the condition expression.
  7482. \item[\code{explicate\_stmt}] generates code for statements.
  7483. \end{description}
  7484. These four functions should build the dictionary of basic blocks. The
  7485. following auxiliary function can be used to create a new basic block
  7486. from a list of statements. It returns a \code{goto} statement that
  7487. jumps to the new basic block.
  7488. \begin{center}
  7489. \begin{minipage}{\textwidth}
  7490. \begin{lstlisting}
  7491. def create_block(stmts, basic_blocks):
  7492. label = label_name(generate_name('block'))
  7493. basic_blocks[label] = stmts
  7494. return Goto(label)
  7495. \end{lstlisting}
  7496. \end{minipage}
  7497. \end{center}
  7498. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7499. \code{explicate\_control} pass.
  7500. The \code{explicate\_effect} function has three parameters: 1) the
  7501. expression to be compiled, 2) the already-compiled code for this
  7502. expression's \emph{continuation}, that is, the list of statements that
  7503. should execute after this expression, and 3) the dictionary of
  7504. generated basic blocks. The \code{explicate\_effect} function returns
  7505. a list of \LangCIf{} statements and it may add to the dictionary of
  7506. basic blocks.
  7507. %
  7508. Let's consider a few of the cases for the expression to be compiled.
  7509. If the expression to be compiled is a constant, then it can be
  7510. discarded because it has no side effects. If it's a \CREAD{}, then it
  7511. has a side-effect and should be preserved. So the expression should be
  7512. translated into a statement using the \code{Expr} AST class. If the
  7513. expression to be compiled is an \code{if} expression, we translate the
  7514. two branches using \code{explicate\_effect} and then translate the
  7515. condition expression using \code{explicate\_pred}, which generates
  7516. code for the entire \code{if}.
  7517. The \code{explicate\_assign} function has four parameters: 1) the
  7518. right-hand-side of the assignment, 2) the left-hand-side of the
  7519. assignment (the variable), 3) the continuation, and 4) the dictionary
  7520. of basic blocks. The \code{explicate\_assign} function returns a list
  7521. of \LangCIf{} statements and it may add to the dictionary of basic
  7522. blocks.
  7523. When the right-hand-side is an \code{if} expression, there is some
  7524. work to do. In particular, the two branches should be translated using
  7525. \code{explicate\_assign} and the condition expression should be
  7526. translated using \code{explicate\_pred}. Otherwise we can simply
  7527. generate an assignment statement, with the given left and right-hand
  7528. sides, concatenated with its continuation.
  7529. \begin{figure}[tbp]
  7530. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7531. def explicate_effect(e, cont, basic_blocks):
  7532. match e:
  7533. case IfExp(test, body, orelse):
  7534. ...
  7535. case Call(func, args):
  7536. ...
  7537. case Begin(body, result):
  7538. ...
  7539. case _:
  7540. ...
  7541. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7542. match rhs:
  7543. case IfExp(test, body, orelse):
  7544. ...
  7545. case Begin(body, result):
  7546. ...
  7547. case _:
  7548. return [Assign([lhs], rhs)] + cont
  7549. def explicate_pred(cnd, thn, els, basic_blocks):
  7550. match cnd:
  7551. case Compare(left, [op], [right]):
  7552. goto_thn = create_block(thn, basic_blocks)
  7553. goto_els = create_block(els, basic_blocks)
  7554. return [If(cnd, [goto_thn], [goto_els])]
  7555. case Constant(True):
  7556. return thn;
  7557. case Constant(False):
  7558. return els;
  7559. case UnaryOp(Not(), operand):
  7560. ...
  7561. case IfExp(test, body, orelse):
  7562. ...
  7563. case Begin(body, result):
  7564. ...
  7565. case _:
  7566. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7567. [create_block(els, basic_blocks)],
  7568. [create_block(thn, basic_blocks)])]
  7569. def explicate_stmt(s, cont, basic_blocks):
  7570. match s:
  7571. case Assign([lhs], rhs):
  7572. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7573. case Expr(value):
  7574. return explicate_effect(value, cont, basic_blocks)
  7575. case If(test, body, orelse):
  7576. ...
  7577. def explicate_control(p):
  7578. match p:
  7579. case Module(body):
  7580. new_body = [Return(Constant(0))]
  7581. basic_blocks = {}
  7582. for s in reversed(body):
  7583. new_body = explicate_stmt(s, new_body, basic_blocks)
  7584. basic_blocks[label_name('start')] = new_body
  7585. return CProgram(basic_blocks)
  7586. \end{lstlisting}
  7587. \caption{Skeleton for the \code{explicate\_control} pass.}
  7588. \label{fig:explicate-control-Lif}
  7589. \end{figure}
  7590. \fi}
  7591. {\if\edition\racketEd
  7592. \subsection{Explicate Tail and Assign}
  7593. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7594. additional cases for Boolean constants and \key{if}. The cases for
  7595. \code{if} should recursively compile the two branches using either
  7596. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7597. cases should then invoke \code{explicate\_pred} on the condition
  7598. expression, passing in the generated code for the two branches. For
  7599. example, consider the following program with an \code{if} in tail
  7600. position.
  7601. % cond_test_6.rkt
  7602. \begin{lstlisting}
  7603. (let ([x (read)])
  7604. (if (eq? x 0) 42 777))
  7605. \end{lstlisting}
  7606. The two branches are recursively compiled to return statements. We
  7607. then delegate to \code{explicate\_pred}, passing the condition
  7608. \code{(eq? x 0)} and the two return statements. We return to this
  7609. example shortly when we discuss \code{explicate\_pred}.
  7610. Next let us consider a program with an \code{if} on the right-hand
  7611. side of a \code{let}.
  7612. \begin{lstlisting}
  7613. (let ([y (read)])
  7614. (let ([x (if (eq? y 0) 40 777)])
  7615. (+ x 2)))
  7616. \end{lstlisting}
  7617. Note that the body of the inner \code{let} will have already been
  7618. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7619. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7620. to recursively process both branches of the \code{if}, and we do not
  7621. want to duplicate code, so we generate the following block using an
  7622. auxiliary function named \code{create\_block} that we discuss below.
  7623. \begin{lstlisting}
  7624. block_6:
  7625. return (+ x 2)
  7626. \end{lstlisting}
  7627. We then use \code{goto block\_6;} as the \code{cont} argument for
  7628. compiling the branches. So the two branches compile to
  7629. \begin{center}
  7630. \begin{minipage}{0.2\textwidth}
  7631. \begin{lstlisting}
  7632. x = 40;
  7633. goto block_6;
  7634. \end{lstlisting}
  7635. \end{minipage}
  7636. \hspace{0.5in} and \hspace{0.5in}
  7637. \begin{minipage}{0.2\textwidth}
  7638. \begin{lstlisting}
  7639. x = 777;
  7640. goto block_6;
  7641. \end{lstlisting}
  7642. \end{minipage}
  7643. \end{center}
  7644. Finally, we delegate to \code{explicate\_pred}, passing the condition
  7645. \code{(eq? y 0)} and the above code for the branches.
  7646. \subsection{Create Block}
  7647. We recommend implementing the \code{create\_block} auxiliary function
  7648. as follows, using a global variable \code{basic-blocks} to store a
  7649. dictionary that maps labels to $\Tail$ expressions. The main idea is
  7650. that \code{create\_block} generates a new label and then associates
  7651. the given \code{tail} with the new label in the \code{basic-blocks}
  7652. dictionary. The result of \code{create\_block} is a \code{Goto} to the
  7653. new label. However, if the given \code{tail} is already a \code{Goto},
  7654. then there is no need to generate a new label and entry in
  7655. \code{basic-blocks}; we can simply return that \code{Goto}.
  7656. %
  7657. \begin{lstlisting}
  7658. (define (create_block tail)
  7659. (match tail
  7660. [(Goto label) (Goto label)]
  7661. [else
  7662. (let ([label (gensym 'block)])
  7663. (set! basic-blocks (cons (cons label tail) basic-blocks))
  7664. (Goto label))]))
  7665. \end{lstlisting}
  7666. \fi}
  7667. {\if\edition\racketEd
  7668. \subsection{Explicate Predicate}
  7669. \begin{figure}[tbp]
  7670. \begin{lstlisting}
  7671. (define (explicate_pred cnd thn els)
  7672. (match cnd
  7673. [(Var x) ___]
  7674. [(Let x rhs body) ___]
  7675. [(Prim 'not (list e)) ___]
  7676. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7677. (IfStmt (Prim op es) (create_block thn)
  7678. (create_block els))]
  7679. [(Bool b) (if b thn els)]
  7680. [(If cnd^ thn^ els^) ___]
  7681. [else (error "explicate_pred unhandled case" cnd)]))
  7682. \end{lstlisting}
  7683. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7684. \label{fig:explicate-pred}
  7685. \end{figure}
  7686. \fi}
  7687. \racket{The skeleton for the \code{explicate\_pred} function is given
  7688. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7689. 1) \code{cnd}, the condition expression of the \code{if},
  7690. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7691. and 3) \code{els}, the code generated by
  7692. explicate for the ``else'' branch. The \code{explicate\_pred}
  7693. function should match on \code{cnd} with a case for
  7694. every kind of expression that can have type \code{Boolean}.}
  7695. %
  7696. \python{The \code{explicate\_pred} function has four parameters: 1)
  7697. the condition expression, 2) the generated statements for the
  7698. ``then'' branch, 3) the generated statements for the ``else''
  7699. branch, and 4) the dictionary of basic blocks. The
  7700. \code{explicate\_pred} function returns a list of \LangCIf{}
  7701. statements and it may add to the dictionary of basic blocks.}
  7702. Consider the case for comparison operators. We translate the
  7703. comparison to an \code{if} statement whose branches are \code{goto}
  7704. statements created by applying \code{create\_block} to the code
  7705. generated for the \code{thn} and \code{els} branches. Let us
  7706. illustrate this translation by returning to the program with an
  7707. \code{if} expression in tail position, shown again below. We invoke
  7708. \code{explicate\_pred} on its condition \racket{\code{(eq? x 0)}}
  7709. \python{\code{x == 0}}.
  7710. %
  7711. {\if\edition\racketEd
  7712. \begin{lstlisting}
  7713. (let ([x (read)])
  7714. (if (eq? x 0) 42 777))
  7715. \end{lstlisting}
  7716. \fi}
  7717. %
  7718. {\if\edition\pythonEd
  7719. \begin{lstlisting}
  7720. x = input_int()
  7721. 42 if x == 0 else 777
  7722. \end{lstlisting}
  7723. \fi}
  7724. %
  7725. \noindent The two branches \code{42} and \code{777} were already
  7726. compiled to \code{return} statements, from which we now create the
  7727. following blocks.
  7728. %
  7729. \begin{center}
  7730. \begin{minipage}{\textwidth}
  7731. \begin{lstlisting}
  7732. block_1:
  7733. return 42;
  7734. block_2:
  7735. return 777;
  7736. \end{lstlisting}
  7737. \end{minipage}
  7738. \end{center}
  7739. %
  7740. After that, \code{explicate\_pred} compiles the comparison
  7741. \racket{\code{(eq? x 0)}}
  7742. \python{\code{x == 0}}
  7743. to the following \code{if} statement.
  7744. %
  7745. {\if\edition\racketEd
  7746. \begin{center}
  7747. \begin{minipage}{\textwidth}
  7748. \begin{lstlisting}
  7749. if (eq? x 0)
  7750. goto block_1;
  7751. else
  7752. goto block_2;
  7753. \end{lstlisting}
  7754. \end{minipage}
  7755. \end{center}
  7756. \fi}
  7757. {\if\edition\pythonEd
  7758. \begin{center}
  7759. \begin{minipage}{\textwidth}
  7760. \begin{lstlisting}
  7761. if x == 0:
  7762. goto block_1;
  7763. else
  7764. goto block_2;
  7765. \end{lstlisting}
  7766. \end{minipage}
  7767. \end{center}
  7768. \fi}
  7769. Next consider the case for Boolean constants. We perform a kind of
  7770. partial evaluation\index{subject}{partial evaluation} and output
  7771. either the \code{thn} or \code{els} branch depending on whether the
  7772. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7773. following program.
  7774. {\if\edition\racketEd
  7775. \begin{lstlisting}
  7776. (if #t 42 777)
  7777. \end{lstlisting}
  7778. \fi}
  7779. {\if\edition\pythonEd
  7780. \begin{lstlisting}
  7781. 42 if True else 777
  7782. \end{lstlisting}
  7783. \fi}
  7784. %
  7785. \noindent Again, the two branches \code{42} and \code{777} were
  7786. compiled to \code{return} statements, so \code{explicate\_pred}
  7787. compiles the constant \racket{\code{\#t}} \python{\code{True}} to the
  7788. code for the ``then'' branch.
  7789. \begin{lstlisting}
  7790. return 42;
  7791. \end{lstlisting}
  7792. This case demonstrates that we sometimes discard the \code{thn} or
  7793. \code{els} blocks that are input to \code{explicate\_pred}.
  7794. The case for \key{if} expressions in \code{explicate\_pred} is
  7795. particularly illuminating because it deals with the challenges we
  7796. discussed above regarding nested \key{if} expressions
  7797. (Figure~\ref{fig:explicate-control-s1-38}). The
  7798. \racket{\lstinline{thn^}}\python{\code{body}} and
  7799. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7800. \key{if} inherit their context from the current one, that is,
  7801. predicate context. So you should recursively apply
  7802. \code{explicate\_pred} to the
  7803. \racket{\lstinline{thn^}}\python{\code{body}} and
  7804. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7805. those recursive calls, pass \code{thn} and \code{els} as the extra
  7806. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7807. inside each recursive call. As discussed above, to avoid duplicating
  7808. code, we need to add them to the dictionary of basic blocks so that we
  7809. can instead refer to them by name and execute them with a \key{goto}.
  7810. {\if\edition\pythonEd
  7811. %
  7812. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7813. three parameters: 1) the statement to be compiled, 2) the code for its
  7814. continuation, and 3) the dictionary of basic blocks. The
  7815. \code{explicate\_stmt} returns a list of statements and it may add to
  7816. the dictionary of basic blocks. The cases for assignment and an
  7817. expression-statement are given in full in the skeleton code: they
  7818. simply dispatch to \code{explicate\_assign} and
  7819. \code{explicate\_effect}, respectively. The case for \code{if}
  7820. statements is not given, and is similar to the case for \code{if}
  7821. expressions.
  7822. The \code{explicate\_control} function itself is given in
  7823. Figure~\ref{fig:explicate-control-Lif}. It applies
  7824. \code{explicate\_stmt} to each statement in the program, from back to
  7825. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7826. used as the continuation parameter in the next call to
  7827. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7828. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7829. the dictionary of basic blocks, labeling it as the ``start'' block.
  7830. %
  7831. \fi}
  7832. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7833. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7834. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7835. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7836. %% results from the two recursive calls. We complete the case for
  7837. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7838. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7839. %% the result $B_5$.
  7840. %% \[
  7841. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7842. %% \quad\Rightarrow\quad
  7843. %% B_5
  7844. %% \]
  7845. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7846. %% inherit the current context, so they are in tail position. Thus, the
  7847. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7848. %% \code{explicate\_tail}.
  7849. %% %
  7850. %% We need to pass $B_0$ as the accumulator argument for both of these
  7851. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7852. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7853. %% to the control-flow graph and obtain a promised goto $G_0$.
  7854. %% %
  7855. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7856. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7857. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7858. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7859. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7860. %% \[
  7861. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7862. %% \]
  7863. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7864. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7865. %% should not be confused with the labels for the blocks that appear in
  7866. %% the generated code. We initially construct unlabeled blocks; we only
  7867. %% attach labels to blocks when we add them to the control-flow graph, as
  7868. %% we see in the next case.
  7869. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7870. %% function. The context of the \key{if} is an assignment to some
  7871. %% variable $x$ and then the control continues to some promised block
  7872. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7873. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7874. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7875. %% branches of the \key{if} inherit the current context, so they are in
  7876. %% assignment positions. Let $B_2$ be the result of applying
  7877. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7878. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7879. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7880. %% the result of applying \code{explicate\_pred} to the predicate
  7881. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7882. %% translates to the promise $B_4$.
  7883. %% \[
  7884. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7885. %% \]
  7886. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7887. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7888. \code{remove\_complex\_operands} pass and then the
  7889. \code{explicate\_control} pass on the example program. We walk through
  7890. the output program.
  7891. %
  7892. Following the order of evaluation in the output of
  7893. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7894. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7895. in the predicate of the inner \key{if}. In the output of
  7896. \code{explicate\_control}, in the
  7897. block labeled \code{start}, are two assignment statements followed by a
  7898. \code{if} statement that branches to \code{block\_4} or
  7899. \code{block\_5}. The blocks associated with those labels contain the
  7900. translations of the code
  7901. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7902. and
  7903. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7904. respectively. In particular, we start \code{block\_4} with the
  7905. comparison
  7906. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7907. and then branch to \code{block\_2} or \code{block\_3},
  7908. which correspond to the two branches of the outer \key{if}, i.e.,
  7909. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7910. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7911. %
  7912. The story for \code{block\_5} is similar to that of \code{block\_4}.
  7913. %
  7914. \python{The \code{block\_1} corresponds to the \code{print} statement
  7915. at the end of the program.}
  7916. {\if\edition\racketEd
  7917. \subsection{Interactions between Explicate and Shrink}
  7918. The way in which the \code{shrink} pass transforms logical operations
  7919. such as \code{and} and \code{or} can impact the quality of code
  7920. generated by \code{explicate\_control}. For example, consider the
  7921. following program.
  7922. % cond_test_21.rkt, and_eq_input.py
  7923. \begin{lstlisting}
  7924. (if (and (eq? (read) 0) (eq? (read) 1))
  7925. 0
  7926. 42)
  7927. \end{lstlisting}
  7928. The \code{and} operation should transform into something that the
  7929. \code{explicate\_pred} function can still analyze and descend through to
  7930. reach the underlying \code{eq?} conditions. Ideally, your
  7931. \code{explicate\_control} pass should generate code similar to the
  7932. following for the above program.
  7933. \begin{center}
  7934. \begin{lstlisting}
  7935. start:
  7936. tmp1 = (read);
  7937. if (eq? tmp1 0) goto block40;
  7938. else goto block39;
  7939. block40:
  7940. tmp2 = (read);
  7941. if (eq? tmp2 1) goto block38;
  7942. else goto block39;
  7943. block38:
  7944. return 0;
  7945. block39:
  7946. return 42;
  7947. \end{lstlisting}
  7948. \end{center}
  7949. \fi}
  7950. \begin{exercise}\normalfont\normalsize
  7951. \racket{
  7952. Implement the pass \code{explicate\_control} by adding the cases for
  7953. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7954. \code{explicate\_assign} functions. Implement the auxiliary function
  7955. \code{explicate\_pred} for predicate contexts.}
  7956. \python{Implement \code{explicate\_control} pass with its
  7957. four auxiliary functions.}
  7958. %
  7959. Create test cases that exercise all of the new cases in the code for
  7960. this pass.
  7961. %
  7962. {\if\edition\racketEd
  7963. Add the following entry to the list of \code{passes} in
  7964. \code{run-tests.rkt} and then run this script to test your compiler.
  7965. \begin{lstlisting}
  7966. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7967. \end{lstlisting}
  7968. \fi}
  7969. \end{exercise}
  7970. \clearpage
  7971. \section{Select Instructions}
  7972. \label{sec:select-Lif}
  7973. \index{subject}{instruction selection}
  7974. The \code{select\_instructions} pass translates \LangCIf{} to
  7975. \LangXIfVar{}.
  7976. %
  7977. \racket{Recall that we implement this pass using three auxiliary
  7978. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7979. $\Tail$ in \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  7980. %
  7981. \racket{For $\Atm$, we have new cases for the Booleans.}
  7982. %
  7983. \python{We begin with the Boolean constants.}
  7984. We take the usual approach of encoding them as integers.
  7985. \[
  7986. \TRUE{} \quad\Rightarrow\quad \key{1}
  7987. \qquad\qquad
  7988. \FALSE{} \quad\Rightarrow\quad \key{0}
  7989. \]
  7990. For translating statements, we discuss some of the cases. The
  7991. \code{not} operation can be implemented in terms of \code{xorq} as we
  7992. discussed at the beginning of this section. Given an assignment, if
  7993. the left-hand side variable is the same as the argument of \code{not},
  7994. then just the \code{xorq} instruction suffices.
  7995. \[
  7996. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7997. \quad\Rightarrow\quad
  7998. \key{xorq}~\key{\$}1\key{,}~\Var
  7999. \]
  8000. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  8001. semantics of x86. In the following translation, let $\Arg$ be the
  8002. result of translating $\Atm$ to x86.
  8003. \[
  8004. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  8005. \quad\Rightarrow\quad
  8006. \begin{array}{l}
  8007. \key{movq}~\Arg\key{,}~\Var\\
  8008. \key{xorq}~\key{\$}1\key{,}~\Var
  8009. \end{array}
  8010. \]
  8011. Next consider the cases for equality comparisons. Translating this
  8012. operation to x86 is slightly involved due to the unusual nature of the
  8013. \key{cmpq} instruction that we discussed in Section~\ref{sec:x86-if}.
  8014. We recommend translating an assignment with an equality on the
  8015. right-hand side into a sequence of three instructions. \\
  8016. \begin{tabular}{lll}
  8017. \begin{minipage}{0.4\textwidth}
  8018. \begin{lstlisting}
  8019. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  8020. \end{lstlisting}
  8021. \end{minipage}
  8022. &
  8023. $\Rightarrow$
  8024. &
  8025. \begin{minipage}{0.4\textwidth}
  8026. \begin{lstlisting}
  8027. cmpq |$\Arg_2$|, |$\Arg_1$|
  8028. sete %al
  8029. movzbq %al, |$\Var$|
  8030. \end{lstlisting}
  8031. \end{minipage}
  8032. \end{tabular} \\
  8033. The translations for the other comparison operators are similar to the
  8034. above but use different condition codes for the \code{set} instruction.
  8035. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  8036. \key{goto} and \key{if} statements. Both are straightforward to
  8037. translate to x86.}
  8038. %
  8039. A \key{goto} statement becomes a jump instruction.
  8040. \[
  8041. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8042. \]
  8043. %
  8044. An \key{if} statement becomes a compare instruction followed by a
  8045. conditional jump (for the ``then'' branch) and the fall-through is to
  8046. a regular jump (for the ``else'' branch).\\
  8047. \begin{tabular}{lll}
  8048. \begin{minipage}{0.4\textwidth}
  8049. \begin{lstlisting}
  8050. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8051. goto |$\ell_1$||$\racket{\key{;}}$|
  8052. else|$\python{\key{:}}$|
  8053. goto |$\ell_2$||$\racket{\key{;}}$|
  8054. \end{lstlisting}
  8055. \end{minipage}
  8056. &
  8057. $\Rightarrow$
  8058. &
  8059. \begin{minipage}{0.4\textwidth}
  8060. \begin{lstlisting}
  8061. cmpq |$\Arg_2$|, |$\Arg_1$|
  8062. je |$\ell_1$|
  8063. jmp |$\ell_2$|
  8064. \end{lstlisting}
  8065. \end{minipage}
  8066. \end{tabular} \\
  8067. Again, the translations for the other comparison operators are similar to the
  8068. above but use different condition codes for the conditional jump instruction.
  8069. \python{Regarding the \key{return} statement, we recommend treating it
  8070. as an assignment to the \key{rax} register followed by a jump to the
  8071. conclusion of the \code{main} function.}
  8072. \begin{exercise}\normalfont\normalsize
  8073. Expand your \code{select\_instructions} pass to handle the new
  8074. features of the \LangCIf{} language.
  8075. %
  8076. {\if\edition\racketEd
  8077. Add the following entry to the list of \code{passes} in
  8078. \code{run-tests.rkt}
  8079. \begin{lstlisting}
  8080. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8081. \end{lstlisting}
  8082. \fi}
  8083. %
  8084. Run the script to test your compiler on all the test programs.
  8085. \end{exercise}
  8086. \section{Register Allocation}
  8087. \label{sec:register-allocation-Lif}
  8088. \index{subject}{register allocation}
  8089. The changes required for compiling \LangIf{} affect liveness analysis,
  8090. building the interference graph, and assigning homes, but the graph
  8091. coloring algorithm itself does not change.
  8092. \subsection{Liveness Analysis}
  8093. \label{sec:liveness-analysis-Lif}
  8094. \index{subject}{liveness analysis}
  8095. Recall that for \LangVar{} we implemented liveness analysis for a
  8096. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8097. the addition of \key{if} expressions to \LangIf{},
  8098. \code{explicate\_control} produces many basic blocks.
  8099. %% We recommend that you create a new auxiliary function named
  8100. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8101. %% control-flow graph.
  8102. The first question is: in what order should we process the basic blocks?
  8103. Recall that to perform liveness analysis on a basic block we need to
  8104. know the live-after set for the last instruction in the block. If a
  8105. basic block has no successors (i.e. contains no jumps to other
  8106. blocks), then it has an empty live-after set and we can immediately
  8107. apply liveness analysis to it. If a basic block has some successors,
  8108. then we need to complete liveness analysis on those blocks
  8109. first. These ordering constraints are the reverse of a
  8110. \emph{topological order}\index{subject}{topological order} on a graph
  8111. representation of the program. In particular, the \emph{control flow
  8112. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8113. of a program has a node for each basic block and an edge for each jump
  8114. from one block to another. It is straightforward to generate a CFG
  8115. from the dictionary of basic blocks. One then transposes the CFG and
  8116. applies the topological sort algorithm.
  8117. %
  8118. %
  8119. \racket{We recommend using the \code{tsort} and \code{transpose}
  8120. functions of the Racket \code{graph} package to accomplish this.}
  8121. %
  8122. \python{We provide implementations of \code{topological\_sort} and
  8123. \code{transpose} in the file \code{graph.py} of the support code.}
  8124. %
  8125. As an aside, a topological ordering is only guaranteed to exist if the
  8126. graph does not contain any cycles. This is the case for the
  8127. control-flow graphs that we generate from \LangIf{} programs.
  8128. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8129. and learn how to handle cycles in the control-flow graph.
  8130. \racket{You'll need to construct a directed graph to represent the
  8131. control-flow graph. Do not use the \code{directed-graph} of the
  8132. \code{graph} package because that only allows at most one edge
  8133. between each pair of vertices, but a control-flow graph may have
  8134. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8135. file in the support code implements a graph representation that
  8136. allows multiple edges between a pair of vertices.}
  8137. {\if\edition\racketEd
  8138. The next question is how to analyze jump instructions. Recall that in
  8139. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8140. \code{label->live} that maps each label to the set of live locations
  8141. at the beginning of its block. We use \code{label->live} to determine
  8142. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8143. that we have many basic blocks, \code{label->live} needs to be updated
  8144. as we process the blocks. In particular, after performing liveness
  8145. analysis on a block, we take the live-before set of its first
  8146. instruction and associate that with the block's label in the
  8147. \code{label->live} alist.
  8148. \fi}
  8149. %
  8150. {\if\edition\pythonEd
  8151. %
  8152. The next question is how to analyze jump instructions. The locations
  8153. that are live before a \code{jmp} should be the locations in
  8154. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8155. maintaining a dictionary named \code{live\_before\_block} that maps each
  8156. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8157. block. After performing liveness analysis on each block, we take the
  8158. live-before set of its first instruction and associate that with the
  8159. block's label in the \code{live\_before\_block} dictionary.
  8160. %
  8161. \fi}
  8162. In \LangXIfVar{} we also have the conditional jump
  8163. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8164. this instruction is particularly interesting because, during
  8165. compilation, we do not know which way a conditional jump will go. So
  8166. we do not know whether to use the live-before set for the block
  8167. associated with the $\itm{label}$ or the live-before set for the
  8168. following instruction. However, there is no harm to the correctness
  8169. of the generated code if we classify more locations as live than the
  8170. ones that are truly live during one particular execution of the
  8171. instruction. Thus, we can take the union of the live-before sets from
  8172. the following instruction and from the mapping for $\itm{label}$ in
  8173. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8174. The auxiliary functions for computing the variables in an
  8175. instruction's argument and for computing the variables read-from ($R$)
  8176. or written-to ($W$) by an instruction need to be updated to handle the
  8177. new kinds of arguments and instructions in \LangXIfVar{}.
  8178. \begin{exercise}\normalfont\normalsize
  8179. {\if\edition\racketEd
  8180. %
  8181. Update the \code{uncover\_live} pass to apply liveness analysis to
  8182. every basic block in the program.
  8183. %
  8184. Add the following entry to the list of \code{passes} in the
  8185. \code{run-tests.rkt} script.
  8186. \begin{lstlisting}
  8187. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8188. \end{lstlisting}
  8189. \fi}
  8190. {\if\edition\pythonEd
  8191. %
  8192. Update the \code{uncover\_live} function to perform liveness analysis,
  8193. in reverse topological order, on all of the basic blocks in the
  8194. program.
  8195. %
  8196. \fi}
  8197. % Check that the live-after sets that you generate for
  8198. % example X matches the following... -Jeremy
  8199. \end{exercise}
  8200. \subsection{Build the Interference Graph}
  8201. \label{sec:build-interference-Lif}
  8202. Many of the new instructions in \LangXIfVar{} can be handled in the
  8203. same way as the instructions in \LangXVar{}.
  8204. % Thus, if your code was
  8205. % already quite general, it will not need to be changed to handle the
  8206. % new instructions. If your code is not general enough, we recommend that
  8207. % you change your code to be more general. For example, you can factor
  8208. % out the computing of the the read and write sets for each kind of
  8209. % instruction into auxiliary functions.
  8210. %
  8211. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8212. similar to the \key{movq} instruction. See rule number 1 in
  8213. Section~\ref{sec:build-interference}.
  8214. \begin{exercise}\normalfont\normalsize
  8215. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8216. {\if\edition\racketEd
  8217. Add the following entries to the list of \code{passes} in the
  8218. \code{run-tests.rkt} script.
  8219. \begin{lstlisting}
  8220. (list "build_interference" build_interference interp-pseudo-x86-1)
  8221. (list "allocate_registers" allocate_registers interp-pseudo-x86-1)
  8222. \end{lstlisting}
  8223. \fi}
  8224. % Check that the interference graph that you generate for
  8225. % example X matches the following graph G... -Jeremy
  8226. \end{exercise}
  8227. \section{Patch Instructions}
  8228. The new instructions \key{cmpq} and \key{movzbq} have some special
  8229. restrictions that need to be handled in the \code{patch\_instructions}
  8230. pass.
  8231. %
  8232. The second argument of the \key{cmpq} instruction must not be an
  8233. immediate value (such as an integer). So if you are comparing two
  8234. immediates, we recommend inserting a \key{movq} instruction to put the
  8235. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8236. one memory reference.
  8237. %
  8238. The second argument of the \key{movzbq} must be a register.
  8239. \begin{exercise}\normalfont\normalsize
  8240. %
  8241. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8242. %
  8243. {\if\edition\racketEd
  8244. Add the following entry to the list of \code{passes} in
  8245. \code{run-tests.rkt} and then run this script to test your compiler.
  8246. \begin{lstlisting}
  8247. (list "patch_instructions" patch_instructions interp-x86-1)
  8248. \end{lstlisting}
  8249. \fi}
  8250. \end{exercise}
  8251. {\if\edition\pythonEd
  8252. \section{Prelude and Conclusion}
  8253. \label{sec:prelude-conclusion-cond}
  8254. The generation of the \code{main} function with its prelude and
  8255. conclusion must change to accommodate how the program now consists of
  8256. one or more basic blocks. After the prelude in \code{main}, jump to
  8257. the \code{start} block. Place the conclusion in a basic block labeled
  8258. with \code{conclusion}.
  8259. \fi}
  8260. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8261. \LangIf{} translated to x86, showing the results of
  8262. \code{explicate\_control}, \code{select\_instructions}, and the final
  8263. x86 assembly.
  8264. \begin{figure}[tbp]
  8265. {\if\edition\racketEd
  8266. \begin{tabular}{lll}
  8267. \begin{minipage}{0.4\textwidth}
  8268. % cond_test_20.rkt, eq_input.py
  8269. \begin{lstlisting}
  8270. (if (eq? (read) 1) 42 0)
  8271. \end{lstlisting}
  8272. $\Downarrow$
  8273. \begin{lstlisting}
  8274. start:
  8275. tmp7951 = (read);
  8276. if (eq? tmp7951 1)
  8277. goto block7952;
  8278. else
  8279. goto block7953;
  8280. block7952:
  8281. return 42;
  8282. block7953:
  8283. return 0;
  8284. \end{lstlisting}
  8285. $\Downarrow$
  8286. \begin{lstlisting}
  8287. start:
  8288. callq read_int
  8289. movq %rax, tmp7951
  8290. cmpq $1, tmp7951
  8291. je block7952
  8292. jmp block7953
  8293. block7953:
  8294. movq $0, %rax
  8295. jmp conclusion
  8296. block7952:
  8297. movq $42, %rax
  8298. jmp conclusion
  8299. \end{lstlisting}
  8300. \end{minipage}
  8301. &
  8302. $\Rightarrow\qquad$
  8303. \begin{minipage}{0.4\textwidth}
  8304. \begin{lstlisting}
  8305. start:
  8306. callq read_int
  8307. movq %rax, %rcx
  8308. cmpq $1, %rcx
  8309. je block7952
  8310. jmp block7953
  8311. block7953:
  8312. movq $0, %rax
  8313. jmp conclusion
  8314. block7952:
  8315. movq $42, %rax
  8316. jmp conclusion
  8317. .globl main
  8318. main:
  8319. pushq %rbp
  8320. movq %rsp, %rbp
  8321. pushq %r13
  8322. pushq %r12
  8323. pushq %rbx
  8324. pushq %r14
  8325. subq $0, %rsp
  8326. jmp start
  8327. conclusion:
  8328. addq $0, %rsp
  8329. popq %r14
  8330. popq %rbx
  8331. popq %r12
  8332. popq %r13
  8333. popq %rbp
  8334. retq
  8335. \end{lstlisting}
  8336. \end{minipage}
  8337. \end{tabular}
  8338. \fi}
  8339. {\if\edition\pythonEd
  8340. \begin{tabular}{lll}
  8341. \begin{minipage}{0.4\textwidth}
  8342. % cond_test_20.rkt, eq_input.py
  8343. \begin{lstlisting}
  8344. print(42 if input_int() == 1 else 0)
  8345. \end{lstlisting}
  8346. $\Downarrow$
  8347. \begin{lstlisting}
  8348. start:
  8349. tmp_0 = input_int()
  8350. if tmp_0 == 1:
  8351. goto block_3
  8352. else:
  8353. goto block_4
  8354. block_3:
  8355. tmp_1 = 42
  8356. goto block_2
  8357. block_4:
  8358. tmp_1 = 0
  8359. goto block_2
  8360. block_2:
  8361. print(tmp_1)
  8362. return 0
  8363. \end{lstlisting}
  8364. $\Downarrow$
  8365. \begin{lstlisting}
  8366. start:
  8367. callq read_int
  8368. movq %rax, tmp_0
  8369. cmpq 1, tmp_0
  8370. je block_3
  8371. jmp block_4
  8372. block_3:
  8373. movq 42, tmp_1
  8374. jmp block_2
  8375. block_4:
  8376. movq 0, tmp_1
  8377. jmp block_2
  8378. block_2:
  8379. movq tmp_1, %rdi
  8380. callq print_int
  8381. movq 0, %rax
  8382. jmp conclusion
  8383. \end{lstlisting}
  8384. \end{minipage}
  8385. &
  8386. $\Rightarrow\qquad$
  8387. \begin{minipage}{0.4\textwidth}
  8388. \begin{lstlisting}
  8389. .globl main
  8390. main:
  8391. pushq %rbp
  8392. movq %rsp, %rbp
  8393. subq $0, %rsp
  8394. jmp start
  8395. start:
  8396. callq read_int
  8397. movq %rax, %rcx
  8398. cmpq $1, %rcx
  8399. je block_3
  8400. jmp block_4
  8401. block_3:
  8402. movq $42, %rcx
  8403. jmp block_2
  8404. block_4:
  8405. movq $0, %rcx
  8406. jmp block_2
  8407. block_2:
  8408. movq %rcx, %rdi
  8409. callq print_int
  8410. movq $0, %rax
  8411. jmp conclusion
  8412. conclusion:
  8413. addq $0, %rsp
  8414. popq %rbp
  8415. retq
  8416. \end{lstlisting}
  8417. \end{minipage}
  8418. \end{tabular}
  8419. \fi}
  8420. \caption{Example compilation of an \key{if} expression to x86, showing
  8421. the results of \code{explicate\_control},
  8422. \code{select\_instructions}, and the final x86 assembly code. }
  8423. \label{fig:if-example-x86}
  8424. \end{figure}
  8425. \begin{figure}[tbp]
  8426. {\if\edition\racketEd
  8427. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8428. \node (Lif) at (0,2) {\large \LangIf{}};
  8429. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8430. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8431. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8432. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8433. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8434. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8435. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8436. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8437. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8438. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8439. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8440. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8441. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8442. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8443. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8444. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8445. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8446. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8447. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8448. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8449. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8450. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8451. \end{tikzpicture}
  8452. \fi}
  8453. {\if\edition\pythonEd
  8454. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8455. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8456. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8457. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8458. \node (C-1) at (3,0) {\large \LangCIf{}};
  8459. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8460. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8461. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8462. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8463. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8464. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8465. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8466. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8467. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8468. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8469. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8470. \end{tikzpicture}
  8471. \fi}
  8472. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8473. \label{fig:Lif-passes}
  8474. \end{figure}
  8475. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8476. compilation of \LangIf{}.
  8477. \section{Challenge: Optimize Blocks and Remove Jumps}
  8478. \label{sec:opt-jumps}
  8479. We discuss two optional challenges that involve optimizing the
  8480. control-flow of the program.
  8481. \subsection{Optimize Blocks}
  8482. The algorithm for \code{explicate\_control} that we discussed in
  8483. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8484. blocks. It creates a basic block whenever a continuation \emph{might}
  8485. get used more than once (e.g., whenever the \code{cont} parameter is
  8486. passed into two or more recursive calls). However, some continuation
  8487. arguments may not be used at all. For example, consider the case for
  8488. the constant \TRUE{} in \code{explicate\_pred}, where we discard the
  8489. \code{els} continuation.
  8490. %
  8491. {\if\edition\racketEd
  8492. The following example program falls into this
  8493. case, and it creates two unused blocks.
  8494. \begin{center}
  8495. \begin{tabular}{lll}
  8496. \begin{minipage}{0.4\textwidth}
  8497. % cond_test_82.rkt
  8498. \begin{lstlisting}
  8499. (let ([y (if #t
  8500. (read)
  8501. (if (eq? (read) 0)
  8502. 777
  8503. (let ([x (read)])
  8504. (+ 1 x))))])
  8505. (+ y 2))
  8506. \end{lstlisting}
  8507. \end{minipage}
  8508. &
  8509. $\Rightarrow$
  8510. &
  8511. \begin{minipage}{0.55\textwidth}
  8512. \begin{lstlisting}
  8513. start:
  8514. y = (read);
  8515. goto block_5;
  8516. block_5:
  8517. return (+ y 2);
  8518. block_6:
  8519. y = 777;
  8520. goto block_5;
  8521. block_7:
  8522. x = (read);
  8523. y = (+ 1 x2);
  8524. goto block_5;
  8525. \end{lstlisting}
  8526. \end{minipage}
  8527. \end{tabular}
  8528. \end{center}
  8529. \fi}
  8530. So the question is how can we decide whether to create a basic block?
  8531. \emph{Lazy evaluation}\index{subject}{lazy
  8532. evaluation}~\citep{Friedman:1976aa} can solve this conundrum by
  8533. delaying the creation of a basic block until the point in time where
  8534. we know it will be used.
  8535. %
  8536. {\if\edition\racketEd
  8537. %
  8538. Racket provides support for
  8539. lazy evaluation with the
  8540. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8541. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8542. \index{subject}{delay} creates a
  8543. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8544. expressions is postponed. When \key{(force}
  8545. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8546. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8547. result of $e_n$ is cached in the promise and returned. If \code{force}
  8548. is applied again to the same promise, then the cached result is
  8549. returned. If \code{force} is applied to an argument that is not a
  8550. promise, \code{force} simply returns the argument.
  8551. %
  8552. \fi}
  8553. %
  8554. {\if\edition\pythonEd
  8555. %
  8556. While Python does not provide direct support for lazy evaluation, it
  8557. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8558. by wrapping it inside a function with no parameters. We can
  8559. \emph{force} its evaluation by calling the function. However, in some
  8560. cases of \code{explicate\_pred}, etc., we will return a list of
  8561. statements and in other cases we will return a function that computes
  8562. a list of statements. We use the term \emph{promise} to refer to a
  8563. value that may be delayed. To uniformly deal with
  8564. promises, we define the following \code{force} function that checks
  8565. whether its input is delayed (i.e., whether it is a function) and then
  8566. either 1) calls the function, or 2) returns the input.
  8567. \begin{lstlisting}
  8568. def force(promise):
  8569. if isinstance(promise, types.FunctionType):
  8570. return promise()
  8571. else:
  8572. return promise
  8573. \end{lstlisting}
  8574. %
  8575. \fi}
  8576. We use promises for the input and output of the functions
  8577. \code{explicate\_pred}, \code{explicate\_assign},
  8578. %
  8579. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8580. %
  8581. So instead of taking and returning \racket{$\Tail$
  8582. expressions}\python{lists of statements}, they take and return
  8583. promises. Furthermore, when we come to a situation in which a
  8584. continuation might be used more than once, as in the case for
  8585. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8586. that creates a basic block for each continuation (if there is not
  8587. already one) and then returns a \code{goto} statement to that basic
  8588. block. When we come to a situation where we have a promise but need an
  8589. actual piece of code, e.g. to create a larger piece of code with a
  8590. constructor such as \code{Seq}, then insert a call to \code{force}.
  8591. %
  8592. {\if\edition\racketEd
  8593. %
  8594. Also we must modify the \code{create\_block} function to begin with
  8595. \code{delay} to create a promise. When forced, this promise forces the
  8596. original promise. If that returns a \code{Goto} (because the block was
  8597. already added to \code{basic-blocks}), then we return the
  8598. \code{Goto}. Otherwise we add the block to \code{basic-blocks} and
  8599. return a \code{Goto} to the new label.
  8600. \begin{center}
  8601. \begin{minipage}{\textwidth}
  8602. \begin{lstlisting}
  8603. (define (create_block tail)
  8604. (delay
  8605. (define t (force tail))
  8606. (match t
  8607. [(Goto label) (Goto label)]
  8608. [else
  8609. (let ([label (gensym 'block)])
  8610. (set! basic-blocks (cons (cons label tail) basic-blocks))
  8611. (Goto label))]))
  8612. \end{lstlisting}
  8613. \end{minipage}
  8614. \end{center}
  8615. \fi}
  8616. {\if\edition\pythonEd
  8617. %
  8618. Here is the new version of the \code{create\_block} auxiliary function
  8619. that works on promises and that checks whether the block consists of a
  8620. solitary \code{goto} statement.\\
  8621. \begin{minipage}{\textwidth}
  8622. \begin{lstlisting}
  8623. def create_block(promise, basic_blocks):
  8624. stmts = force(promise)
  8625. match stmts:
  8626. case [Goto(l)]:
  8627. return Goto(l)
  8628. case _:
  8629. label = label_name(generate_name('block'))
  8630. basic_blocks[label] = stmts
  8631. return Goto(label)
  8632. \end{lstlisting}
  8633. \end{minipage}
  8634. \fi}
  8635. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8636. improved \code{explicate\_control} on the above example. As you can
  8637. see, the number of basic blocks has been reduced from 4 blocks (see
  8638. Figure~\ref{fig:explicate-control-s1-38}) down to 2 blocks.
  8639. \begin{figure}[tbp]
  8640. {\if\edition\racketEd
  8641. \begin{tabular}{lll}
  8642. \begin{minipage}{0.4\textwidth}
  8643. % cond_test_82.rkt
  8644. \begin{lstlisting}
  8645. (let ([y (if #t
  8646. (read)
  8647. (if (eq? (read) 0)
  8648. 777
  8649. (let ([x (read)])
  8650. (+ 1 x))))])
  8651. (+ y 2))
  8652. \end{lstlisting}
  8653. \end{minipage}
  8654. &
  8655. $\Rightarrow$
  8656. &
  8657. \begin{minipage}{0.55\textwidth}
  8658. \begin{lstlisting}
  8659. start:
  8660. y = (read);
  8661. goto block_5;
  8662. block_5:
  8663. return (+ y 2);
  8664. \end{lstlisting}
  8665. \end{minipage}
  8666. \end{tabular}
  8667. \fi}
  8668. {\if\edition\pythonEd
  8669. \begin{tabular}{lll}
  8670. \begin{minipage}{0.4\textwidth}
  8671. % cond_test_41.rkt
  8672. \begin{lstlisting}
  8673. x = input_int()
  8674. y = input_int()
  8675. print(y + 2 \
  8676. if (x == 0 \
  8677. if x < 1 \
  8678. else x == 2) \
  8679. else y + 10)
  8680. \end{lstlisting}
  8681. \end{minipage}
  8682. &
  8683. $\Rightarrow$
  8684. &
  8685. \begin{minipage}{0.55\textwidth}
  8686. \begin{lstlisting}
  8687. start:
  8688. x = input_int()
  8689. y = input_int()
  8690. if x < 1:
  8691. goto block_4
  8692. else:
  8693. goto block_5
  8694. block_4:
  8695. if x == 0:
  8696. goto block_2
  8697. else:
  8698. goto block_3
  8699. block_5:
  8700. if x == 2:
  8701. goto block_2
  8702. else:
  8703. goto block_3
  8704. block_2:
  8705. tmp_0 = y + 2
  8706. goto block_1
  8707. block_3:
  8708. tmp_0 = y + 10
  8709. goto block_1
  8710. block_1:
  8711. print(tmp_0)
  8712. return 0
  8713. \end{lstlisting}
  8714. \end{minipage}
  8715. \end{tabular}
  8716. \fi}
  8717. \caption{Translation from \LangIf{} to \LangCIf{}
  8718. via the improved \code{explicate\_control}.}
  8719. \label{fig:explicate-control-challenge}
  8720. \end{figure}
  8721. %% Recall that in the example output of \code{explicate\_control} in
  8722. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8723. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8724. %% block. The first goal of this challenge assignment is to remove those
  8725. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8726. %% \code{explicate\_control} on the left and shows the result of bypassing
  8727. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8728. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8729. %% \code{block55}. The optimized code on the right of
  8730. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8731. %% \code{then} branch jumping directly to \code{block55}. The story is
  8732. %% similar for the \code{else} branch, as well as for the two branches in
  8733. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8734. %% have been optimized in this way, there are no longer any jumps to
  8735. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8736. %% \begin{figure}[tbp]
  8737. %% \begin{tabular}{lll}
  8738. %% \begin{minipage}{0.4\textwidth}
  8739. %% \begin{lstlisting}
  8740. %% block62:
  8741. %% tmp54 = (read);
  8742. %% if (eq? tmp54 2) then
  8743. %% goto block59;
  8744. %% else
  8745. %% goto block60;
  8746. %% block61:
  8747. %% tmp53 = (read);
  8748. %% if (eq? tmp53 0) then
  8749. %% goto block57;
  8750. %% else
  8751. %% goto block58;
  8752. %% block60:
  8753. %% goto block56;
  8754. %% block59:
  8755. %% goto block55;
  8756. %% block58:
  8757. %% goto block56;
  8758. %% block57:
  8759. %% goto block55;
  8760. %% block56:
  8761. %% return (+ 700 77);
  8762. %% block55:
  8763. %% return (+ 10 32);
  8764. %% start:
  8765. %% tmp52 = (read);
  8766. %% if (eq? tmp52 1) then
  8767. %% goto block61;
  8768. %% else
  8769. %% goto block62;
  8770. %% \end{lstlisting}
  8771. %% \end{minipage}
  8772. %% &
  8773. %% $\Rightarrow$
  8774. %% &
  8775. %% \begin{minipage}{0.55\textwidth}
  8776. %% \begin{lstlisting}
  8777. %% block62:
  8778. %% tmp54 = (read);
  8779. %% if (eq? tmp54 2) then
  8780. %% goto block55;
  8781. %% else
  8782. %% goto block56;
  8783. %% block61:
  8784. %% tmp53 = (read);
  8785. %% if (eq? tmp53 0) then
  8786. %% goto block55;
  8787. %% else
  8788. %% goto block56;
  8789. %% block56:
  8790. %% return (+ 700 77);
  8791. %% block55:
  8792. %% return (+ 10 32);
  8793. %% start:
  8794. %% tmp52 = (read);
  8795. %% if (eq? tmp52 1) then
  8796. %% goto block61;
  8797. %% else
  8798. %% goto block62;
  8799. %% \end{lstlisting}
  8800. %% \end{minipage}
  8801. %% \end{tabular}
  8802. %% \caption{Optimize jumps by removing trivial blocks.}
  8803. %% \label{fig:optimize-jumps}
  8804. %% \end{figure}
  8805. %% The name of this pass is \code{optimize-jumps}. We recommend
  8806. %% implementing this pass in two phases. The first phrase builds a hash
  8807. %% table that maps labels to possibly improved labels. The second phase
  8808. %% changes the target of each \code{goto} to use the improved label. If
  8809. %% the label is for a trivial block, then the hash table should map the
  8810. %% label to the first non-trivial block that can be reached from this
  8811. %% label by jumping through trivial blocks. If the label is for a
  8812. %% non-trivial block, then the hash table should map the label to itself;
  8813. %% we do not want to change jumps to non-trivial blocks.
  8814. %% The first phase can be accomplished by constructing an empty hash
  8815. %% table, call it \code{short-cut}, and then iterating over the control
  8816. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8817. %% then update the hash table, mapping the block's source to the target
  8818. %% of the \code{goto}. Also, the hash table may already have mapped some
  8819. %% labels to the block's source, to you must iterate through the hash
  8820. %% table and update all of those so that they instead map to the target
  8821. %% of the \code{goto}.
  8822. %% For the second phase, we recommend iterating through the $\Tail$ of
  8823. %% each block in the program, updating the target of every \code{goto}
  8824. %% according to the mapping in \code{short-cut}.
  8825. \begin{exercise}\normalfont\normalsize
  8826. Implement the improvements to the \code{explicate\_control} pass.
  8827. Check that it removes trivial blocks in a few example programs. Then
  8828. check that your compiler still passes all of your tests.
  8829. \end{exercise}
  8830. \subsection{Remove Jumps}
  8831. There is an opportunity for removing jumps that is apparent in the
  8832. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8833. ends with a jump to \code{block\_5} and there are no other jumps to
  8834. \code{block\_5} in the rest of the program. In this situation we can
  8835. avoid the runtime overhead of this jump by merging \code{block\_5}
  8836. into the preceding block, in this case the \code{start} block.
  8837. Figure~\ref{fig:remove-jumps} shows the output of
  8838. \code{allocate\_registers} on the left and the result of this
  8839. optimization on the right.
  8840. \begin{figure}[tbp]
  8841. {\if\edition\racketEd
  8842. \begin{tabular}{lll}
  8843. \begin{minipage}{0.5\textwidth}
  8844. % cond_test_82.rkt
  8845. \begin{lstlisting}
  8846. start:
  8847. callq read_int
  8848. movq %rax, %rcx
  8849. jmp block_5
  8850. block_5:
  8851. movq %rcx, %rax
  8852. addq $2, %rax
  8853. jmp conclusion
  8854. \end{lstlisting}
  8855. \end{minipage}
  8856. &
  8857. $\Rightarrow\qquad$
  8858. \begin{minipage}{0.4\textwidth}
  8859. \begin{lstlisting}
  8860. start:
  8861. callq read_int
  8862. movq %rax, %rcx
  8863. movq %rcx, %rax
  8864. addq $2, %rax
  8865. jmp conclusion
  8866. \end{lstlisting}
  8867. \end{minipage}
  8868. \end{tabular}
  8869. \fi}
  8870. {\if\edition\pythonEd
  8871. \begin{tabular}{lll}
  8872. \begin{minipage}{0.5\textwidth}
  8873. % cond_test_20.rkt
  8874. \begin{lstlisting}
  8875. start:
  8876. callq read_int
  8877. movq %rax, tmp_0
  8878. cmpq 1, tmp_0
  8879. je block_3
  8880. jmp block_4
  8881. block_3:
  8882. movq 42, tmp_1
  8883. jmp block_2
  8884. block_4:
  8885. movq 0, tmp_1
  8886. jmp block_2
  8887. block_2:
  8888. movq tmp_1, %rdi
  8889. callq print_int
  8890. movq 0, %rax
  8891. jmp conclusion
  8892. \end{lstlisting}
  8893. \end{minipage}
  8894. &
  8895. $\Rightarrow\qquad$
  8896. \begin{minipage}{0.4\textwidth}
  8897. \begin{lstlisting}
  8898. start:
  8899. callq read_int
  8900. movq %rax, tmp_0
  8901. cmpq 1, tmp_0
  8902. je block_3
  8903. movq 0, tmp_1
  8904. jmp block_2
  8905. block_3:
  8906. movq 42, tmp_1
  8907. jmp block_2
  8908. block_2:
  8909. movq tmp_1, %rdi
  8910. callq print_int
  8911. movq 0, %rax
  8912. jmp conclusion
  8913. \end{lstlisting}
  8914. \end{minipage}
  8915. \end{tabular}
  8916. \fi}
  8917. \caption{Merging basic blocks by removing unnecessary jumps.}
  8918. \label{fig:remove-jumps}
  8919. \end{figure}
  8920. \begin{exercise}\normalfont\normalsize
  8921. %
  8922. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8923. into their preceding basic block, when there is only one preceding
  8924. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8925. %
  8926. {\if\edition\racketEd
  8927. In the \code{run-tests.rkt} script, add the following entry to the
  8928. list of \code{passes} between \code{allocate\_registers}
  8929. and \code{patch\_instructions}.
  8930. \begin{lstlisting}
  8931. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8932. \end{lstlisting}
  8933. \fi}
  8934. %
  8935. Run the script to test your compiler.
  8936. %
  8937. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8938. blocks on several test programs.
  8939. \end{exercise}
  8940. \section{Further Reading}
  8941. \label{sec:cond-further-reading}
  8942. The algorithm for the \code{explicate\_control} pass is based on the
  8943. \code{expose-basic-blocks} pass in the course notes of
  8944. \citet{Dybvig:2010aa}.
  8945. %
  8946. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8947. \citet{Appel:2003fk}, and is related to translations into continuation
  8948. passing
  8949. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8950. %
  8951. The treatment of conditionals in the \code{explicate\_control} pass is
  8952. similar to short-cut boolean
  8953. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8954. and the case-of-case transformation~\citep{PeytonJones:1998}.
  8955. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8956. \chapter{Loops and Dataflow Analysis}
  8957. \label{ch:Lwhile}
  8958. % TODO: define R'_8
  8959. % TODO: multi-graph
  8960. {\if\edition\racketEd
  8961. %
  8962. In this chapter we study two features that are the hallmarks of
  8963. imperative programming languages: loops and assignments to local
  8964. variables. The following example demonstrates these new features by
  8965. computing the sum of the first five positive integers.
  8966. % similar to loop_test_1.rkt
  8967. \begin{lstlisting}
  8968. (let ([sum 0])
  8969. (let ([i 5])
  8970. (begin
  8971. (while (> i 0)
  8972. (begin
  8973. (set! sum (+ sum i))
  8974. (set! i (- i 1))))
  8975. sum)))
  8976. \end{lstlisting}
  8977. The \code{while} loop consists of a condition and a
  8978. body\footnote{The \code{while} loop is not a built-in
  8979. feature of the Racket language, but Racket includes many looping
  8980. constructs and it is straightforward to define \code{while} as a
  8981. macro.}. The body is evaluated repeatedly so long as the condition
  8982. remains true.
  8983. %
  8984. The \code{set!} consists of a variable and a right-hand-side
  8985. expression. The \code{set!} updates value of the variable to the
  8986. value of the right-hand-side.
  8987. %
  8988. The primary purpose of both the \code{while} loop and \code{set!} is
  8989. to cause side effects, so they do not have a meaningful result
  8990. value. Instead their result is the \code{\#<void>} value. The
  8991. expression \code{(void)} is an explicit way to create the
  8992. \code{\#<void>} value and it has type \code{Void}. The
  8993. \code{\#<void>} value can be passed around just like other values
  8994. inside an \LangLoop{} program and it can be compared for equality with
  8995. another \code{\#<void>} value. However, there are no other operations
  8996. specific to the the \code{\#<void>} value in \LangLoop{}. In contrast,
  8997. Racket defines the \code{void?} predicate that returns \code{\#t}
  8998. when applied to \code{\#<void>} and \code{\#f} otherwise.%
  8999. %
  9000. \footnote{Racket's \code{Void} type corresponds to what is often
  9001. called the \code{Unit} type. Racket's \code{Void} type is inhabited
  9002. by a single value \code{\#<void>} which corresponds to \code{unit}
  9003. or \code{()} in the literature~\citep{Pierce:2002hj}.}.
  9004. %
  9005. With the addition of side-effecting features such as \code{while} loop
  9006. and \code{set!}, it is helpful to also include in a language feature
  9007. for sequencing side effects: the \code{begin} expression. It consists
  9008. of one or more subexpressions that are evaluated left-to-right.
  9009. %
  9010. \fi}
  9011. {\if\edition\pythonEd
  9012. %
  9013. In this chapter we study loops, one of the hallmarks of imperative
  9014. programming languages. The following example demonstrates the
  9015. \code{while} loop by computing the sum of the first five positive
  9016. integers.
  9017. \begin{lstlisting}
  9018. sum = 0
  9019. i = 5
  9020. while i > 0:
  9021. sum = sum + i
  9022. i = i - 1
  9023. print(sum)
  9024. \end{lstlisting}
  9025. The \code{while} loop consists of a condition expression and a body (a
  9026. sequence of statements). The body is evaluated repeatedly so long as
  9027. the condition remains true.
  9028. %
  9029. \fi}
  9030. \section{The \LangLoop{} Language}
  9031. \newcommand{\LwhileGrammarRacket}{
  9032. \begin{array}{lcl}
  9033. \Type &::=& \key{Void}\\
  9034. \Exp &::=& \CSETBANG{\Var}{\Exp}
  9035. \MID \CBEGIN{\Exp^{*}}{\Exp}
  9036. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  9037. \end{array}
  9038. }
  9039. \newcommand{\LwhileASTRacket}{
  9040. \begin{array}{lcl}
  9041. \Type &::=& \key{Void}\\
  9042. \Exp &::=& \SETBANG{\Var}{\Exp}
  9043. \MID \BEGIN{\Exp^{*}}{\Exp}
  9044. \MID \WHILE{\Exp}{\Exp}
  9045. \MID \VOID{}
  9046. \end{array}
  9047. }
  9048. \newcommand{\LwhileGrammarPython}{
  9049. \begin{array}{rcl}
  9050. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9051. \end{array}
  9052. }
  9053. \newcommand{\LwhileASTPython}{
  9054. \begin{array}{lcl}
  9055. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9056. \end{array}
  9057. }
  9058. \begin{figure}[tp]
  9059. \centering
  9060. \fbox{
  9061. \begin{minipage}{0.96\textwidth}
  9062. \small
  9063. {\if\edition\racketEd
  9064. \[
  9065. \begin{array}{l}
  9066. \gray{\LintGrammarRacket{}} \\ \hline
  9067. \gray{\LvarGrammarRacket{}} \\ \hline
  9068. \gray{\LifGrammarRacket{}} \\ \hline
  9069. \LwhileGrammarRacket \\
  9070. \begin{array}{lcl}
  9071. \LangLoopM{} &::=& \Exp
  9072. \end{array}
  9073. \end{array}
  9074. \]
  9075. \fi}
  9076. {\if\edition\pythonEd
  9077. \[
  9078. \begin{array}{l}
  9079. \gray{\LintGrammarPython} \\ \hline
  9080. \gray{\LvarGrammarPython} \\ \hline
  9081. \gray{\LifGrammarPython} \\ \hline
  9082. \LwhileGrammarPython \\
  9083. \begin{array}{rcl}
  9084. \LangLoopM{} &::=& \Stmt^{*}
  9085. \end{array}
  9086. \end{array}
  9087. \]
  9088. \fi}
  9089. \end{minipage}
  9090. }
  9091. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9092. \label{fig:Lwhile-concrete-syntax}
  9093. \end{figure}
  9094. \begin{figure}[tp]
  9095. \centering
  9096. \fbox{
  9097. \begin{minipage}{0.96\textwidth}
  9098. \small
  9099. {\if\edition\racketEd
  9100. \[
  9101. \begin{array}{l}
  9102. \gray{\LintOpAST} \\ \hline
  9103. \gray{\LvarASTRacket{}} \\ \hline
  9104. \gray{\LifASTRacket{}} \\ \hline
  9105. \LwhileASTRacket{} \\
  9106. \begin{array}{lcl}
  9107. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9108. \end{array}
  9109. \end{array}
  9110. \]
  9111. \fi}
  9112. {\if\edition\pythonEd
  9113. \[
  9114. \begin{array}{l}
  9115. \gray{\LintASTPython} \\ \hline
  9116. \gray{\LvarASTPython} \\ \hline
  9117. \gray{\LifASTPython} \\ \hline
  9118. \LwhileASTPython \\
  9119. \begin{array}{lcl}
  9120. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9121. \end{array}
  9122. \end{array}
  9123. \]
  9124. \fi}
  9125. \end{minipage}
  9126. }
  9127. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9128. \label{fig:Lwhile-syntax}
  9129. \end{figure}
  9130. The concrete syntax of \LangLoop{} is defined in
  9131. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9132. in Figure~\ref{fig:Lwhile-syntax}.
  9133. %
  9134. The definitional interpreter for \LangLoop{} is shown in
  9135. Figure~\ref{fig:interp-Lwhile}.
  9136. %
  9137. {\if\edition\racketEd
  9138. %
  9139. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9140. and \code{Void} and we make changes to the cases for \code{Var} and
  9141. \code{Let} regarding variables. To support assignment to variables and
  9142. to make their lifetimes indefinite (see the second example in
  9143. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9144. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9145. value.
  9146. %
  9147. Now to discuss the new cases. For \code{SetBang}, we find the
  9148. variable in the environment to obtain a boxed value and then we change
  9149. it using \code{set-box!} to the result of evaluating the right-hand
  9150. side. The result value of a \code{SetBang} is \code{\#<void>}.
  9151. %
  9152. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9153. if the result is true, 2) evaluate the body.
  9154. The result value of a \code{while} loop is also \code{\#<void>}.
  9155. %
  9156. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9157. subexpressions \itm{es} for their effects and then evaluates
  9158. and returns the result from \itm{body}.
  9159. %
  9160. The $\VOID{}$ expression produces the \code{\#<void>} value.
  9161. %
  9162. \fi}
  9163. {\if\edition\pythonEd
  9164. %
  9165. We add a new case for \code{While} in the \code{interp\_stmts}
  9166. function, where we repeatedly interpret the \code{body} so long as the
  9167. \code{test} expression remains true.
  9168. %
  9169. \fi}
  9170. \begin{figure}[tbp]
  9171. {\if\edition\racketEd
  9172. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9173. (define interp-Lwhile-class
  9174. (class interp-Lif-class
  9175. (super-new)
  9176. (define/override ((interp-exp env) e)
  9177. (define recur (interp-exp env))
  9178. (match e
  9179. [(Let x e body)
  9180. (define new-env (dict-set env x (box (recur e))))
  9181. ((interp-exp new-env) body)]
  9182. [(Var x) (unbox (dict-ref env x))]
  9183. [(SetBang x rhs)
  9184. (set-box! (dict-ref env x) (recur rhs))]
  9185. [(WhileLoop cnd body)
  9186. (define (loop)
  9187. (cond [(recur cnd) (recur body) (loop)]
  9188. [else (void)]))
  9189. (loop)]
  9190. [(Begin es body)
  9191. (for ([e es]) (recur e))
  9192. (recur body)]
  9193. [(Void) (void)]
  9194. [else ((super interp-exp env) e)]))
  9195. ))
  9196. (define (interp-Lwhile p)
  9197. (send (new interp-Lwhile-class) interp-program p))
  9198. \end{lstlisting}
  9199. \fi}
  9200. {\if\edition\pythonEd
  9201. \begin{lstlisting}
  9202. class InterpLwhile(InterpLif):
  9203. def interp_stmts(self, ss, env):
  9204. if len(ss) == 0:
  9205. return
  9206. match ss[0]:
  9207. case While(test, body, []):
  9208. while self.interp_exp(test, env):
  9209. self.interp_stmts(body, env)
  9210. return self.interp_stmts(ss[1:], env)
  9211. case _:
  9212. return super().interp_stmts(ss, env)
  9213. \end{lstlisting}
  9214. \fi}
  9215. \caption{Interpreter for \LangLoop{}.}
  9216. \label{fig:interp-Lwhile}
  9217. \end{figure}
  9218. The type checker for \LangLoop{} is defined in
  9219. Figure~\ref{fig:type-check-Lwhile}.
  9220. %
  9221. {\if\edition\racketEd
  9222. %
  9223. The type checking of the \code{SetBang} expression requires the type
  9224. of the variable and the right-hand-side to agree. The result type is
  9225. \code{Void}. For \code{while}, the condition must be a \code{Boolean}
  9226. and the result type is \code{Void}. For \code{Begin}, the result type
  9227. is the type of its last subexpression.
  9228. %
  9229. \fi}
  9230. %
  9231. {\if\edition\pythonEd
  9232. %
  9233. A \code{while} loop is well typed if the type of the \code{test}
  9234. expression is \code{bool} and the statements in the \code{body} are
  9235. well typed.
  9236. %
  9237. \fi}
  9238. \begin{figure}[tbp]
  9239. {\if\edition\racketEd
  9240. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9241. (define type-check-Lwhile-class
  9242. (class type-check-Lif-class
  9243. (super-new)
  9244. (inherit check-type-equal?)
  9245. (define/override (type-check-exp env)
  9246. (lambda (e)
  9247. (define recur (type-check-exp env))
  9248. (match e
  9249. [(SetBang x rhs)
  9250. (define-values (rhs^ rhsT) (recur rhs))
  9251. (define varT (dict-ref env x))
  9252. (check-type-equal? rhsT varT e)
  9253. (values (SetBang x rhs^) 'Void)]
  9254. [(WhileLoop cnd body)
  9255. (define-values (cnd^ Tc) (recur cnd))
  9256. (check-type-equal? Tc 'Boolean e)
  9257. (define-values (body^ Tbody) ((type-check-exp env) body))
  9258. (values (WhileLoop cnd^ body^) 'Void)]
  9259. [(Begin es body)
  9260. (define-values (es^ ts)
  9261. (for/lists (l1 l2) ([e es]) (recur e)))
  9262. (define-values (body^ Tbody) (recur body))
  9263. (values (Begin es^ body^) Tbody)]
  9264. [else ((super type-check-exp env) e)])))
  9265. ))
  9266. (define (type-check-Lwhile p)
  9267. (send (new type-check-Lwhile-class) type-check-program p))
  9268. \end{lstlisting}
  9269. \fi}
  9270. {\if\edition\pythonEd
  9271. \begin{lstlisting}
  9272. class TypeCheckLwhile(TypeCheckLif):
  9273. def type_check_stmts(self, ss, env):
  9274. if len(ss) == 0:
  9275. return
  9276. match ss[0]:
  9277. case While(test, body, []):
  9278. test_t = self.type_check_exp(test, env)
  9279. check_type_equal(bool, test_t, test)
  9280. body_t = self.type_check_stmts(body, env)
  9281. return self.type_check_stmts(ss[1:], env)
  9282. case _:
  9283. return super().type_check_stmts(ss, env)
  9284. \end{lstlisting}
  9285. \fi}
  9286. \caption{Type checker for the \LangLoop{} language.}
  9287. \label{fig:type-check-Lwhile}
  9288. \end{figure}
  9289. {\if\edition\racketEd
  9290. %
  9291. At first glance, the translation of these language features to x86
  9292. seems straightforward because the \LangCIf{} intermediate language
  9293. already supports all of the ingredients that we need: assignment,
  9294. \code{goto}, conditional branching, and sequencing. However, there are
  9295. complications that arise which we discuss in the next section. After
  9296. that we introduce the changes necessary to the existing passes.
  9297. %
  9298. \fi}
  9299. {\if\edition\pythonEd
  9300. %
  9301. At first glance, the translation of \code{while} loops to x86 seems
  9302. straightforward because the \LangCIf{} intermediate language already
  9303. supports \code{goto} and conditional branching. However, there are
  9304. complications that arise which we discuss in the next section. After
  9305. that we introduce the changes necessary to the existing passes.
  9306. %
  9307. \fi}
  9308. \section{Cyclic Control Flow and Dataflow Analysis}
  9309. \label{sec:dataflow-analysis}
  9310. Up until this point the programs generated in
  9311. \code{explicate\_control} were guaranteed to be acyclic. However, each
  9312. \code{while} loop introduces a cycle. But does that matter?
  9313. %
  9314. Indeed it does. Recall that for register allocation, the compiler
  9315. performs liveness analysis to determine which variables can share the
  9316. same register. To accomplish this we analyzed the control-flow graph
  9317. in reverse topological order
  9318. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9319. only well-defined for acyclic graphs.
  9320. Let us return to the example of computing the sum of the first five
  9321. positive integers. Here is the program after instruction selection but
  9322. before register allocation.
  9323. \begin{center}
  9324. {\if\edition\racketEd
  9325. \begin{minipage}{0.45\textwidth}
  9326. \begin{lstlisting}
  9327. (define (main) : Integer
  9328. mainstart:
  9329. movq $0, sum
  9330. movq $5, i
  9331. jmp block5
  9332. block5:
  9333. movq i, tmp3
  9334. cmpq tmp3, $0
  9335. jl block7
  9336. jmp block8
  9337. \end{lstlisting}
  9338. \end{minipage}
  9339. \begin{minipage}{0.45\textwidth}
  9340. \begin{lstlisting}
  9341. block7:
  9342. addq i, sum
  9343. movq $1, tmp4
  9344. negq tmp4
  9345. addq tmp4, i
  9346. jmp block5
  9347. block8:
  9348. movq $27, %rax
  9349. addq sum, %rax
  9350. jmp mainconclusion
  9351. )
  9352. \end{lstlisting}
  9353. \end{minipage}
  9354. \fi}
  9355. {\if\edition\pythonEd
  9356. \begin{minipage}{0.45\textwidth}
  9357. \begin{lstlisting}
  9358. mainstart:
  9359. movq $0, sum
  9360. movq $5, i
  9361. jmp block5
  9362. block5:
  9363. cmpq $0, i
  9364. jg block7
  9365. jmp block8
  9366. \end{lstlisting}
  9367. \end{minipage}
  9368. \begin{minipage}{0.45\textwidth}
  9369. \begin{lstlisting}
  9370. block7:
  9371. addq i, sum
  9372. subq $1, i
  9373. jmp block5
  9374. block8:
  9375. movq sum, %rdi
  9376. callq print_int
  9377. movq $0, %rax
  9378. jmp mainconclusion
  9379. \end{lstlisting}
  9380. \end{minipage}
  9381. \fi}
  9382. \end{center}
  9383. Recall that liveness analysis works backwards, starting at the end
  9384. of each function. For this example we could start with \code{block8}
  9385. because we know what is live at the beginning of the conclusion,
  9386. just \code{rax} and \code{rsp}. So the live-before set
  9387. for \code{block8} is \code{\{rsp,sum\}}.
  9388. %
  9389. Next we might try to analyze \code{block5} or \code{block7}, but
  9390. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9391. we are stuck.
  9392. The way out of this impasse is to realize that we can compute an
  9393. under-approximation of each live-before set by starting with empty
  9394. live-after sets. By \emph{under-approximation}, we mean that the set
  9395. only contains variables that are live for some execution of the
  9396. program, but the set may be missing some variables that are live.
  9397. Next, the under-approximations for each block can be improved by 1)
  9398. updating the live-after set for each block using the approximate
  9399. live-before sets from the other blocks and 2) perform liveness
  9400. analysis again on each block. In fact, by iterating this process, the
  9401. under-approximations eventually become the correct solutions!
  9402. %
  9403. This approach of iteratively analyzing a control-flow graph is
  9404. applicable to many static analysis problems and goes by the name
  9405. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9406. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9407. Washington.
  9408. Let us apply this approach to the above example. We use the empty set
  9409. for the initial live-before set for each block. Let $m_0$ be the
  9410. following mapping from label names to sets of locations (variables and
  9411. registers).
  9412. \begin{center}
  9413. \begin{lstlisting}
  9414. mainstart: {}, block5: {}, block7: {}, block8: {}
  9415. \end{lstlisting}
  9416. \end{center}
  9417. Using the above live-before approximations, we determine the
  9418. live-after for each block and then apply liveness analysis to each
  9419. block. This produces our next approximation $m_1$ of the live-before
  9420. sets.
  9421. \begin{center}
  9422. \begin{lstlisting}
  9423. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9424. \end{lstlisting}
  9425. \end{center}
  9426. For the second round, the live-after for \code{mainstart} is the
  9427. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9428. liveness analysis for \code{mainstart} computes the empty set. The
  9429. live-after for \code{block5} is the union of the live-before sets for
  9430. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9431. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9432. sum\}}. The live-after for \code{block7} is the live-before for
  9433. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9434. So the liveness analysis for \code{block7} remains \code{\{i,
  9435. sum\}}. Together these yield the following approximation $m_2$ of
  9436. the live-before sets.
  9437. \begin{center}
  9438. \begin{lstlisting}
  9439. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9440. \end{lstlisting}
  9441. \end{center}
  9442. In the preceding iteration, only \code{block5} changed, so we can
  9443. limit our attention to \code{mainstart} and \code{block7}, the two
  9444. blocks that jump to \code{block5}. As a result, the live-before sets
  9445. for \code{mainstart} and \code{block7} are updated to include
  9446. \code{rsp}, yielding the following approximation $m_3$.
  9447. \begin{center}
  9448. \begin{lstlisting}
  9449. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9450. \end{lstlisting}
  9451. \end{center}
  9452. Because \code{block7} changed, we analyze \code{block5} once more, but
  9453. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9454. our approximations have converged, so $m_3$ is the solution.
  9455. This iteration process is guaranteed to converge to a solution by the
  9456. Kleene Fixed-Point Theorem, a general theorem about functions on
  9457. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9458. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9459. elements, a least element $\bot$ (pronounced bottom), and a join
  9460. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9461. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9462. working with join semi-lattices.} When two elements are ordered $m_i
  9463. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9464. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9465. approximation than $m_i$. The bottom element $\bot$ represents the
  9466. complete lack of information, i.e., the worst approximation. The join
  9467. operator takes two lattice elements and combines their information,
  9468. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9469. bound}
  9470. A dataflow analysis typically involves two lattices: one lattice to
  9471. represent abstract states and another lattice that aggregates the
  9472. abstract states of all the blocks in the control-flow graph. For
  9473. liveness analysis, an abstract state is a set of locations. We form
  9474. the lattice $L$ by taking its elements to be sets of locations, the
  9475. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9476. set, and the join operator to be set union.
  9477. %
  9478. We form a second lattice $M$ by taking its elements to be mappings
  9479. from the block labels to sets of locations (elements of $L$). We
  9480. order the mappings point-wise, using the ordering of $L$. So given any
  9481. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9482. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9483. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9484. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9485. We can think of one iteration of liveness analysis applied to the
  9486. whole program as being a function $f$ on the lattice $M$. It takes a
  9487. mapping as input and computes a new mapping.
  9488. \[
  9489. f(m_i) = m_{i+1}
  9490. \]
  9491. Next let us think for a moment about what a final solution $m_s$
  9492. should look like. If we perform liveness analysis using the solution
  9493. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9494. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9495. \[
  9496. f(m_s) = m_s
  9497. \]
  9498. Furthermore, the solution should only include locations that are
  9499. forced to be there by performing liveness analysis on the program, so
  9500. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9501. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9502. monotone (better inputs produce better outputs), then the least fixed
  9503. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9504. chain} obtained by starting at $\bot$ and iterating $f$ as
  9505. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9506. \[
  9507. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9508. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9509. \]
  9510. When a lattice contains only finitely-long ascending chains, then
  9511. every Kleene chain tops out at some fixed point after some number of
  9512. iterations of $f$.
  9513. \[
  9514. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9515. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9516. \]
  9517. The liveness analysis is indeed a monotone function and the lattice
  9518. $M$ only has finitely-long ascending chains because there are only a
  9519. finite number of variables and blocks in the program. Thus we are
  9520. guaranteed that iteratively applying liveness analysis to all blocks
  9521. in the program will eventually produce the least fixed point solution.
  9522. Next let us consider dataflow analysis in general and discuss the
  9523. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9524. %
  9525. The algorithm has four parameters: the control-flow graph \code{G}, a
  9526. function \code{transfer} that applies the analysis to one block, the
  9527. \code{bottom} and \code{join} operator for the lattice of abstract
  9528. states. The \code{analyze\_dataflow} function is formulated as a
  9529. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9530. function come from the predecessor nodes in the control-flow
  9531. graph. However, liveness analysis is a \emph{backward} dataflow
  9532. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9533. function with the transpose of the control-flow graph.
  9534. The algorithm begins by creating the bottom mapping, represented by a
  9535. hash table. It then pushes all of the nodes in the control-flow graph
  9536. onto the work list (a queue). The algorithm repeats the \code{while}
  9537. loop as long as there are items in the work list. In each iteration, a
  9538. node is popped from the work list and processed. The \code{input} for
  9539. the node is computed by taking the join of the abstract states of all
  9540. the predecessor nodes. The \code{transfer} function is then applied to
  9541. obtain the \code{output} abstract state. If the output differs from
  9542. the previous state for this block, the mapping for this block is
  9543. updated and its successor nodes are pushed onto the work list.
  9544. \begin{figure}[tb]
  9545. {\if\edition\racketEd
  9546. \begin{lstlisting}
  9547. (define (analyze_dataflow G transfer bottom join)
  9548. (define mapping (make-hash))
  9549. (for ([v (in-vertices G)])
  9550. (dict-set! mapping v bottom))
  9551. (define worklist (make-queue))
  9552. (for ([v (in-vertices G)])
  9553. (enqueue! worklist v))
  9554. (define trans-G (transpose G))
  9555. (while (not (queue-empty? worklist))
  9556. (define node (dequeue! worklist))
  9557. (define input (for/fold ([state bottom])
  9558. ([pred (in-neighbors trans-G node)])
  9559. (join state (dict-ref mapping pred))))
  9560. (define output (transfer node input))
  9561. (cond [(not (equal? output (dict-ref mapping node)))
  9562. (dict-set! mapping node output)
  9563. (for ([v (in-neighbors G node)])
  9564. (enqueue! worklist v))]))
  9565. mapping)
  9566. \end{lstlisting}
  9567. \fi}
  9568. {\if\edition\pythonEd
  9569. \begin{lstlisting}
  9570. def analyze_dataflow(G, transfer, bottom, join):
  9571. trans_G = transpose(G)
  9572. mapping = dict((v, bottom) for v in G.vertices())
  9573. worklist = deque(G.vertices)
  9574. while worklist:
  9575. node = worklist.pop()
  9576. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9577. output = transfer(node, input)
  9578. if output != mapping[node]:
  9579. mapping[node] = output
  9580. worklist.extend(G.adjacent(node))
  9581. \end{lstlisting}
  9582. \fi}
  9583. \caption{Generic work list algorithm for dataflow analysis}
  9584. \label{fig:generic-dataflow}
  9585. \end{figure}
  9586. {\if\edition\racketEd
  9587. \section{Mutable Variables \& Remove Complex Operands}
  9588. There is a subtle interaction between the
  9589. \code{remove\_complex\_operands} pass, the addition of \code{set!},
  9590. and the left-to-right order of evaluation of Racket. Consider the
  9591. following example.
  9592. \begin{lstlisting}
  9593. (let ([x 2])
  9594. (+ x (begin (set! x 40) x)))
  9595. \end{lstlisting}
  9596. The result of this program is \code{42} because the first read from
  9597. \code{x} produces \code{2} and the second produces \code{40}. However,
  9598. if we naively apply the \code{remove\_complex\_operands} pass to this
  9599. example we obtain the following program whose result is \code{80}!
  9600. \begin{lstlisting}
  9601. (let ([x 2])
  9602. (let ([tmp (begin (set! x 40) x)])
  9603. (+ x tmp)))
  9604. \end{lstlisting}
  9605. The problem is that, with mutable variables, the ordering between
  9606. reads and writes is important, and the
  9607. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9608. before the first read of \code{x}.
  9609. We recommend solving this problem by giving special treatment to reads
  9610. from mutable variables, that is, variables that occur on the left-hand
  9611. side of a \code{set!}. We mark each read from a mutable variable with
  9612. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9613. that the read operation is effectful in that it can produce different
  9614. results at different points in time. Let's apply this idea to the
  9615. following variation that also involves a variable that is not mutated.
  9616. % loop_test_24.rkt
  9617. \begin{lstlisting}
  9618. (let ([x 2])
  9619. (let ([y 0])
  9620. (+ y (+ x (begin (set! x 40) x)))))
  9621. \end{lstlisting}
  9622. We first analyze the above program to discover that variable \code{x}
  9623. is mutable but \code{y} is not. We then transform the program as
  9624. follows, replacing each occurrence of \code{x} with \code{(get! x)}.
  9625. \begin{lstlisting}
  9626. (let ([x 2])
  9627. (let ([y 0])
  9628. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9629. \end{lstlisting}
  9630. Now that we have a clear distinction between reads from mutable and
  9631. immutable variables, we can apply the \code{remove\_complex\_operands}
  9632. pass, where reads from immutable variables are still classified as
  9633. atomic expressions but reads from mutable variables are classified as
  9634. complex. Thus, \code{remove\_complex\_operands} yields the following
  9635. program.\\
  9636. \begin{minipage}{\textwidth}
  9637. \begin{lstlisting}
  9638. (let ([x 2])
  9639. (let ([y 0])
  9640. (+ y (let ([t1 (get! x)])
  9641. (let ([t2 (begin (set! x 40) (get! x))])
  9642. (+ t1 t2))))))
  9643. \end{lstlisting}
  9644. \end{minipage}
  9645. The temporary variable \code{t1} gets the value of \code{x} before the
  9646. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9647. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9648. do not generate a temporary variable for the occurrence of \code{y}
  9649. because it's an immutable variable. We want to avoid such unnecessary
  9650. extra temporaries because they would needless increase the number of
  9651. variables, making it more likely for some of them to be spilled. The
  9652. result of this program is \code{42}, the same as the result prior to
  9653. \code{remove\_complex\_operands}.
  9654. The approach that we've sketched above requires only a small
  9655. modification to \code{remove\_complex\_operands} to handle
  9656. \code{get!}. However, it requires a new pass, called
  9657. \code{uncover-get!}, that we discuss in
  9658. Section~\ref{sec:uncover-get-bang}.
  9659. As an aside, this problematic interaction between \code{set!} and the
  9660. pass \code{remove\_complex\_operands} is particular to Racket and not
  9661. its predecessor, the Scheme language. The key difference is that
  9662. Scheme does not specify an order of evaluation for the arguments of an
  9663. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9664. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9665. would be correct results for the example program. Interestingly,
  9666. Racket is implemented on top of the Chez Scheme
  9667. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9668. presented in this section (using extra \code{let} bindings to control
  9669. the order of evaluation) is used in the translation from Racket to
  9670. Scheme~\citep{Flatt:2019tb}.
  9671. \fi} % racket
  9672. Having discussed the complications that arise from adding support for
  9673. assignment and loops, we turn to discussing the individual compilation
  9674. passes.
  9675. {\if\edition\racketEd
  9676. \section{Uncover \texttt{get!}}
  9677. \label{sec:uncover-get-bang}
  9678. The goal of this pass it to mark uses of mutable variables so that
  9679. \code{remove\_complex\_operands} can treat them as complex expressions
  9680. and thereby preserve their ordering relative to the side-effects in
  9681. other operands. So the first step is to collect all the mutable
  9682. variables. We recommend creating an auxiliary function for this,
  9683. named \code{collect-set!}, that recursively traverses expressions,
  9684. returning the set of all variables that occur on the left-hand side of a
  9685. \code{set!}. Here's an excerpt of its implementation.
  9686. \begin{center}
  9687. \begin{minipage}{\textwidth}
  9688. \begin{lstlisting}
  9689. (define (collect-set! e)
  9690. (match e
  9691. [(Var x) (set)]
  9692. [(Int n) (set)]
  9693. [(Let x rhs body)
  9694. (set-union (collect-set! rhs) (collect-set! body))]
  9695. [(SetBang var rhs)
  9696. (set-union (set var) (collect-set! rhs))]
  9697. ...))
  9698. \end{lstlisting}
  9699. \end{minipage}
  9700. \end{center}
  9701. By placing this pass after \code{uniquify}, we need not worry about
  9702. variable shadowing and our logic for \code{Let} can remain simple, as
  9703. in the excerpt above.
  9704. The second step is to mark the occurrences of the mutable variables
  9705. with the new \code{GetBang} AST node (\code{get!} in concrete
  9706. syntax). The following is an excerpt of the \code{uncover-get!-exp}
  9707. function, which takes two parameters: the set of mutable variables
  9708. \code{set!-vars}, and the expression \code{e} to be processed. The
  9709. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9710. mutable variable or leaves it alone if not.
  9711. \begin{center}
  9712. \begin{minipage}{\textwidth}
  9713. \begin{lstlisting}
  9714. (define ((uncover-get!-exp set!-vars) e)
  9715. (match e
  9716. [(Var x)
  9717. (if (set-member? set!-vars x)
  9718. (GetBang x)
  9719. (Var x))]
  9720. ...))
  9721. \end{lstlisting}
  9722. \end{minipage}
  9723. \end{center}
  9724. To wrap things up, define the \code{uncover-get!} function for
  9725. processing a whole program, using \code{collect-set!} to obtain the
  9726. set of mutable variables and then \code{uncover-get!-exp} to replace
  9727. their occurrences with \code{GetBang}.
  9728. \fi}
  9729. \section{Remove Complex Operands}
  9730. \label{sec:rco-loop}
  9731. {\if\edition\racketEd
  9732. %
  9733. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9734. \code{while} are all complex expressions. The subexpressions of
  9735. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9736. %
  9737. \fi}
  9738. {\if\edition\pythonEd
  9739. %
  9740. The change needed for this pass is to add a case for the \code{while}
  9741. statement. The condition of a \code{while} loop is allowed to be a
  9742. complex expression, just like the condition of the \code{if}
  9743. statement.
  9744. %
  9745. \fi}
  9746. %
  9747. Figure~\ref{fig:Lwhile-anf-syntax} defines the output language
  9748. \LangLoopANF{} of this pass.
  9749. \newcommand{\LwhileMonadASTRacket}{
  9750. \begin{array}{rcl}
  9751. \Atm &::=& \VOID{} \\
  9752. \Exp &::=& \GETBANG{\Var}
  9753. \MID \SETBANG{\Var}{\Exp}
  9754. \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} \\
  9755. &\MID& \WHILE{\Exp}{\Exp}
  9756. \end{array}
  9757. }
  9758. \newcommand{\LwhileMonadASTPython}{
  9759. \begin{array}{rcl}
  9760. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9761. \end{array}
  9762. }
  9763. \begin{figure}[tp]
  9764. \centering
  9765. \fbox{
  9766. \begin{minipage}{0.96\textwidth}
  9767. \small
  9768. {\if\edition\racketEd
  9769. \[
  9770. \begin{array}{l}
  9771. \gray{\LvarMonadASTRacket} \\ \hline
  9772. \gray{\LifMonadASTRacket} \\ \hline
  9773. \LwhileMonadASTRacket \\
  9774. \begin{array}{rcl}
  9775. \LangLoopANF &::=& \PROGRAM{\code{'()}}{\Exp}
  9776. \end{array}
  9777. \end{array}
  9778. \]
  9779. \fi}
  9780. {\if\edition\pythonEd
  9781. \[
  9782. \begin{array}{l}
  9783. \gray{\LvarMonadASTPython} \\ \hline
  9784. \gray{\LifMonadASTPython} \\ \hline
  9785. \LwhileMonadASTPython \\
  9786. \begin{array}{rcl}
  9787. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9788. \end{array}
  9789. \end{array}
  9790. %% \begin{array}{rcl}
  9791. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9792. %% \Exp &::=& \Atm \MID \READ{} \\
  9793. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9794. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9795. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9796. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9797. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9798. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9799. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9800. %% \end{array}
  9801. \]
  9802. \fi}
  9803. \end{minipage}
  9804. }
  9805. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9806. \label{fig:Lwhile-anf-syntax}
  9807. \end{figure}
  9808. {\if\edition\racketEd
  9809. %
  9810. As usual, when a complex expression appears in a grammar position that
  9811. needs to be atomic, such as the argument of a primitive operator, we
  9812. must introduce a temporary variable and bind it to the complex
  9813. expression. This approach applies, unchanged, to handle the new
  9814. language forms. For example, in the following code there are two
  9815. \code{begin} expressions appearing as arguments to the \code{+}
  9816. operator. The output of \code{rco\_exp} is shown below, in which the
  9817. \code{begin} expressions have been bound to temporary
  9818. variables. Recall that \code{let} expressions in \LangLoopANF{} are
  9819. allowed to have arbitrary expressions in their right-hand-side
  9820. expression, so it is fine to place \code{begin} there.
  9821. %
  9822. \begin{center}
  9823. \begin{tabular}{lcl}
  9824. \begin{minipage}{0.4\textwidth}
  9825. \begin{lstlisting}
  9826. (let ([x2 10])
  9827. (let ([y3 0])
  9828. (+ (+ (begin
  9829. (set! y3 (read))
  9830. (get! x2))
  9831. (begin
  9832. (set! x2 (read))
  9833. (get! y3)))
  9834. (get! x2))))
  9835. \end{lstlisting}
  9836. \end{minipage}
  9837. &
  9838. $\Rightarrow$
  9839. &
  9840. \begin{minipage}{0.4\textwidth}
  9841. \begin{lstlisting}
  9842. (let ([x2 10])
  9843. (let ([y3 0])
  9844. (let ([tmp4 (begin
  9845. (set! y3 (read))
  9846. x2)])
  9847. (let ([tmp5 (begin
  9848. (set! x2 (read))
  9849. y3)])
  9850. (let ([tmp6 (+ tmp4 tmp5)])
  9851. (let ([tmp7 x2])
  9852. (+ tmp6 tmp7)))))))
  9853. \end{lstlisting}
  9854. \end{minipage}
  9855. \end{tabular}
  9856. \end{center}
  9857. \fi}
  9858. \section{Explicate Control \racket{and \LangCLoop{}}}
  9859. \label{sec:explicate-loop}
  9860. \newcommand{\CloopASTRacket}{
  9861. \begin{array}{lcl}
  9862. \Atm &::=& \VOID \\
  9863. \Stmt &::=& \READ{}
  9864. \end{array}
  9865. }
  9866. {\if\edition\racketEd
  9867. Recall that in the \code{explicate\_control} pass we define one helper
  9868. function for each kind of position in the program. For the \LangVar{}
  9869. language of integers and variables we needed assignment and tail
  9870. positions. The \code{if} expressions of \LangIf{} introduced predicate
  9871. positions. For \LangLoop{}, the \code{begin} expression introduces yet
  9872. another kind of position: effect position. Except for the last
  9873. subexpression, the subexpressions inside a \code{begin} are evaluated
  9874. only for their effect. Their result values are discarded. We can
  9875. generate better code by taking this fact into account.
  9876. The output language of \code{explicate\_control} is \LangCLoop{}
  9877. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9878. \LangCIf{}. The only syntactic difference is the addition of \VOID{}
  9879. and that \code{read} may appear as a statement. The most significant
  9880. difference between the programs generated by \code{explicate\_control}
  9881. in Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this
  9882. chapter is that the control-flow graphs of the later may contain
  9883. cycles.
  9884. \begin{figure}[tp]
  9885. \fbox{
  9886. \begin{minipage}{0.96\textwidth}
  9887. \small
  9888. \[
  9889. \begin{array}{l}
  9890. \gray{\CvarASTRacket} \\ \hline
  9891. \gray{\CifASTRacket} \\ \hline
  9892. \CloopASTRacket \\
  9893. \begin{array}{lcl}
  9894. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9895. \end{array}
  9896. \end{array}
  9897. \]
  9898. \end{minipage}
  9899. }
  9900. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9901. \label{fig:c7-syntax}
  9902. \end{figure}
  9903. The new auxiliary function \code{explicate\_effect} takes an
  9904. expression (in an effect position) and the code for its
  9905. continuation. The function returns a $\Tail$ that includes the
  9906. generated code for the input expression followed by the
  9907. continuation. If the expression is obviously pure, that is, never
  9908. causes side effects, then the expression can be removed, so the result
  9909. is just the continuation.
  9910. %
  9911. The case for $\WHILE{\itm{cnd}}{\itm{body}}$ expressions is
  9912. interesting; the generated code is depicted in the following diagram.
  9913. \begin{center}
  9914. \begin{minipage}{0.3\textwidth}
  9915. \xymatrix{
  9916. *+[F=]{\txt{\code{goto} \itm{loop}}} \ar[r]
  9917. & *+[F]{\txt{\itm{loop}: \\ \itm{cnd'}}} \ar[r]^{else} \ar[d]^{then}
  9918. & *+[F]{\txt{\itm{cont}}} \\
  9919. & *+[F]{\txt{\itm{body'} \\ \code{goto} \itm{loop}}} \ar@/^50pt/[u]
  9920. }
  9921. \end{minipage}
  9922. \end{center}
  9923. We start by creating a fresh label $\itm{loop}$ for the top of the
  9924. loop. Next, recursively process the \itm{body} (in effect position)
  9925. with a \code{goto} to $\itm{loop}$ as the continuation, producing
  9926. \itm{body'}. Process the \itm{cnd} (in predicate position) with
  9927. \itm{body'} as the then-branch and the continuation block as the
  9928. else-branch. The result should be added to the dictionary of
  9929. \code{basic-blocks} with the label \itm{loop}. The result for the
  9930. whole \code{while} loop is a \code{goto} to the \itm{loop} label.
  9931. The auxiliary functions for tail, assignment, and predicate positions
  9932. need to be updated. The three new language forms, \code{while},
  9933. \code{set!}, and \code{begin}, can appear in assignment and tail
  9934. positions. Only \code{begin} may appear in predicate positions; the
  9935. other two have result type \code{Void}.
  9936. \fi}
  9937. %
  9938. {\if\edition\pythonEd
  9939. %
  9940. The output of this pass is the language \LangCIf{}. No new language
  9941. features are needed in the output because a \code{while} loop can be
  9942. expressed in terms of \code{goto} and \code{if} statements, which are
  9943. already in \LangCIf{}.
  9944. %
  9945. Add a case for the \code{while} statement to the
  9946. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9947. the condition expression.
  9948. %
  9949. \fi}
  9950. {\if\edition\racketEd
  9951. \section{Select Instructions}
  9952. \label{sec:select-instructions-loop}
  9953. Only two small additions are needed in the \code{select\_instructions}
  9954. pass to handle the changes to \LangCLoop{}. First, to handle the
  9955. addition of \VOID{} we simply translate it to \code{0}. Second,
  9956. \code{read} may appear as a stand-alone statement instead of only
  9957. appearing on the right-hand side of an assignment statement. The code
  9958. generation is nearly identical to the one for assignment; just leave
  9959. off the instruction for moving the result into the left-hand side.
  9960. \fi}
  9961. \section{Register Allocation}
  9962. \label{sec:register-allocation-loop}
  9963. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9964. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9965. which complicates the liveness analysis needed for register
  9966. allocation.
  9967. %
  9968. We recommend using the generic \code{analyze\_dataflow} function that
  9969. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9970. perform liveness analysis, replacing the code in
  9971. \code{uncover\_live} that processed the basic blocks in topological
  9972. order (Section~\ref{sec:liveness-analysis-Lif}).
  9973. The \code{analyze\_dataflow} function has four parameters.
  9974. \begin{enumerate}
  9975. \item The first parameter \code{G} should be passed the transpose
  9976. of the control-flow graph.
  9977. \item The second parameter \code{transfer} should be passed a function
  9978. that applies liveness analysis to a basic block. It takes two
  9979. parameters: the label for the block to analyze and the live-after
  9980. set for that block. The transfer function should return the
  9981. live-before set for the block.
  9982. %
  9983. \racket{Also, as a side-effect, it should update the block's
  9984. $\itm{info}$ with the liveness information for each instruction.}
  9985. %
  9986. \python{Also, as a side-effect, it should update the live-before and
  9987. live-after sets for each instruction.}
  9988. %
  9989. To implement the \code{transfer} function, you should be able to
  9990. reuse the code you already have for analyzing basic blocks.
  9991. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9992. \code{bottom} and \code{join} for the lattice of abstract states,
  9993. i.e. sets of locations. For liveness analysis, the bottom of the
  9994. lattice is the empty set and the join operator is set union.
  9995. \end{enumerate}
  9996. \begin{figure}[p]
  9997. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9998. \node (Lfun) at (0,2) {\large \LangLoop{}};
  9999. \node (Lfun-2) at (3,2) {\large \LangLoop{}};
  10000. %\node (Lfun-3) at (6,2) {\large \LangLoop{}};
  10001. %\node (Lfun-4) at (9,2) {\large \LangLoopFunRef{}};
  10002. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  10003. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  10004. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  10005. \node (F1-4) at (6,2) {\large \LangLoop{}};
  10006. \node (F1-5) at (9,2) {\large \LangLoop{}};
  10007. \node (F1-6) at (12,2) {\large \LangLoopANF{}};
  10008. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  10009. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  10010. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  10011. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  10012. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  10013. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  10014. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  10015. %% \path[->,bend left=15] (Lfun) edge [above] node
  10016. %% {\ttfamily\footnotesize type-check} (Lfun-2);
  10017. \path[->,bend left=15] (Lfun) edge [above] node
  10018. {\ttfamily\footnotesize shrink} (Lfun-2);
  10019. \path[->,bend left=15] (Lfun-2) edge [above] node
  10020. {\ttfamily\footnotesize uniquify} (F1-4);
  10021. %% \path[->,bend left=15] (Lfun-3) edge [above] node
  10022. %% {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  10023. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10024. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  10025. %% \path[->,bend left=15] (Lfun-4) edge [right] node
  10026. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  10027. %% \path[->,bend right=15] (F1-2) edge [above] node
  10028. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  10029. %% \path[->,bend right=15] (F1-3) edge [above] node
  10030. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  10031. \path[->,bend left=15] (F1-4) edge [above] node
  10032. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  10033. \path[->,bend left=15] (F1-5) edge [above] node
  10034. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  10035. \path[->,bend left=15] (F1-6) edge [right] node
  10036. {\ttfamily\footnotesize explicate\_control} (C3-2);
  10037. \path[->,bend left=15] (C3-2) edge [left] node
  10038. {\ttfamily\footnotesize select\_instr.} (x86-2);
  10039. \path[->,bend right=15] (x86-2) edge [left] node
  10040. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  10041. \path[->,bend right=15] (x86-2-1) edge [below] node
  10042. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  10043. \path[->,bend right=15] (x86-2-2) edge [left] node
  10044. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  10045. \path[->,bend left=15] (x86-3) edge [above] node
  10046. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  10047. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  10048. \end{tikzpicture}
  10049. \caption{Diagram of the passes for \LangLoop{}.}
  10050. \label{fig:Lwhile-passes}
  10051. \end{figure}
  10052. Figure~\ref{fig:Lwhile-passes} provides an overview of all the passes needed
  10053. for the compilation of \LangLoop{}.
  10054. % Further Reading: dataflow analysis
  10055. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  10056. \chapter{Tuples and Garbage Collection}
  10057. \label{ch:Lvec}
  10058. \index{subject}{tuple}
  10059. \index{subject}{vector}
  10060. \index{subject}{allocate}
  10061. \index{subject}{heap allocate}
  10062. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  10063. %% all the IR grammars are spelled out! \\ --Jeremy}
  10064. %% \margincomment{\scriptsize Be more explicit about how to deal with
  10065. %% the root stack. \\ --Jeremy}
  10066. In this chapter we study the implementation of tuples\racket{, called
  10067. vectors in Racket}. A tuple is a fixed-length sequence of elements
  10068. where each element may have a different type.
  10069. %
  10070. This language feature is the first to use the computer's
  10071. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  10072. indefinite, that is, a tuple lives forever from the programmer's
  10073. viewpoint. Of course, from an implementer's viewpoint, it is important
  10074. to reclaim the space associated with a tuple when it is no longer
  10075. needed, which is why we also study \emph{garbage collection}
  10076. \index{garbage collection} techniques in this chapter.
  10077. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  10078. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  10079. language of Chapter~\ref{ch:Lwhile} with tuples.
  10080. %
  10081. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10082. copying live tuples back and forth between two halves of the heap. The
  10083. garbage collector requires coordination with the compiler so that it
  10084. can find all of the live tuples.
  10085. %
  10086. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10087. discuss the necessary changes and additions to the compiler passes,
  10088. including a new compiler pass named \code{expose\_allocation}.
  10089. \section{The \LangVec{} Language}
  10090. \label{sec:r3}
  10091. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10092. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10093. %
  10094. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10095. creating a tuple, \code{vector-ref} for reading an element of a
  10096. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10097. \code{vector-length} for obtaining the number of elements of a
  10098. tuple.}
  10099. %
  10100. \python{The \LangVec{} language adds 1) tuple creation via a
  10101. comma-separated list of expressions, 2) accessing an element of a
  10102. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10103. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10104. operator, and 4) obtaining the number of elements (the length) of a
  10105. tuple. In this chapter, we restrict access indices to constant
  10106. integers.}
  10107. %
  10108. The program below shows an example use of tuples. It creates a tuple
  10109. \code{t} containing the elements \code{40},
  10110. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10111. contains just \code{2}. The element at index $1$ of \code{t} is
  10112. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10113. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10114. to which we add \code{2}, the element at index $0$ of the tuple. So
  10115. the result of the program is \code{42}.
  10116. %
  10117. {\if\edition\racketEd
  10118. \begin{lstlisting}
  10119. (let ([t (vector 40 #t (vector 2))])
  10120. (if (vector-ref t 1)
  10121. (+ (vector-ref t 0)
  10122. (vector-ref (vector-ref t 2) 0))
  10123. 44))
  10124. \end{lstlisting}
  10125. \fi}
  10126. {\if\edition\pythonEd
  10127. \begin{lstlisting}
  10128. t = 40, True, (2,)
  10129. print( t[0] + t[2][0] if t[1] else 44 )
  10130. \end{lstlisting}
  10131. \fi}
  10132. \newcommand{\LtupGrammarRacket}{
  10133. \begin{array}{lcl}
  10134. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10135. \Exp &::=& \LP\key{vector}\;\Exp^{*}\RP
  10136. \MID \LP\key{vector-length}\;\Exp\RP \\
  10137. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10138. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10139. \end{array}
  10140. }
  10141. \newcommand{\LtupASTRacket}{
  10142. \begin{array}{lcl}
  10143. \Type &::=& \LP\key{Vector}\;\Type^{*}\RP \\
  10144. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10145. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10146. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10147. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10148. \end{array}
  10149. }
  10150. \newcommand{\LtupGrammarPython}{
  10151. \begin{array}{rcl}
  10152. \itm{cmp} &::= & \key{is} \\
  10153. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10154. \end{array}
  10155. }
  10156. \newcommand{\LtupASTPython}{
  10157. \begin{array}{lcl}
  10158. \itm{cmp} &::= & \code{Is()} \\
  10159. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10160. &\MID& \LEN{\Exp}
  10161. \end{array}
  10162. }
  10163. \begin{figure}[tbp]
  10164. \centering
  10165. \fbox{
  10166. \begin{minipage}{0.96\textwidth}
  10167. \small
  10168. {\if\edition\racketEd
  10169. \[
  10170. \begin{array}{l}
  10171. \gray{\LintGrammarRacket{}} \\ \hline
  10172. \gray{\LvarGrammarRacket{}} \\ \hline
  10173. \gray{\LifGrammarRacket{}} \\ \hline
  10174. \gray{\LwhileGrammarRacket} \\ \hline
  10175. \LtupGrammarRacket \\
  10176. \begin{array}{lcl}
  10177. \LangVecM{} &::=& \Exp
  10178. \end{array}
  10179. \end{array}
  10180. \]
  10181. \fi}
  10182. {\if\edition\pythonEd
  10183. \[
  10184. \begin{array}{l}
  10185. \gray{\LintGrammarPython{}} \\ \hline
  10186. \gray{\LvarGrammarPython{}} \\ \hline
  10187. \gray{\LifGrammarPython{}} \\ \hline
  10188. \gray{\LwhileGrammarPython} \\ \hline
  10189. \LtupGrammarPython \\
  10190. \begin{array}{rcl}
  10191. \LangVecM{} &::=& \Stmt^{*}
  10192. \end{array}
  10193. \end{array}
  10194. \]
  10195. \fi}
  10196. \end{minipage}
  10197. }
  10198. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10199. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10200. \label{fig:Lvec-concrete-syntax}
  10201. \end{figure}
  10202. \begin{figure}[tp]
  10203. \centering
  10204. \fbox{
  10205. \begin{minipage}{0.96\textwidth}
  10206. \small
  10207. {\if\edition\racketEd
  10208. \[
  10209. \begin{array}{l}
  10210. \gray{\LintOpAST} \\ \hline
  10211. \gray{\LvarASTRacket{}} \\ \hline
  10212. \gray{\LifASTRacket{}} \\ \hline
  10213. \gray{\LwhileASTRacket{}} \\ \hline
  10214. \LtupASTRacket{} \\
  10215. \begin{array}{lcl}
  10216. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10217. \end{array}
  10218. \end{array}
  10219. \]
  10220. \fi}
  10221. {\if\edition\pythonEd
  10222. \[
  10223. \begin{array}{l}
  10224. \gray{\LintASTPython} \\ \hline
  10225. \gray{\LvarASTPython} \\ \hline
  10226. \gray{\LifASTPython} \\ \hline
  10227. \gray{\LwhileASTPython} \\ \hline
  10228. \LtupASTPython \\
  10229. \begin{array}{lcl}
  10230. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10231. \end{array}
  10232. \end{array}
  10233. \]
  10234. \fi}
  10235. \end{minipage}
  10236. }
  10237. \caption{The abstract syntax of \LangVec{}.}
  10238. \label{fig:Lvec-syntax}
  10239. \end{figure}
  10240. Tuples raise several interesting new issues. First, variable binding
  10241. performs a shallow-copy when dealing with tuples, which means that
  10242. different variables can refer to the same tuple, that is, two
  10243. variables can be \emph{aliases}\index{subject}{alias} for the same
  10244. entity. Consider the following example in which both \code{t1} and
  10245. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10246. different tuple value but with equal elements. The result of the
  10247. program is \code{42}.
  10248. \begin{center}
  10249. \begin{minipage}{0.96\textwidth}
  10250. {\if\edition\racketEd
  10251. \begin{lstlisting}
  10252. (let ([t1 (vector 3 7)])
  10253. (let ([t2 t1])
  10254. (let ([t3 (vector 3 7)])
  10255. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10256. 42
  10257. 0))))
  10258. \end{lstlisting}
  10259. \fi}
  10260. {\if\edition\pythonEd
  10261. \begin{lstlisting}
  10262. t1 = 3, 7
  10263. t2 = t1
  10264. t3 = 3, 7
  10265. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10266. \end{lstlisting}
  10267. \fi}
  10268. \end{minipage}
  10269. \end{center}
  10270. {\if\edition\racketEd
  10271. Whether two variables are aliased or not affects what happens
  10272. when the underlying tuple is mutated\index{subject}{mutation}.
  10273. Consider the following example in which \code{t1} and \code{t2}
  10274. again refer to the same tuple value.
  10275. \begin{center}
  10276. \begin{minipage}{0.96\textwidth}
  10277. \begin{lstlisting}
  10278. (let ([t1 (vector 3 7)])
  10279. (let ([t2 t1])
  10280. (let ([_ (vector-set! t2 0 42)])
  10281. (vector-ref t1 0))))
  10282. \end{lstlisting}
  10283. \end{minipage}
  10284. \end{center}
  10285. The mutation through \code{t2} is visible when referencing the tuple
  10286. from \code{t1}, so the result of this program is \code{42}.
  10287. \fi}
  10288. The next issue concerns the lifetime of tuples. When does their
  10289. lifetime end? Notice that \LangVec{} does not include an operation
  10290. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10291. to any notion of static scoping.
  10292. %
  10293. {\if\edition\racketEd
  10294. %
  10295. For example, the following program returns \code{42} even though the
  10296. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10297. that reads from the vector it was bound to.
  10298. \begin{center}
  10299. \begin{minipage}{0.96\textwidth}
  10300. \begin{lstlisting}
  10301. (let ([v (vector (vector 44))])
  10302. (let ([x (let ([w (vector 42)])
  10303. (let ([_ (vector-set! v 0 w)])
  10304. 0))])
  10305. (+ x (vector-ref (vector-ref v 0) 0))))
  10306. \end{lstlisting}
  10307. \end{minipage}
  10308. \end{center}
  10309. \fi}
  10310. %
  10311. {\if\edition\pythonEd
  10312. %
  10313. For example, the following program returns \code{42} even though the
  10314. variable \code{x} goes out of scope when the function returns, prior
  10315. to reading the tuple element at index zero. (We study the compilation
  10316. of functions in Chapter~\ref{ch:Lfun}.)
  10317. %
  10318. \begin{center}
  10319. \begin{minipage}{0.96\textwidth}
  10320. \begin{lstlisting}
  10321. def f():
  10322. x = 42, 43
  10323. return x
  10324. t = f()
  10325. print( t[0] )
  10326. \end{lstlisting}
  10327. \end{minipage}
  10328. \end{center}
  10329. \fi}
  10330. %
  10331. From the perspective of programmer-observable behavior, tuples live
  10332. forever. However, if they really lived forever then many long-running
  10333. programs would run out of memory. To solve this problem, the
  10334. language's runtime system performs automatic garbage collection.
  10335. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10336. \LangVec{} language.
  10337. %
  10338. \racket{We define the \code{vector}, \code{vector-ref},
  10339. \code{vector-set!}, and \code{vector-length} operations for
  10340. \LangVec{} in terms of the corresponding operations in Racket. One
  10341. subtle point is that the \code{vector-set!} operation returns the
  10342. \code{\#<void>} value.}
  10343. %
  10344. \python{We represent tuples with Python lists in the interpreter
  10345. because we need to write to them
  10346. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10347. immutable.) We define element access, the \code{is} operator, and
  10348. the \code{len} operator for \LangVec{} in terms of the corresponding
  10349. operations in Python.}
  10350. \begin{figure}[tbp]
  10351. {\if\edition\racketEd
  10352. \begin{lstlisting}
  10353. (define interp-Lvec-class
  10354. (class interp-Lwhile-class
  10355. (super-new)
  10356. (define/override (interp-op op)
  10357. (match op
  10358. ['eq? (lambda (v1 v2)
  10359. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10360. (and (boolean? v1) (boolean? v2))
  10361. (and (vector? v1) (vector? v2))
  10362. (and (void? v1) (void? v2)))
  10363. (eq? v1 v2)]))]
  10364. ['vector vector]
  10365. ['vector-length vector-length]
  10366. ['vector-ref vector-ref]
  10367. ['vector-set! vector-set!]
  10368. [else (super interp-op op)]
  10369. ))
  10370. (define/override ((interp-exp env) e)
  10371. (match e
  10372. [(HasType e t) ((interp-exp env) e)]
  10373. [else ((super interp-exp env) e)]
  10374. ))
  10375. ))
  10376. (define (interp-Lvec p)
  10377. (send (new interp-Lvec-class) interp-program p))
  10378. \end{lstlisting}
  10379. \fi}
  10380. %
  10381. {\if\edition\pythonEd
  10382. \begin{lstlisting}
  10383. class InterpLtup(InterpLwhile):
  10384. def interp_cmp(self, cmp):
  10385. match cmp:
  10386. case Is():
  10387. return lambda x, y: x is y
  10388. case _:
  10389. return super().interp_cmp(cmp)
  10390. def interp_exp(self, e, env):
  10391. match e:
  10392. case Tuple(es, Load()):
  10393. return tuple([self.interp_exp(e, env) for e in es])
  10394. case Subscript(tup, index, Load()):
  10395. t = self.interp_exp(tup, env)
  10396. n = self.interp_exp(index, env)
  10397. return t[n]
  10398. case _:
  10399. return super().interp_exp(e, env)
  10400. \end{lstlisting}
  10401. \fi}
  10402. \caption{Interpreter for the \LangVec{} language.}
  10403. \label{fig:interp-Lvec}
  10404. \end{figure}
  10405. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10406. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10407. we need to know which elements of the tuple are themselves tuples for
  10408. the purposes of garbage collection. We can obtain this information
  10409. during type checking. The type checker in
  10410. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10411. expression, it also
  10412. %
  10413. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10414. where $T$ is the tuple's type.
  10415. To create the s-expression for the \code{Vector} type in
  10416. Figure~\ref{fig:type-check-Lvec}, we use the
  10417. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10418. operator} \code{,@} to insert the list \code{t*} without its usual
  10419. start and end parentheses. \index{subject}{unquote-slicing}}
  10420. %
  10421. \python{records the type of each tuple expression in a new field
  10422. named \code{has\_type}. Because the type checker has to compute the type
  10423. of each tuple access, the index must be a constant.}
  10424. \begin{figure}[tp]
  10425. {\if\edition\racketEd
  10426. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10427. (define type-check-Lvec-class
  10428. (class type-check-Lif-class
  10429. (super-new)
  10430. (inherit check-type-equal?)
  10431. (define/override (type-check-exp env)
  10432. (lambda (e)
  10433. (define recur (type-check-exp env))
  10434. (match e
  10435. [(Prim 'vector es)
  10436. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10437. (define t `(Vector ,@t*))
  10438. (values (HasType (Prim 'vector e*) t) t)]
  10439. [(Prim 'vector-ref (list e1 (Int i)))
  10440. (define-values (e1^ t) (recur e1))
  10441. (match t
  10442. [`(Vector ,ts ...)
  10443. (unless (and (0 . <= . i) (i . < . (length ts)))
  10444. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10445. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10446. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10447. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10448. (define-values (e-vec t-vec) (recur e1))
  10449. (define-values (e-arg^ t-arg) (recur arg))
  10450. (match t-vec
  10451. [`(Vector ,ts ...)
  10452. (unless (and (0 . <= . i) (i . < . (length ts)))
  10453. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10454. (check-type-equal? (list-ref ts i) t-arg e)
  10455. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10456. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10457. [(Prim 'vector-length (list e))
  10458. (define-values (e^ t) (recur e))
  10459. (match t
  10460. [`(Vector ,ts ...)
  10461. (values (Prim 'vector-length (list e^)) 'Integer)]
  10462. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10463. [(Prim 'eq? (list arg1 arg2))
  10464. (define-values (e1 t1) (recur arg1))
  10465. (define-values (e2 t2) (recur arg2))
  10466. (match* (t1 t2)
  10467. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10468. [(other wise) (check-type-equal? t1 t2 e)])
  10469. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10470. [(HasType (Prim 'vector es) t)
  10471. ((type-check-exp env) (Prim 'vector es))]
  10472. [(HasType e1 t)
  10473. (define-values (e1^ t^) (recur e1))
  10474. (check-type-equal? t t^ e)
  10475. (values (HasType e1^ t) t)]
  10476. [else ((super type-check-exp env) e)]
  10477. )))
  10478. ))
  10479. (define (type-check-Lvec p)
  10480. (send (new type-check-Lvec-class) type-check-program p))
  10481. \end{lstlisting}
  10482. \fi}
  10483. {\if\edition\pythonEd
  10484. \begin{lstlisting}
  10485. class TypeCheckLtup(TypeCheckLwhile):
  10486. def type_check_exp(self, e, env):
  10487. match e:
  10488. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10489. l = self.type_check_exp(left, env)
  10490. r = self.type_check_exp(right, env)
  10491. check_type_equal(l, r, e)
  10492. return bool
  10493. case Tuple(es, Load()):
  10494. ts = [self.type_check_exp(e, env) for e in es]
  10495. e.has_type = tuple(ts)
  10496. return e.has_type
  10497. case Subscript(tup, Constant(index), Load()):
  10498. tup_ty = self.type_check_exp(tup, env)
  10499. index_ty = self.type_check_exp(Constant(index), env)
  10500. check_type_equal(index_ty, int, index)
  10501. match tup_ty:
  10502. case tuple(ts):
  10503. return ts[index]
  10504. case _:
  10505. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10506. case _:
  10507. return super().type_check_exp(e, env)
  10508. \end{lstlisting}
  10509. \fi}
  10510. \caption{Type checker for the \LangVec{} language.}
  10511. \label{fig:type-check-Lvec}
  10512. \end{figure}
  10513. \section{Garbage Collection}
  10514. \label{sec:GC}
  10515. Garbage collection is a runtime technique for reclaiming space on the
  10516. heap that will not be used in the future of the running program. We
  10517. use the term \emph{object}\index{subject}{object} to refer to any
  10518. value that is stored in the heap, which for now only includes
  10519. tuples.%
  10520. %
  10521. \footnote{The term ``object'' as it is used in the context of
  10522. object-oriented programming has a more specific meaning than how we
  10523. are using the term here.}
  10524. %
  10525. Unfortunately, it is impossible to know precisely which objects will
  10526. be accessed in the future and which will not. Instead, garbage
  10527. collectors over approximate the set of objects that will be accessed by
  10528. identifying which objects can possibly be accessed. The running
  10529. program can directly access objects that are in registers and on the
  10530. procedure call stack. It can also transitively access the elements of
  10531. tuples, starting with a tuple whose address is in a register or on the
  10532. procedure call stack. We define the \emph{root
  10533. set}\index{subject}{root set} to be all the tuple addresses that are
  10534. in registers or on the procedure call stack. We define the \emph{live
  10535. objects}\index{subject}{live objects} to be the objects that are
  10536. reachable from the root set. Garbage collectors reclaim the space that
  10537. is allocated to objects that are no longer live. That means that some
  10538. objects may not get reclaimed as soon as they could be, but at least
  10539. garbage collectors do not reclaim the space dedicated to objects that
  10540. will be accessed in the future! The programmer can influence which
  10541. objects get reclaimed by causing them to become unreachable.
  10542. So the goal of the garbage collector is twofold:
  10543. \begin{enumerate}
  10544. \item preserve all the live objects, and
  10545. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10546. \end{enumerate}
  10547. \subsection{Two-Space Copying Collector}
  10548. Here we study a relatively simple algorithm for garbage collection
  10549. that is the basis of many state-of-the-art garbage
  10550. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10551. particular, we describe a two-space copying
  10552. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10553. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10554. collector} \index{subject}{two-space copying collector}
  10555. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10556. what happens in a two-space collector, showing two time steps, prior
  10557. to garbage collection (on the top) and after garbage collection (on
  10558. the bottom). In a two-space collector, the heap is divided into two
  10559. parts named the FromSpace\index{subject}{FromSpace} and the
  10560. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10561. FromSpace until there is not enough room for the next allocation
  10562. request. At that point, the garbage collector goes to work to make
  10563. room for the next allocation.
  10564. A copying collector makes more room by copying all of the live objects
  10565. from the FromSpace into the ToSpace and then performs a sleight of
  10566. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10567. as the new ToSpace. In the example of
  10568. Figure~\ref{fig:copying-collector}, the root set consists of three
  10569. pointers, one in a register and two on the stack. All of the live
  10570. objects have been copied to the ToSpace (the right-hand side of
  10571. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10572. pointer relationships. For example, the pointer in the register still
  10573. points to a tuple that in turn points to two other tuples. There are
  10574. four tuples that are not reachable from the root set and therefore do
  10575. not get copied into the ToSpace.
  10576. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10577. created by a well-typed program in \LangVec{} because it contains a
  10578. cycle. However, creating cycles will be possible once we get to
  10579. \LangDyn{} (Chapter~\ref{ch:Ldyn}). We design the garbage collector
  10580. to deal with cycles to begin with so we will not need to revisit this
  10581. issue.
  10582. \begin{figure}[tbp]
  10583. \centering
  10584. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10585. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10586. \\[5ex]
  10587. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10588. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10589. \caption{A copying collector in action.}
  10590. \label{fig:copying-collector}
  10591. \end{figure}
  10592. \subsection{Graph Copying via Cheney's Algorithm}
  10593. \label{sec:cheney}
  10594. \index{subject}{Cheney's algorithm}
  10595. Let us take a closer look at the copying of the live objects. The
  10596. allocated objects and pointers can be viewed as a graph and we need to
  10597. copy the part of the graph that is reachable from the root set. To
  10598. make sure we copy all of the reachable vertices in the graph, we need
  10599. an exhaustive graph traversal algorithm, such as depth-first search or
  10600. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10601. such algorithms take into account the possibility of cycles by marking
  10602. which vertices have already been visited, so as to ensure termination
  10603. of the algorithm. These search algorithms also use a data structure
  10604. such as a stack or queue as a to-do list to keep track of the vertices
  10605. that need to be visited. We use breadth-first search and a trick
  10606. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10607. and copying tuples into the ToSpace.
  10608. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10609. copy progresses. The queue is represented by a chunk of contiguous
  10610. memory at the beginning of the ToSpace, using two pointers to track
  10611. the front and the back of the queue, called the \emph{free pointer}
  10612. and the \emph{scan pointer} respectively. The algorithm starts by
  10613. copying all tuples that are immediately reachable from the root set
  10614. into the ToSpace to form the initial queue. When we copy a tuple, we
  10615. mark the old tuple to indicate that it has been visited. We discuss
  10616. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10617. that any pointers inside the copied tuples in the queue still point
  10618. back to the FromSpace. Once the initial queue has been created, the
  10619. algorithm enters a loop in which it repeatedly processes the tuple at
  10620. the front of the queue and pops it off the queue. To process a tuple,
  10621. the algorithm copies all the objects that are directly reachable from it
  10622. to the ToSpace, placing them at the back of the queue. The algorithm
  10623. then updates the pointers in the popped tuple so they point to the
  10624. newly copied objects.
  10625. \begin{figure}[tbp]
  10626. \centering
  10627. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10628. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10629. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10630. \label{fig:cheney}
  10631. \end{figure}
  10632. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10633. tuple whose second element is $42$ to the back of the queue. The other
  10634. pointer goes to a tuple that has already been copied, so we do not
  10635. need to copy it again, but we do need to update the pointer to the new
  10636. location. This can be accomplished by storing a \emph{forwarding
  10637. pointer}\index{subject}{forwarding pointer} to the new location in the
  10638. old tuple, back when we initially copied the tuple into the
  10639. ToSpace. This completes one step of the algorithm. The algorithm
  10640. continues in this way until the queue is empty, that is, when the scan
  10641. pointer catches up with the free pointer.
  10642. \subsection{Data Representation}
  10643. \label{sec:data-rep-gc}
  10644. The garbage collector places some requirements on the data
  10645. representations used by our compiler. First, the garbage collector
  10646. needs to distinguish between pointers and other kinds of data such as
  10647. integers. There are several ways to accomplish this.
  10648. \begin{enumerate}
  10649. \item Attached a tag to each object that identifies what type of
  10650. object it is~\citep{McCarthy:1960dz}.
  10651. \item Store different types of objects in different
  10652. regions~\citep{Steele:1977ab}.
  10653. \item Use type information from the program to either (a) generate
  10654. type-specific code for collecting or (b) generate tables that
  10655. guide the collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10656. \end{enumerate}
  10657. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10658. need to tag objects anyways, so option 1 is a natural choice for those
  10659. languages. However, \LangVec{} is a statically typed language, so it
  10660. would be unfortunate to require tags on every object, especially small
  10661. and pervasive objects like integers and Booleans. Option 3 is the
  10662. best-performing choice for statically typed languages, but comes with
  10663. a relatively high implementation complexity. To keep this chapter
  10664. within a reasonable time budget, we recommend a combination of options
  10665. 1 and 2, using separate strategies for the stack and the heap.
  10666. Regarding the stack, we recommend using a separate stack for pointers,
  10667. which we call the \emph{root stack}\index{subject}{root stack}
  10668. (a.k.a. ``shadow
  10669. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10670. is, when a local variable needs to be spilled and is of type
  10671. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10672. root stack instead of putting it on the procedure call
  10673. stack. Furthermore, we always spill tuple-typed variables if they are
  10674. live during a call to the collector, thereby ensuring that no pointers
  10675. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10676. reproduces the example from Figure~\ref{fig:copying-collector} and
  10677. contrasts it with the data layout using a root stack. The root stack
  10678. contains the two pointers from the regular stack and also the pointer
  10679. in the second register.
  10680. \begin{figure}[tbp]
  10681. \centering
  10682. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10683. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10684. \caption{Maintaining a root stack to facilitate garbage collection.}
  10685. \label{fig:shadow-stack}
  10686. \end{figure}
  10687. The problem of distinguishing between pointers and other kinds of data
  10688. also arises inside of each tuple on the heap. We solve this problem by
  10689. attaching a tag, an extra 64-bits, to each
  10690. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10691. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10692. that we have drawn the bits in a big-endian way, from right-to-left,
  10693. with bit location 0 (the least significant bit) on the far right,
  10694. which corresponds to the direction of the x86 shifting instructions
  10695. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10696. is dedicated to specifying which elements of the tuple are pointers,
  10697. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10698. indicates there is a pointer and a 0 bit indicates some other kind of
  10699. data. The pointer mask starts at bit location 7. We limit tuples to a
  10700. maximum size of 50 elements, so we just need 50 bits for the pointer
  10701. mask.%
  10702. %
  10703. \footnote{A production-quality compiler would handle
  10704. arbitrary-sized tuples and use a more complex approach.}
  10705. %
  10706. The tag also contains two other pieces of information. The length of
  10707. the tuple (number of elements) is stored in bits location 1 through
  10708. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10709. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10710. has not yet been copied. If the bit has value 0 then the entire tag
  10711. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10712. zero anyways because our tuples are 8-byte aligned.)
  10713. \begin{figure}[tbp]
  10714. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10715. \caption{Representation of tuples in the heap.}
  10716. \label{fig:tuple-rep}
  10717. \end{figure}
  10718. \subsection{Implementation of the Garbage Collector}
  10719. \label{sec:organize-gz}
  10720. \index{subject}{prelude}
  10721. An implementation of the copying collector is provided in the
  10722. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10723. interface to the garbage collector that is used by the compiler. The
  10724. \code{initialize} function creates the FromSpace, ToSpace, and root
  10725. stack and should be called in the prelude of the \code{main}
  10726. function. The arguments of \code{initialize} are the root stack size
  10727. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10728. good choice for both. The \code{initialize} function puts the address
  10729. of the beginning of the FromSpace into the global variable
  10730. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10731. the address that is 1-past the last element of the FromSpace. We use
  10732. half-open intervals to represent chunks of
  10733. memory~\citep{Dijkstra:1982aa}. The \code{rootstack\_begin} variable
  10734. points to the first element of the root stack.
  10735. As long as there is room left in the FromSpace, your generated code
  10736. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10737. %
  10738. The amount of room left in the FromSpace is the difference between the
  10739. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10740. function should be called when there is not enough room left in the
  10741. FromSpace for the next allocation. The \code{collect} function takes
  10742. a pointer to the current top of the root stack (one past the last item
  10743. that was pushed) and the number of bytes that need to be
  10744. allocated. The \code{collect} function performs the copying collection
  10745. and leaves the heap in a state such that there is enough room for the
  10746. next allocation.
  10747. \begin{figure}[tbp]
  10748. \begin{lstlisting}
  10749. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10750. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10751. int64_t* free_ptr;
  10752. int64_t* fromspace_begin;
  10753. int64_t* fromspace_end;
  10754. int64_t** rootstack_begin;
  10755. \end{lstlisting}
  10756. \caption{The compiler's interface to the garbage collector.}
  10757. \label{fig:gc-header}
  10758. \end{figure}
  10759. %% \begin{exercise}
  10760. %% In the file \code{runtime.c} you will find the implementation of
  10761. %% \code{initialize} and a partial implementation of \code{collect}.
  10762. %% The \code{collect} function calls another function, \code{cheney},
  10763. %% to perform the actual copy, and that function is left to the reader
  10764. %% to implement. The following is the prototype for \code{cheney}.
  10765. %% \begin{lstlisting}
  10766. %% static void cheney(int64_t** rootstack_ptr);
  10767. %% \end{lstlisting}
  10768. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10769. %% rootstack (which is an array of pointers). The \code{cheney} function
  10770. %% also communicates with \code{collect} through the global
  10771. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10772. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10773. %% the ToSpace:
  10774. %% \begin{lstlisting}
  10775. %% static int64_t* tospace_begin;
  10776. %% static int64_t* tospace_end;
  10777. %% \end{lstlisting}
  10778. %% The job of the \code{cheney} function is to copy all the live
  10779. %% objects (reachable from the root stack) into the ToSpace, update
  10780. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10781. %% update the root stack so that it points to the objects in the
  10782. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10783. %% and ToSpace.
  10784. %% \end{exercise}
  10785. The introduction of garbage collection has a non-trivial impact on our
  10786. compiler passes. We introduce a new compiler pass named
  10787. \code{expose\_allocation} that elaborates the code for allocating
  10788. tuples. We also make significant changes to
  10789. \code{select\_instructions}, \code{build\_interference},
  10790. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10791. make minor changes in several more passes.
  10792. The following program will serve as our running example. It creates
  10793. two tuples, one nested inside the other. Both tuples have length
  10794. one. The program accesses the element in the inner tuple.
  10795. % tests/vectors_test_17.rkt
  10796. {\if\edition\racketEd
  10797. \begin{lstlisting}
  10798. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10799. \end{lstlisting}
  10800. \fi}
  10801. {\if\edition\pythonEd
  10802. \begin{lstlisting}
  10803. print( ((42,),)[0][0] )
  10804. \end{lstlisting}
  10805. \fi}
  10806. {\if\edition\racketEd
  10807. \section{Shrink}
  10808. \label{sec:shrink-Lvec}
  10809. Recall that the \code{shrink} pass translates the primitives operators
  10810. into a smaller set of primitives.
  10811. %
  10812. This pass comes after type checking and the type checker adds a
  10813. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10814. need to add a case for \code{HasType} to the \code{shrink} pass.
  10815. \fi}
  10816. \section{Expose Allocation}
  10817. \label{sec:expose-allocation}
  10818. The pass \code{expose\_allocation} lowers tuple creation into a
  10819. conditional call to the collector followed by allocating the
  10820. appropriate amount of memory and initializing it. We choose to place
  10821. the \code{expose\_allocation} pass before
  10822. \code{remove\_complex\_operands} because it generates
  10823. code that contains complex operands.
  10824. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10825. replaces tuple creation with new lower-level forms that we use in the
  10826. translation of tuple creation.
  10827. %
  10828. {\if\edition\racketEd
  10829. \[
  10830. \begin{array}{lcl}
  10831. \Exp &::=& \cdots
  10832. \MID (\key{collect} \,\itm{int})
  10833. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10834. \MID (\key{global-value} \,\itm{name})
  10835. \end{array}
  10836. \]
  10837. \fi}
  10838. {\if\edition\pythonEd
  10839. \[
  10840. \begin{array}{lcl}
  10841. \Exp &::=& \cdots\\
  10842. &\MID& \key{collect}(\itm{int})
  10843. \MID \key{allocate}(\itm{int},\itm{type})
  10844. \MID \key{global\_value}(\itm{name}) \\
  10845. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10846. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10847. \end{array}
  10848. \]
  10849. \fi}
  10850. %
  10851. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10852. make sure that there are $n$ bytes ready to be allocated. During
  10853. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10854. the \code{collect} function in \code{runtime.c}.
  10855. %
  10856. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10857. space at the front for the 64 bit tag), but the elements are not
  10858. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10859. of the tuple:
  10860. %
  10861. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10862. %
  10863. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10864. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10865. as \code{free\_ptr}.
  10866. %
  10867. \python{The \code{begin} form is an expression that executes a
  10868. sequence of statements and then produces the value of the expression
  10869. at the end.}
  10870. The following shows the transformation of tuple creation into 1) a
  10871. sequence of temporary variable bindings for the initializing
  10872. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10873. \code{allocate}, and 4) the initialization of the tuple. The
  10874. \itm{len} placeholder refers to the length of the tuple and
  10875. \itm{bytes} is how many total bytes need to be allocated for the
  10876. tuple, which is 8 for the tag plus \itm{len} times 8.
  10877. %
  10878. \python{The \itm{type} needed for the second argument of the
  10879. \code{allocate} form can be obtained from the \code{has\_type} field
  10880. of the tuple AST node, which is stored there by running the type
  10881. checker for \LangVec{} immediately before this pass.}
  10882. %
  10883. \begin{center}
  10884. \begin{minipage}{\textwidth}
  10885. {\if\edition\racketEd
  10886. \begin{lstlisting}
  10887. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10888. |$\Longrightarrow$|
  10889. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10890. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10891. (global-value fromspace_end))
  10892. (void)
  10893. (collect |\itm{bytes}|))])
  10894. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10895. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10896. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10897. |$v$|) ... )))) ...)
  10898. \end{lstlisting}
  10899. \fi}
  10900. {\if\edition\pythonEd
  10901. \begin{lstlisting}
  10902. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10903. |$\Longrightarrow$|
  10904. begin:
  10905. |$x_0$| = |$e_0$|
  10906. |$\vdots$|
  10907. |$x_{n-1}$| = |$e_{n-1}$|
  10908. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10909. 0
  10910. else:
  10911. collect(|\itm{bytes}|)
  10912. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10913. |$v$|[0] = |$x_0$|
  10914. |$\vdots$|
  10915. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10916. |$v$|
  10917. \end{lstlisting}
  10918. \fi}
  10919. \end{minipage}
  10920. \end{center}
  10921. %
  10922. \noindent The sequencing of the initializing expressions
  10923. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10924. they may trigger garbage collection and we cannot have an allocated
  10925. but uninitialized tuple on the heap during a collection.
  10926. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10927. \code{expose\_allocation} pass on our running example.
  10928. \begin{figure}[tbp]
  10929. % tests/s2_17.rkt
  10930. {\if\edition\racketEd
  10931. \begin{lstlisting}
  10932. (vector-ref
  10933. (vector-ref
  10934. (let ([vecinit6
  10935. (let ([_4 (if (< (+ (global-value free_ptr) 16)
  10936. (global-value fromspace_end))
  10937. (void)
  10938. (collect 16))])
  10939. (let ([alloc2 (allocate 1 (Vector Integer))])
  10940. (let ([_3 (vector-set! alloc2 0 42)])
  10941. alloc2)))])
  10942. (let ([_8 (if (< (+ (global-value free_ptr) 16)
  10943. (global-value fromspace_end))
  10944. (void)
  10945. (collect 16))])
  10946. (let ([alloc5 (allocate 1 (Vector (Vector Integer)))])
  10947. (let ([_7 (vector-set! alloc5 0 vecinit6)])
  10948. alloc5))))
  10949. 0)
  10950. 0)
  10951. \end{lstlisting}
  10952. \fi}
  10953. {\if\edition\pythonEd
  10954. \begin{lstlisting}
  10955. print( |$T_1$|[0][0] )
  10956. \end{lstlisting}
  10957. where $T_1$ is
  10958. \begin{lstlisting}
  10959. begin:
  10960. tmp.1 = |$T_2$|
  10961. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10962. 0
  10963. else:
  10964. collect(16)
  10965. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10966. tmp.2[0] = tmp.1
  10967. tmp.2
  10968. \end{lstlisting}
  10969. and $T_2$ is
  10970. \begin{lstlisting}
  10971. begin:
  10972. tmp.3 = 42
  10973. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10974. 0
  10975. else:
  10976. collect(16)
  10977. tmp.4 = allocate(1, TupleType([int]))
  10978. tmp.4[0] = tmp.3
  10979. tmp.4
  10980. \end{lstlisting}
  10981. \fi}
  10982. \caption{Output of the \code{expose\_allocation} pass.}
  10983. \label{fig:expose-alloc-output}
  10984. \end{figure}
  10985. \section{Remove Complex Operands}
  10986. \label{sec:remove-complex-opera-Lvec}
  10987. {\if\edition\racketEd
  10988. %
  10989. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10990. should be treated as complex operands.
  10991. %
  10992. \fi}
  10993. %
  10994. {\if\edition\pythonEd
  10995. %
  10996. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10997. and tuple access should be treated as complex operands. The
  10998. sub-expressions of tuple access must be atomic.
  10999. %
  11000. \fi}
  11001. %% A new case for
  11002. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  11003. %% handled carefully to prevent the \code{Prim} node from being separated
  11004. %% from its enclosing \code{HasType}.
  11005. Figure~\ref{fig:Lvec-anf-syntax}
  11006. shows the grammar for the output language \LangAllocANF{} of this
  11007. pass, which is \LangAlloc{} in monadic normal form.
  11008. \newcommand{\LtupMonadASTRacket}{
  11009. \begin{array}{rcl}
  11010. \Exp &::=& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  11011. \MID \GLOBALVALUE{\Var}
  11012. \end{array}
  11013. }
  11014. \newcommand{\LtupMonadASTPython}{
  11015. \begin{array}{rcl}
  11016. \Exp &::=& \GET{\Atm}{\Atm} \\
  11017. &\MID& \LEN{\Atm}\\
  11018. &\MID& \ALLOCATE{\Int}{\Type}
  11019. \MID \GLOBALVALUE{\Var} \\
  11020. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  11021. &\MID& \COLLECT{\Int}
  11022. \end{array}
  11023. }
  11024. \begin{figure}[tp]
  11025. \centering
  11026. \fbox{
  11027. \begin{minipage}{0.96\textwidth}
  11028. \small
  11029. {\if\edition\racketEd
  11030. \[
  11031. \begin{array}{l}
  11032. \gray{\LvarMonadASTRacket} \\ \hline
  11033. \gray{\LifMonadASTRacket} \\ \hline
  11034. \gray{\LwhileMonadASTRacket} \\ \hline
  11035. \LtupMonadASTRacket \\
  11036. \begin{array}{rcl}
  11037. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  11038. \end{array}
  11039. \end{array}
  11040. \]
  11041. \fi}
  11042. {\if\edition\pythonEd
  11043. \[
  11044. \begin{array}{l}
  11045. \gray{\LvarMonadASTPython} \\ \hline
  11046. \gray{\LifMonadASTPython} \\ \hline
  11047. \gray{\LwhileMonadASTPython} \\ \hline
  11048. \LtupMonadASTPython \\
  11049. \begin{array}{rcl}
  11050. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11051. \end{array}
  11052. \end{array}
  11053. %% \begin{array}{lcl}
  11054. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  11055. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  11056. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  11057. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  11058. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  11059. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  11060. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  11061. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  11062. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  11063. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  11064. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  11065. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  11066. %% &\MID& \GET{\Atm}{\Atm} \\
  11067. %% &\MID& \LEN{\Exp}\\
  11068. %% &\MID& \ALLOCATE{\Int}{\Type}
  11069. %% \MID \GLOBALVALUE{\Var}\RP\\
  11070. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  11071. %% % why have \LET?
  11072. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  11073. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  11074. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  11075. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  11076. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  11077. %% \MID \COLLECT{\Int} \\
  11078. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  11079. %% \end{array}
  11080. \]
  11081. \fi}
  11082. \end{minipage}
  11083. }
  11084. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11085. \label{fig:Lvec-anf-syntax}
  11086. \end{figure}
  11087. \section{Explicate Control and the \LangCVec{} language}
  11088. \label{sec:explicate-control-r3}
  11089. \newcommand{\CtupASTRacket}{
  11090. \begin{array}{lcl}
  11091. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11092. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11093. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11094. &\MID& \VECLEN{\Atm} \\
  11095. &\MID& \GLOBALVALUE{\Var} \\
  11096. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11097. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11098. \end{array}
  11099. }
  11100. \newcommand{\CtupASTPython}{
  11101. \begin{array}{lcl}
  11102. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11103. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11104. \Stmt &::=& \COLLECT{\Int} \\
  11105. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11106. \end{array}
  11107. }
  11108. \begin{figure}[tp]
  11109. \fbox{
  11110. \begin{minipage}{0.96\textwidth}
  11111. \small
  11112. {\if\edition\racketEd
  11113. \[
  11114. \begin{array}{l}
  11115. \gray{\CvarASTRacket} \\ \hline
  11116. \gray{\CifASTRacket} \\ \hline
  11117. \gray{\CloopASTRacket} \\ \hline
  11118. \CtupASTRacket \\
  11119. \begin{array}{lcl}
  11120. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11121. \end{array}
  11122. \end{array}
  11123. \]
  11124. \fi}
  11125. {\if\edition\pythonEd
  11126. \[
  11127. \begin{array}{l}
  11128. \gray{\CifASTPython} \\ \hline
  11129. \CtupASTPython \\
  11130. \begin{array}{lcl}
  11131. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11132. \end{array}
  11133. \end{array}
  11134. \]
  11135. \fi}
  11136. \end{minipage}
  11137. }
  11138. \caption{The abstract syntax of \LangCVec{}, extending
  11139. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11140. (Figure~\ref{fig:c1-syntax})}.}
  11141. \label{fig:c2-syntax}
  11142. \end{figure}
  11143. The output of \code{explicate\_control} is a program in the
  11144. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11145. Figure~\ref{fig:c2-syntax}.
  11146. %
  11147. %% \racket{(The concrete syntax is defined in
  11148. %% Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11149. %
  11150. The new expressions of \LangCVec{} include \key{allocate},
  11151. %
  11152. \racket{\key{vector-ref}, and \key{vector-set!},}
  11153. %
  11154. \python{accessing tuple elements,}
  11155. %
  11156. and \key{global\_value}.
  11157. %
  11158. \python{\LangCVec{} also includes the \code{collect} statement and
  11159. assignment to a tuple element.}
  11160. %
  11161. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11162. %
  11163. The \code{explicate\_control} pass can treat these new forms much like
  11164. the other forms that we've already encountered. The output of the
  11165. \code{explicate\_control} pass on the running example is shown on the
  11166. left-side of Figure~\ref{fig:select-instr-output-gc} in the next
  11167. section.
  11168. \section{Select Instructions and the \LangXGlobal{} Language}
  11169. \label{sec:select-instructions-gc}
  11170. \index{subject}{instruction selection}
  11171. %% void (rep as zero)
  11172. %% allocate
  11173. %% collect (callq collect)
  11174. %% vector-ref
  11175. %% vector-set!
  11176. %% vector-length
  11177. %% global (postpone)
  11178. In this pass we generate x86 code for most of the new operations that
  11179. were needed to compile tuples, including \code{Allocate},
  11180. \code{Collect}, and accessing tuple elements.
  11181. %
  11182. We compile \code{GlobalValue} to \code{Global} because the later has a
  11183. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11184. \ref{fig:x86-2}). \index{subject}{x86}
  11185. The tuple read and write forms translate into \code{movq}
  11186. instructions. (The $+1$ in the offset is to move past the tag at the
  11187. beginning of the tuple representation.)
  11188. %
  11189. \begin{center}
  11190. \begin{minipage}{\textwidth}
  11191. {\if\edition\racketEd
  11192. \begin{lstlisting}
  11193. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11194. |$\Longrightarrow$|
  11195. movq |$\itm{tup}'$|, %r11
  11196. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11197. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11198. |$\Longrightarrow$|
  11199. movq |$\itm{tup}'$|, %r11
  11200. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11201. movq $0, |$\itm{lhs'}$|
  11202. \end{lstlisting}
  11203. \fi}
  11204. {\if\edition\pythonEd
  11205. \begin{lstlisting}
  11206. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11207. |$\Longrightarrow$|
  11208. movq |$\itm{tup}'$|, %r11
  11209. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11210. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11211. |$\Longrightarrow$|
  11212. movq |$\itm{tup}'$|, %r11
  11213. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11214. \end{lstlisting}
  11215. \fi}
  11216. \end{minipage}
  11217. \end{center}
  11218. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11219. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11220. are obtained by translating from \LangCVec{} to x86.
  11221. %
  11222. The move of $\itm{tup}'$ to
  11223. register \code{r11} ensures that offset expression
  11224. \code{$8(n+1)$(\%r11)} contains a register operand. This requires
  11225. removing \code{r11} from consideration by the register allocating.
  11226. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11227. \code{rax}. Then the generated code for tuple assignment would be
  11228. \begin{lstlisting}
  11229. movq |$\itm{tup}'$|, %rax
  11230. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11231. \end{lstlisting}
  11232. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11233. \code{patch\_instructions} would insert a move through \code{rax}
  11234. as follows.
  11235. \begin{lstlisting}
  11236. movq |$\itm{tup}'$|, %rax
  11237. movq |$\itm{rhs}'$|, %rax
  11238. movq %rax, |$8(n+1)$|(%rax)
  11239. \end{lstlisting}
  11240. But the above sequence of instructions does not work because we're
  11241. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11242. $\itm{rhs}'$) at the same time!
  11243. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11244. be translated into a sequence of instructions that read the tag of the
  11245. tuple and extract the six bits that represent the tuple length, which
  11246. are the bits starting at index 1 and going up to and including bit 6.
  11247. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11248. (shift right) can be used to accomplish this.
  11249. We compile the \code{allocate} form to operations on the
  11250. \code{free\_ptr}, as shown below. This approach is called
  11251. \emph{inline allocation} as it implements allocation without a
  11252. function call, by simply bumping the allocation pointer. It is much
  11253. more efficient than calling a function for each allocation. The
  11254. address in the \code{free\_ptr} is the next free address in the
  11255. FromSpace, so we copy it into \code{r11} and then move it forward by
  11256. enough space for the tuple being allocated, which is $8(\itm{len}+1)$
  11257. bytes because each element is 8 bytes (64 bits) and we use 8 bytes for
  11258. the tag. We then initialize the \itm{tag} and finally copy the
  11259. address in \code{r11} to the left-hand-side. Refer to
  11260. Figure~\ref{fig:tuple-rep} to see how the tag is organized.
  11261. %
  11262. \racket{We recommend using the Racket operations
  11263. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11264. during compilation.}
  11265. %
  11266. \python{We recommend using the bitwise-or operator \code{|} and the
  11267. shift-left operator \code{<<} to compute the tag during
  11268. compilation.}
  11269. %
  11270. The type annotation in the \code{allocate} form is used to determine
  11271. the pointer mask region of the tag.
  11272. %
  11273. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11274. address of the \code{free\_ptr} global variable but uses a special
  11275. instruction-pointer relative addressing mode of the x86-64 processor.
  11276. In particular, the assembler computes the distance $d$ between the
  11277. address of \code{free\_ptr} and where the \code{rip} would be at that
  11278. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11279. \code{$d$(\%rip)}, which at runtime will compute the address of
  11280. \code{free\_ptr}.
  11281. %
  11282. {\if\edition\racketEd
  11283. \begin{lstlisting}
  11284. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11285. |$\Longrightarrow$|
  11286. movq free_ptr(%rip), %r11
  11287. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11288. movq $|$\itm{tag}$|, 0(%r11)
  11289. movq %r11, |$\itm{lhs}'$|
  11290. \end{lstlisting}
  11291. \fi}
  11292. {\if\edition\pythonEd
  11293. \begin{lstlisting}
  11294. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11295. |$\Longrightarrow$|
  11296. movq free_ptr(%rip), %r11
  11297. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11298. movq $|$\itm{tag}$|, 0(%r11)
  11299. movq %r11, |$\itm{lhs}'$|
  11300. \end{lstlisting}
  11301. \fi}
  11302. The \code{collect} form is compiled to a call to the \code{collect}
  11303. function in the runtime. The arguments to \code{collect} are 1) the
  11304. top of the root stack and 2) the number of bytes that need to be
  11305. allocated. We use another dedicated register, \code{r15}, to
  11306. store the pointer to the top of the root stack. So \code{r15} is not
  11307. available for use by the register allocator.
  11308. {\if\edition\racketEd
  11309. \begin{lstlisting}
  11310. (collect |$\itm{bytes}$|)
  11311. |$\Longrightarrow$|
  11312. movq %r15, %rdi
  11313. movq $|\itm{bytes}|, %rsi
  11314. callq collect
  11315. \end{lstlisting}
  11316. \fi}
  11317. {\if\edition\pythonEd
  11318. \begin{lstlisting}
  11319. collect(|$\itm{bytes}$|)
  11320. |$\Longrightarrow$|
  11321. movq %r15, %rdi
  11322. movq $|\itm{bytes}|, %rsi
  11323. callq collect
  11324. \end{lstlisting}
  11325. \fi}
  11326. \newcommand{\GrammarXGlobal}{
  11327. \begin{array}{lcl}
  11328. \Arg &::=& \itm{label} \key{(\%rip)}
  11329. \end{array}
  11330. }
  11331. \newcommand{\ASTXGlobalRacket}{
  11332. \begin{array}{lcl}
  11333. \Arg &::=& \GLOBAL{\itm{label}}
  11334. \end{array}
  11335. }
  11336. \begin{figure}[tp]
  11337. \fbox{
  11338. \begin{minipage}{0.96\textwidth}
  11339. \[
  11340. \begin{array}{l}
  11341. \gray{\GrammarXInt} \\ \hline
  11342. \gray{\GrammarXIf} \\ \hline
  11343. \GrammarXGlobal \\
  11344. \begin{array}{lcl}
  11345. \LangXGlobalM{} &::= & \key{.globl main} \\
  11346. & & \key{main:} \; \Instr^{*}
  11347. \end{array}
  11348. \end{array}
  11349. \]
  11350. \end{minipage}
  11351. }
  11352. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11353. \label{fig:x86-2-concrete}
  11354. \end{figure}
  11355. \begin{figure}[tp]
  11356. \fbox{
  11357. \begin{minipage}{0.96\textwidth}
  11358. \small
  11359. \[
  11360. \begin{array}{l}
  11361. \gray{\ASTXIntRacket} \\ \hline
  11362. \gray{\ASTXIfRacket} \\ \hline
  11363. \ASTXGlobalRacket \\
  11364. \begin{array}{lcl}
  11365. \LangXGlobalM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  11366. \end{array}
  11367. \end{array}
  11368. \]
  11369. \end{minipage}
  11370. }
  11371. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11372. \label{fig:x86-2}
  11373. \end{figure}
  11374. The concrete and abstract syntax of the \LangXGlobal{} language is
  11375. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11376. differs from \LangXIf{} just in the addition of global variables.
  11377. %
  11378. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11379. \code{select\_instructions} pass on the running example.
  11380. \begin{figure}[tbp]
  11381. \centering
  11382. % tests/s2_17.rkt
  11383. \begin{tabular}{lll}
  11384. \begin{minipage}{0.5\textwidth}
  11385. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11386. start:
  11387. tmp9 = (global-value free_ptr);
  11388. tmp0 = (+ tmp9 16);
  11389. tmp1 = (global-value fromspace_end);
  11390. if (< tmp0 tmp1)
  11391. goto block0;
  11392. else
  11393. goto block1;
  11394. block0:
  11395. _4 = (void);
  11396. goto block9;
  11397. block1:
  11398. (collect 16)
  11399. goto block9;
  11400. block9:
  11401. alloc2 = (allocate 1 (Vector Integer));
  11402. _3 = (vector-set! alloc2 0 42);
  11403. vecinit6 = alloc2;
  11404. tmp2 = (global-value free_ptr);
  11405. tmp3 = (+ tmp2 16);
  11406. tmp4 = (global-value fromspace_end);
  11407. if (< tmp3 tmp4)
  11408. goto block7;
  11409. else
  11410. goto block8;
  11411. block7:
  11412. _8 = (void);
  11413. goto block6;
  11414. block8:
  11415. (collect 16)
  11416. goto block6;
  11417. block6:
  11418. alloc5 = (allocate 1 (Vector (Vector Integer)));
  11419. _7 = (vector-set! alloc5 0 vecinit6);
  11420. tmp5 = (vector-ref alloc5 0);
  11421. return (vector-ref tmp5 0);
  11422. \end{lstlisting}
  11423. \end{minipage}
  11424. &$\Rightarrow$&
  11425. \begin{minipage}{0.4\textwidth}
  11426. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11427. start:
  11428. movq free_ptr(%rip), tmp9
  11429. movq tmp9, tmp0
  11430. addq $16, tmp0
  11431. movq fromspace_end(%rip), tmp1
  11432. cmpq tmp1, tmp0
  11433. jl block0
  11434. jmp block1
  11435. block0:
  11436. movq $0, _4
  11437. jmp block9
  11438. block1:
  11439. movq %r15, %rdi
  11440. movq $16, %rsi
  11441. callq collect
  11442. jmp block9
  11443. block9:
  11444. movq free_ptr(%rip), %r11
  11445. addq $16, free_ptr(%rip)
  11446. movq $3, 0(%r11)
  11447. movq %r11, alloc2
  11448. movq alloc2, %r11
  11449. movq $42, 8(%r11)
  11450. movq $0, _3
  11451. movq alloc2, vecinit6
  11452. movq free_ptr(%rip), tmp2
  11453. movq tmp2, tmp3
  11454. addq $16, tmp3
  11455. movq fromspace_end(%rip), tmp4
  11456. cmpq tmp4, tmp3
  11457. jl block7
  11458. jmp block8
  11459. block7:
  11460. movq $0, _8
  11461. jmp block6
  11462. block8:
  11463. movq %r15, %rdi
  11464. movq $16, %rsi
  11465. callq collect
  11466. jmp block6
  11467. block6:
  11468. movq free_ptr(%rip), %r11
  11469. addq $16, free_ptr(%rip)
  11470. movq $131, 0(%r11)
  11471. movq %r11, alloc5
  11472. movq alloc5, %r11
  11473. movq vecinit6, 8(%r11)
  11474. movq $0, _7
  11475. movq alloc5, %r11
  11476. movq 8(%r11), tmp5
  11477. movq tmp5, %r11
  11478. movq 8(%r11), %rax
  11479. jmp conclusion
  11480. \end{lstlisting}
  11481. \end{minipage}
  11482. \end{tabular}
  11483. \caption{Output of the \code{explicate\_control} (left)
  11484. and \code{select\_instructions} (right) passes on the running example.}
  11485. \label{fig:select-instr-output-gc}
  11486. \end{figure}
  11487. \clearpage
  11488. \section{Register Allocation}
  11489. \label{sec:reg-alloc-gc}
  11490. \index{subject}{register allocation}
  11491. As discussed earlier in this chapter, the garbage collector needs to
  11492. access all the pointers in the root set, that is, all variables that
  11493. are tuples. It will be the responsibility of the register allocator
  11494. to make sure that:
  11495. \begin{enumerate}
  11496. \item the root stack is used for spilling tuple-typed variables, and
  11497. \item if a tuple-typed variable is live during a call to the
  11498. collector, it must be spilled to ensure it is visible to the
  11499. collector.
  11500. \end{enumerate}
  11501. The later responsibility can be handled during construction of the
  11502. interference graph, by adding interference edges between the call-live
  11503. tuple-typed variables and all the callee-saved registers. (They
  11504. already interfere with the caller-saved registers.)
  11505. %
  11506. \racket{The type information for variables is in the \code{Program}
  11507. form, so we recommend adding another parameter to the
  11508. \code{build\_interference} function to communicate this alist.}
  11509. %
  11510. \python{The type information for variables is generated by the type
  11511. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11512. the \code{CProgram} AST mode. You'll need to propagate that
  11513. information so that it is available in this pass.}
  11514. The spilling of tuple-typed variables to the root stack can be handled
  11515. after graph coloring, when choosing how to assign the colors
  11516. (integers) to registers and stack locations. The
  11517. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11518. changes to also record the number of spills to the root stack.
  11519. % build-interference
  11520. %
  11521. % callq
  11522. % extra parameter for var->type assoc. list
  11523. % update 'program' and 'if'
  11524. % allocate-registers
  11525. % allocate spilled vectors to the rootstack
  11526. % don't change color-graph
  11527. % TODO:
  11528. %\section{Patch Instructions}
  11529. %[mention that global variables are memory references]
  11530. \section{Prelude and Conclusion}
  11531. \label{sec:print-x86-gc}
  11532. \label{sec:prelude-conclusion-x86-gc}
  11533. \index{subject}{prelude}\index{subject}{conclusion}
  11534. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11535. \code{prelude\_and\_conclusion} pass on the running example. In the
  11536. prelude and conclusion of the \code{main} function, we allocate space
  11537. on the root stack to make room for the spills of tuple-typed
  11538. variables. We do so by bumping the root stack pointer (\code{r15})
  11539. taking care that the root stack grows up instead of down. For the
  11540. running example, there was just one spill so we increment \code{r15}
  11541. by 8 bytes. In the conclusion we subtract 8 bytes from \code{r15}.
  11542. One issue that deserves special care is that there may be a call to
  11543. \code{collect} prior to the initializing assignments for all the
  11544. variables in the root stack. We do not want the garbage collector to
  11545. accidentally think that some uninitialized variable is a pointer that
  11546. needs to be followed. Thus, we zero-out all locations on the root
  11547. stack in the prelude of \code{main}. In
  11548. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11549. %
  11550. \lstinline{movq $0, 0(%r15)}
  11551. %
  11552. is sufficient to accomplish this task because there is only one spill.
  11553. In general, we have to clear as many words as there are spills of
  11554. tuple-typed variables. The garbage collector tests each root to see
  11555. if it is null prior to dereferencing it.
  11556. \begin{figure}[htbp]
  11557. % TODO: Python Version -Jeremy
  11558. \begin{minipage}[t]{0.5\textwidth}
  11559. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11560. .globl main
  11561. main:
  11562. pushq %rbp
  11563. movq %rsp, %rbp
  11564. subq $0, %rsp
  11565. movq $65536, %rdi
  11566. movq $65536, %rsi
  11567. callq initialize
  11568. movq rootstack_begin(%rip), %r15
  11569. movq $0, 0(%r15)
  11570. addq $8, %r15
  11571. jmp start
  11572. conclusion:
  11573. subq $8, %r15
  11574. addq $0, %rsp
  11575. popq %rbp
  11576. retq
  11577. \end{lstlisting}
  11578. \end{minipage}
  11579. \caption{The prelude and conclusion generated by the \code{prelude\_and\_conclusion} pass for the running example.}
  11580. \label{fig:print-x86-output-gc}
  11581. \end{figure}
  11582. \begin{figure}[tbp]
  11583. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11584. \node (Lvec) at (0,2) {\large \LangVec{}};
  11585. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11586. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11587. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11588. \node (Lvec-5) at (9,0) {\large \LangAlloc{}};
  11589. \node (Lvec-6) at (6,0) {\large \LangAllocANF{}};
  11590. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11591. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11592. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11593. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11594. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11595. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11596. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11597. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11598. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11599. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11600. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11601. \path[->,bend left=15] (Lvec-4) edge [right] node
  11602. {\ttfamily\footnotesize uncover\_get!} (Lvec-5);
  11603. \path[->,bend left=15] (Lvec-5) edge [below] node {\ttfamily\footnotesize remove\_complex.} (Lvec-6);
  11604. \path[->,bend right=10] (Lvec-6) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11605. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11606. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11607. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11608. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11609. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11610. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  11611. \end{tikzpicture}
  11612. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11613. \label{fig:Lvec-passes}
  11614. \end{figure}
  11615. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11616. for the compilation of \LangVec{}.
  11617. \clearpage
  11618. {\if\edition\racketEd
  11619. \section{Challenge: Simple Structures}
  11620. \label{sec:simple-structures}
  11621. \index{subject}{struct}
  11622. \index{subject}{structure}
  11623. The language \LangStruct{} extends \LangVec{} with support for simple
  11624. structures. Its concrete syntax is defined in
  11625. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11626. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11627. Racket is a user-defined data type that contains named fields and that
  11628. is heap allocated, similar to a vector. The following is an example of
  11629. a structure definition, in this case the definition of a \code{point}
  11630. type.
  11631. \begin{lstlisting}
  11632. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11633. \end{lstlisting}
  11634. \newcommand{\LstructGrammarRacket}{
  11635. \begin{array}{lcl}
  11636. \Type &::=& \Var \\
  11637. \Exp &::=& (\Var\;\Exp \ldots)\\
  11638. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11639. \end{array}
  11640. }
  11641. \newcommand{\LstructASTRacket}{
  11642. \begin{array}{lcl}
  11643. \Type &::=& \VAR{\Var} \\
  11644. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11645. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11646. \end{array}
  11647. }
  11648. \begin{figure}[tbp]
  11649. \centering
  11650. \fbox{
  11651. \begin{minipage}{0.96\textwidth}
  11652. \[
  11653. \begin{array}{l}
  11654. \gray{\LintGrammarRacket{}} \\ \hline
  11655. \gray{\LvarGrammarRacket{}} \\ \hline
  11656. \gray{\LifGrammarRacket{}} \\ \hline
  11657. \gray{\LwhileGrammarRacket} \\ \hline
  11658. \gray{\LtupGrammarRacket} \\ \hline
  11659. \LstructGrammarRacket \\
  11660. \begin{array}{lcl}
  11661. \LangStruct{} &::=& \Def \ldots \; \Exp
  11662. \end{array}
  11663. \end{array}
  11664. \]
  11665. \end{minipage}
  11666. }
  11667. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11668. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11669. \label{fig:Lstruct-concrete-syntax}
  11670. \end{figure}
  11671. \begin{figure}[tbp]
  11672. \centering
  11673. \fbox{
  11674. \begin{minipage}{0.96\textwidth}
  11675. \small
  11676. \[
  11677. \begin{array}{l}
  11678. \gray{\LintASTRacket{}} \\ \hline
  11679. \gray{\LvarASTRacket{}} \\ \hline
  11680. \gray{\LifASTRacket{}} \\ \hline
  11681. \gray{\LwhileASTRacket} \\ \hline
  11682. \gray{\LtupASTRacket} \\ \hline
  11683. \LstructASTRacket \\
  11684. \begin{array}{lcl}
  11685. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11686. \end{array}
  11687. \end{array}
  11688. \]
  11689. \end{minipage}
  11690. }
  11691. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11692. (Figure~\ref{fig:Lvec-syntax}).}
  11693. \label{fig:Lstruct-syntax}
  11694. \end{figure}
  11695. An instance of a structure is created using function call syntax, with
  11696. the name of the structure in the function position:
  11697. \begin{lstlisting}
  11698. (point 7 12)
  11699. \end{lstlisting}
  11700. Function-call syntax is also used to read a field of a structure. The
  11701. function name is formed by the structure name, a dash, and the field
  11702. name. The following example uses \code{point-x} and \code{point-y} to
  11703. access the \code{x} and \code{y} fields of two point instances.
  11704. \begin{center}
  11705. \begin{lstlisting}
  11706. (let ([pt1 (point 7 12)])
  11707. (let ([pt2 (point 4 3)])
  11708. (+ (- (point-x pt1) (point-x pt2))
  11709. (- (point-y pt1) (point-y pt2)))))
  11710. \end{lstlisting}
  11711. \end{center}
  11712. Similarly, to write to a field of a structure, use its set function,
  11713. whose name starts with \code{set-}, followed by the structure name,
  11714. then a dash, then the field name, and concluded with an exclamation
  11715. mark. The following example uses \code{set-point-x!} to change the
  11716. \code{x} field from \code{7} to \code{42}.
  11717. \begin{center}
  11718. \begin{lstlisting}
  11719. (let ([pt (point 7 12)])
  11720. (let ([_ (set-point-x! pt 42)])
  11721. (point-x pt)))
  11722. \end{lstlisting}
  11723. \end{center}
  11724. \begin{exercise}\normalfont\normalsize
  11725. Create a type checker for \LangStruct{} by extending the type
  11726. checker for \LangVec{}. Extend your compiler with support for simple
  11727. structures, compiling \LangStruct{} to x86 assembly code. Create
  11728. five new test cases that use structures and test your compiler.
  11729. \end{exercise}
  11730. % TODO: create an interpreter for L_struct
  11731. \clearpage
  11732. \section{Challenge: Arrays}
  11733. \label{sec:arrays}
  11734. In Chapter~\ref{ch:Lvec} we studied tuples, that is, a heterogeneous
  11735. sequences of elements whose length is determined at compile-time. This
  11736. challenge is also about sequences, but this time the length is
  11737. determined at run-time and all the elements have the same type (they
  11738. are homogeneous). We use the term ``array'' for this later kind of
  11739. sequence.
  11740. The Racket language does not distinguish between tuples and arrays,
  11741. they are both represented by vectors. However, Typed Racket
  11742. distinguishes between tuples and arrays: the \code{Vector} type is for
  11743. tuples and the \code{Vectorof} type is for arrays.
  11744. %
  11745. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11746. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11747. and the \code{make-vector} primitive operator for creating an array,
  11748. whose arguments are the length of the array and an initial value for
  11749. all the elements in the array. The \code{vector-length},
  11750. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11751. for tuples become overloaded for use with arrays.
  11752. %
  11753. We also include integer multiplication in \LangArray{}, as it is
  11754. useful in many examples involving arrays such as computing the
  11755. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11756. \newcommand{\LarrayGrammarRacket}{
  11757. \begin{array}{lcl}
  11758. \Type &::=& \LP \key{Vectorof}~\Type \RP \\
  11759. \Exp &::=& \CMUL{\Exp}{\Exp}
  11760. \MID \CMAKEVEC{\Exp}{\Exp} \\
  11761. \end{array}
  11762. }
  11763. \begin{figure}[tp]
  11764. \centering
  11765. \fbox{
  11766. \begin{minipage}{0.96\textwidth}
  11767. \small
  11768. {\if\edition\racketEd
  11769. \[
  11770. \begin{array}{l}
  11771. \gray{\LintGrammarRacket{}} \\ \hline
  11772. \gray{\LvarGrammarRacket{}} \\ \hline
  11773. \gray{\LifGrammarRacket{}} \\ \hline
  11774. \gray{\LwhileGrammarRacket} \\ \hline
  11775. \gray{\LtupGrammarRacket} \\ \hline
  11776. \LarrayGrammarRacket \\
  11777. \begin{array}{lcl}
  11778. \LangArray{} &::=& \Exp
  11779. \end{array}
  11780. \end{array}
  11781. \]
  11782. \fi}
  11783. {\if\edition\pythonEd
  11784. UNDER CONSTRUCTION
  11785. \fi}
  11786. \end{minipage}
  11787. }
  11788. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11789. \label{fig:Lvecof-concrete-syntax}
  11790. \end{figure}
  11791. \begin{figure}[tp]
  11792. \begin{lstlisting}
  11793. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11794. [n : Integer]) : Integer
  11795. (let ([i 0])
  11796. (let ([prod 0])
  11797. (begin
  11798. (while (< i n)
  11799. (begin
  11800. (set! prod (+ prod (* (vector-ref A i)
  11801. (vector-ref B i))))
  11802. (set! i (+ i 1))
  11803. ))
  11804. prod))))
  11805. (let ([A (make-vector 2 2)])
  11806. (let ([B (make-vector 2 3)])
  11807. (+ (inner-product A B 2)
  11808. 30)))
  11809. \end{lstlisting}
  11810. \caption{Example program that computes the inner-product.}
  11811. \label{fig:inner-product}
  11812. \end{figure}
  11813. The type checker for \LangArray{} is defined in
  11814. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11815. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11816. of the initializing expression. The length expression is required to
  11817. have type \code{Integer}. The type checking of the operators
  11818. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11819. updated to handle the situation where the vector has type
  11820. \code{Vectorof}. In these cases we translate the operators to their
  11821. \code{vectorof} form so that later passes can easily distinguish
  11822. between operations on tuples versus arrays. We override the
  11823. \code{operator-types} method to provide the type signature for
  11824. multiplication: it takes two integers and returns an integer.
  11825. \begin{figure}[tbp]
  11826. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11827. (define type-check-Lvecof-class
  11828. (class type-check-Lvec-class
  11829. (super-new)
  11830. (inherit check-type-equal?)
  11831. (define/override (operator-types)
  11832. (append '((* . ((Integer Integer) . Integer)))
  11833. (super operator-types)))
  11834. (define/override (type-check-exp env)
  11835. (lambda (e)
  11836. (define recur (type-check-exp env))
  11837. (match e
  11838. [(Prim 'make-vector (list e1 e2))
  11839. (define-values (e1^ t1) (recur e1))
  11840. (define-values (e2^ elt-type) (recur e2))
  11841. (define vec-type `(Vectorof ,elt-type))
  11842. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11843. vec-type)]
  11844. [(Prim 'vector-ref (list e1 e2))
  11845. (define-values (e1^ t1) (recur e1))
  11846. (define-values (e2^ t2) (recur e2))
  11847. (match* (t1 t2)
  11848. [(`(Vectorof ,elt-type) 'Integer)
  11849. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11850. [(other wise) ((super type-check-exp env) e)])]
  11851. [(Prim 'vector-set! (list e1 e2 e3) )
  11852. (define-values (e-vec t-vec) (recur e1))
  11853. (define-values (e2^ t2) (recur e2))
  11854. (define-values (e-arg^ t-arg) (recur e3))
  11855. (match t-vec
  11856. [`(Vectorof ,elt-type)
  11857. (check-type-equal? elt-type t-arg e)
  11858. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11859. [else ((super type-check-exp env) e)])]
  11860. [(Prim 'vector-length (list e1))
  11861. (define-values (e1^ t1) (recur e1))
  11862. (match t1
  11863. [`(Vectorof ,t)
  11864. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11865. [else ((super type-check-exp env) e)])]
  11866. [else ((super type-check-exp env) e)])))
  11867. ))
  11868. (define (type-check-Lvecof p)
  11869. (send (new type-check-Lvecof-class) type-check-program p))
  11870. \end{lstlisting}
  11871. \caption{Type checker for the \LangArray{} language.}
  11872. \label{fig:type-check-Lvecof}
  11873. \end{figure}
  11874. The interpreter for \LangArray{} is defined in
  11875. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11876. implemented with Racket's \code{make-vector} function and
  11877. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11878. integers.
  11879. \begin{figure}[tbp]
  11880. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11881. (define interp-Lvecof-class
  11882. (class interp-Lvec-class
  11883. (super-new)
  11884. (define/override (interp-op op)
  11885. (match op
  11886. ['make-vector make-vector]
  11887. ['* fx*]
  11888. [else (super interp-op op)]))
  11889. ))
  11890. (define (interp-Lvecof p)
  11891. (send (new interp-Lvecof-class) interp-program p))
  11892. \end{lstlisting}
  11893. \caption{Interpreter for \LangArray{}.}
  11894. \label{fig:interp-Lvecof}
  11895. \end{figure}
  11896. \subsection{Data Representation}
  11897. \label{sec:array-rep}
  11898. Just like tuples, we store arrays on the heap which means that the
  11899. garbage collector will need to inspect arrays. An immediate thought is
  11900. to use the same representation for arrays that we use for tuples.
  11901. However, we limit tuples to a length of $50$ so that their length and
  11902. pointer mask can fit into the 64-bit tag at the beginning of each
  11903. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11904. millions of elements, so we need more bits to store the length.
  11905. However, because arrays are homogeneous, we only need $1$ bit for the
  11906. pointer mask instead of one bit per array elements. Finally, the
  11907. garbage collector will need to be able to distinguish between tuples
  11908. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11909. arrive at the following layout for the 64-bit tag at the beginning of
  11910. an array:
  11911. \begin{itemize}
  11912. \item The right-most bit is the forwarding bit, just like in a tuple.
  11913. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11914. it is not.
  11915. \item The next bit to the left is the pointer mask. A $0$ indicates
  11916. that none of the elements are pointers to the heap and a $1$
  11917. indicates that all of the elements are pointers.
  11918. \item The next $61$ bits store the length of the array.
  11919. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11920. array ($1$).
  11921. \end{itemize}
  11922. %% Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11923. %% differentiate the kinds of values that have been injected into the
  11924. %% \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11925. %% to indicate that the value is an array.
  11926. In the following subsections we provide hints regarding how to update
  11927. the passes to handle arrays.
  11928. \subsection{Bounds Checking}
  11929. We recommend inserting a new pass named \code{check\_bounds} that
  11930. inserts code around each the \code{vector-ref} and \code{vector-set!}
  11931. operation to ensure that the index is greater than or equal to zero
  11932. and less than the \code{vector-length}.
  11933. %% \subsection{Reveal Casts}
  11934. %% The array-access operators \code{vectorof-ref} and
  11935. %% \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11936. %% \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11937. %% that the type checker cannot tell whether the index will be in bounds,
  11938. %% so the bounds check must be performed at run time. Recall that the
  11939. %% \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11940. %% an \code{If} arround a vector reference for update to check whether
  11941. %% the index is less than the length. You should do the same for
  11942. %% \code{vectorof-ref} and \code{vectorof-set!} .
  11943. %% In addition, the handling of the \code{any-vector} operators in
  11944. %% \code{reveal-casts} needs to be updated to account for arrays that are
  11945. %% injected to \code{Any}. For the \code{any-vector-length} operator, the
  11946. %% generated code should test whether the tag is for tuples (\code{010})
  11947. %% or arrays (\code{110}) and then dispatch to either
  11948. %% \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11949. %% we add a case in \code{select\_instructions} to generate the
  11950. %% appropriate instructions for accessing the array length from the
  11951. %% header of an array.
  11952. %% For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11953. %% the generated code needs to check that the index is less than the
  11954. %% vector length, so like the code for \code{any-vector-length}, check
  11955. %% the tag to determine whether to use \code{any-vector-length} or
  11956. %% \code{any-vectorof-length} for this purpose. Once the bounds checking
  11957. %% is complete, the generated code can use \code{any-vector-ref} and
  11958. %% \code{any-vector-set!} for both tuples and arrays because the
  11959. %% instructions used for those operators do not look at the tag at the
  11960. %% front of the tuple or array.
  11961. \subsection{Expose Allocation}
  11962. This pass should translate the \code{make-vector} operator into
  11963. lower-level operations. In particular, the new AST node
  11964. $\LP\key{AllocateArray}~\Exp~\Type\RP$ is analogous to the
  11965. \code{Allocate} AST node for tuples. It allocates an array of the
  11966. length specified by the $\Exp$, but does not initialize the elements
  11967. of the array. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$
  11968. where $T$ is the element type for the array. Regarding the
  11969. initialization of the array, we recommend generated a \code{while}
  11970. loop that uses \code{vector-set!} to put the initializing value into
  11971. every element of the array.
  11972. \subsection{Remove Complex Operands}
  11973. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11974. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11975. complex and its subexpression must be atomic.
  11976. \subsection{Explicate Control}
  11977. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11978. \code{explicate\_assign}.
  11979. \subsection{Select Instructions}
  11980. Generate instructions for \code{AllocateArray} similar to those for
  11981. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11982. that the tag at the front of the array should instead use the
  11983. representation discussed in Section~\ref{sec:array-rep}.
  11984. Regarding \code{vectorof-length}, extract the length from the tag
  11985. according to the representation discussed in
  11986. Section~\ref{sec:array-rep}.
  11987. The instructions generated for \code{vectorof-ref} differ from those
  11988. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11989. that the index is not a constant so the offset must be computed at
  11990. runtime. The same is true for \code{vectorof-set!}. Also, the
  11991. \code{vectorof-set!} may appear in an assignment and as a stand-alone
  11992. statement, so make sure to handle both situations in this pass.
  11993. %% Finally, the instructions for \code{any-vectorof-length} should be
  11994. %% similar to those for \code{vectorof-length}, except that one must
  11995. %% first project the array by writing zeroes into the $3$-bit tag
  11996. \begin{exercise}\normalfont\normalsize
  11997. Implement a compiler for the \LangArray{} language by extending your
  11998. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11999. programs, including the one in Figure~\ref{fig:inner-product} and also
  12000. a program that multiplies two matrices. Note that although matrices
  12001. are 2-dimensional arrays, they can be encoded into 1-dimensional
  12002. arrays by laying out each row in the array, one after the next.
  12003. \end{exercise}
  12004. \section{Challenge: Generational Collection}
  12005. The copying collector described in Section~\ref{sec:GC} can incur
  12006. significant runtime overhead because the call to \code{collect} takes
  12007. time proportional to all of the live data. One way to reduce this
  12008. overhead is to reduce how much data is inspected in each call to
  12009. \code{collect}. In particular, researchers have observed that recently
  12010. allocated data is more likely to become garbage then data that has
  12011. survived one or more previous calls to \code{collect}. This insight
  12012. motivated the creation of \emph{generational garbage collectors}
  12013. \index{subject}{generational garbage collector} that
  12014. 1) segregates data according to its age into two or more generations,
  12015. 2) allocates less space for younger generations, so collecting them is
  12016. faster, and more space for the older generations, and 3) performs
  12017. collection on the younger generations more frequently then for older
  12018. generations~\citep{Wilson:1992fk}.
  12019. For this challenge assignment, the goal is to adapt the copying
  12020. collector implemented in \code{runtime.c} to use two generations, one
  12021. for young data and one for old data. Each generation consists of a
  12022. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  12023. \code{collect} function to use the two generations.
  12024. \begin{enumerate}
  12025. \item Copy the young generation's FromSpace to its ToSpace then switch
  12026. the role of the ToSpace and FromSpace
  12027. \item If there is enough space for the requested number of bytes in
  12028. the young FromSpace, then return from \code{collect}.
  12029. \item If there is not enough space in the young FromSpace for the
  12030. requested bytes, then move the data from the young generation to the
  12031. old one with the following steps:
  12032. \begin{enumerate}
  12033. \item If there is enough room in the old FromSpace, copy the young
  12034. FromSpace to the old FromSpace and then return.
  12035. \item If there is not enough room in the old FromSpace, then collect
  12036. the old generation by copying the old FromSpace to the old ToSpace
  12037. and swap the roles of the old FromSpace and ToSpace.
  12038. \item If there is enough room now, copy the young FromSpace to the
  12039. old FromSpace and return. Otherwise, allocate a larger FromSpace
  12040. and ToSpace for the old generation. Copy the young FromSpace and
  12041. the old FromSpace into the larger FromSpace for the old
  12042. generation and then return.
  12043. \end{enumerate}
  12044. \end{enumerate}
  12045. We recommend that you generalize the \code{cheney} function so that it
  12046. can be used for all the copies mentioned above: between the young
  12047. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  12048. between the young FromSpace and old FromSpace. This can be
  12049. accomplished by adding parameters to \code{cheney} that replace its
  12050. use of the global variables \code{fromspace\_begin},
  12051. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  12052. Note that the collection of the young generation does not traverse the
  12053. old generation. This introduces a potential problem: there may be
  12054. young data that is only reachable through pointers in the old
  12055. generation. If these pointers are not taken into account, the
  12056. collector could throw away young data that is live! One solution,
  12057. called \emph{pointer recording}, is to maintain a set of all the
  12058. pointers from the old generation into the new generation and consider
  12059. this set as part of the root set. To maintain this set, the compiler
  12060. must insert extra instructions around every \code{vector-set!}. If the
  12061. vector being modified is in the old generation, and if the value being
  12062. written is a pointer into the new generation, than that pointer must
  12063. be added to the set. Also, if the value being overwritten was a
  12064. pointer into the new generation, then that pointer should be removed
  12065. from the set.
  12066. \begin{exercise}\normalfont\normalsize
  12067. Adapt the \code{collect} function in \code{runtime.c} to implement
  12068. generational garbage collection, as outlined in this section.
  12069. Update the code generation for \code{vector-set!} to implement
  12070. pointer recording. Make sure that your new compiler and runtime
  12071. passes your test suite.
  12072. \end{exercise}
  12073. \fi}
  12074. \section{Further Reading}
  12075. \citet{Appel90} describes many data representation approaches,
  12076. including the ones used in the compilation of Standard ML.
  12077. There are many alternatives to copying collectors (and their bigger
  12078. siblings, the generational collectors) when its comes to garbage
  12079. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12080. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12081. collectors are that allocation is fast (just a comparison and pointer
  12082. increment), there is no fragmentation, cyclic garbage is collected,
  12083. and the time complexity of collection only depends on the amount of
  12084. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12085. main disadvantages of a two-space copying collector is that it uses a
  12086. lot of extra space and takes a long time to perform the copy, though
  12087. these problems are ameliorated in generational collectors.
  12088. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12089. small objects and generate a lot of garbage, so copying and
  12090. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12091. Garbage collection is an active research topic, especially concurrent
  12092. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12093. developing new techniques and revisiting old
  12094. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12095. meet every year at the International Symposium on Memory Management to
  12096. present these findings.
  12097. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12098. \chapter{Functions}
  12099. \label{ch:Lfun}
  12100. \index{subject}{function}
  12101. This chapter studies the compilation of a subset of \racket{Typed
  12102. Racket}\python{Python} in which only top-level function definitions
  12103. are allowed. This kind of function appears in the C programming
  12104. language and it serves as an important stepping stone to implementing
  12105. lexically-scoped functions in the form of \key{lambda} abstractions,
  12106. which is the topic of Chapter~\ref{ch:Llambda}.
  12107. \section{The \LangFun{} Language}
  12108. The concrete and abstract syntax for function definitions and function
  12109. application is shown in Figures~\ref{fig:Lfun-concrete-syntax} and
  12110. \ref{fig:Lfun-syntax}, where we define the \LangFun{} language.
  12111. Programs in \LangFun{} begin with zero or more function definitions.
  12112. The function names from these definitions are in-scope for the entire
  12113. program, including all of the function definitions (so the ordering of
  12114. function definitions does not matter).
  12115. %
  12116. \python{The abstract syntax for function parameters in
  12117. Figure~\ref{fig:Lfun-syntax} is a list of pairs, where each pair
  12118. consists of a parameter name and its type. This design differs from
  12119. Python's \code{ast} module, which has a more complex structure for
  12120. function parameters to handle keyword parameters,
  12121. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12122. complex Python abstract syntax into the simpler syntax of
  12123. Figure~\ref{fig:Lfun-syntax}. The fourth and sixth parameters of the
  12124. \code{FunctionDef} constructor are for decorators and a type
  12125. comment, neither of which are used by our compiler. We recommend
  12126. replacing them with \code{None} in the \code{shrink} pass.
  12127. }
  12128. %
  12129. The concrete syntax for function application\index{subject}{function
  12130. application} is
  12131. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12132. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12133. where the first expression
  12134. must evaluate to a function and the remaining expressions are the arguments. The
  12135. abstract syntax for function application is
  12136. $\APPLY{\Exp}{\Exp^*}$.
  12137. %% The syntax for function application does not include an explicit
  12138. %% keyword, which is error prone when using \code{match}. To alleviate
  12139. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12140. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12141. Functions are first-class in the sense that a function pointer
  12142. \index{subject}{function pointer} is data and can be stored in memory or passed
  12143. as a parameter to another function. Thus, there is a function
  12144. type, written
  12145. {\if\edition\racketEd
  12146. \begin{lstlisting}
  12147. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12148. \end{lstlisting}
  12149. \fi}
  12150. {\if\edition\pythonEd
  12151. \begin{lstlisting}
  12152. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12153. \end{lstlisting}
  12154. \fi}
  12155. %
  12156. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12157. through $\Type_n$ and whose return type is $\Type_R$. The main
  12158. limitation of these functions (with respect to
  12159. \racket{Racket}\python{Python} functions) is that they are not
  12160. lexically scoped. That is, the only external entities that can be
  12161. referenced from inside a function body are other globally-defined
  12162. functions. The syntax of \LangFun{} prevents function definitions from being
  12163. nested inside each other.
  12164. \newcommand{\LfunGrammarRacket}{
  12165. \begin{array}{lcl}
  12166. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12167. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12168. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12169. \end{array}
  12170. }
  12171. \newcommand{\LfunASTRacket}{
  12172. \begin{array}{lcl}
  12173. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12174. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12175. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12176. \end{array}
  12177. }
  12178. \newcommand{\LfunGrammarPython}{
  12179. \begin{array}{lcl}
  12180. \Type &::=& \key{int}
  12181. \MID \key{bool}
  12182. \MID \key{tuple}\LS \Type^+ \RS
  12183. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12184. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12185. \Stmt &::=& \CRETURN{\Exp} \\
  12186. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12187. \end{array}
  12188. }
  12189. \newcommand{\LfunASTPython}{
  12190. \begin{array}{lcl}
  12191. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12192. \MID \key{TupleType}\LS\Type^+\RS\\
  12193. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12194. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12195. \Stmt &::=& \RETURN{\Exp} \\
  12196. \Params &::=& \LP\Var\key{,}\Type\RP^*
  12197. \\
  12198. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12199. \end{array}
  12200. }
  12201. \begin{figure}[tp]
  12202. \centering
  12203. \fbox{
  12204. \begin{minipage}{0.96\textwidth}
  12205. \small
  12206. {\if\edition\racketEd
  12207. \[
  12208. \begin{array}{l}
  12209. \gray{\LintGrammarRacket{}} \\ \hline
  12210. \gray{\LvarGrammarRacket{}} \\ \hline
  12211. \gray{\LifGrammarRacket{}} \\ \hline
  12212. \gray{\LwhileGrammarRacket} \\ \hline
  12213. \gray{\LtupGrammarRacket} \\ \hline
  12214. \LfunGrammarRacket \\
  12215. \begin{array}{lcl}
  12216. \LangFunM{} &::=& \Def \ldots \; \Exp
  12217. \end{array}
  12218. \end{array}
  12219. \]
  12220. \fi}
  12221. {\if\edition\pythonEd
  12222. \[
  12223. \begin{array}{l}
  12224. \gray{\LintGrammarPython{}} \\ \hline
  12225. \gray{\LvarGrammarPython{}} \\ \hline
  12226. \gray{\LifGrammarPython{}} \\ \hline
  12227. \gray{\LwhileGrammarPython} \\ \hline
  12228. \gray{\LtupGrammarPython} \\ \hline
  12229. \LfunGrammarPython \\
  12230. \begin{array}{rcl}
  12231. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12232. \end{array}
  12233. \end{array}
  12234. \]
  12235. \fi}
  12236. \end{minipage}
  12237. }
  12238. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12239. \label{fig:Lfun-concrete-syntax}
  12240. \end{figure}
  12241. \begin{figure}[tp]
  12242. \centering
  12243. \fbox{
  12244. \begin{minipage}{0.96\textwidth}
  12245. \small
  12246. {\if\edition\racketEd
  12247. \[
  12248. \begin{array}{l}
  12249. \gray{\LintOpAST} \\ \hline
  12250. \gray{\LvarASTRacket{}} \\ \hline
  12251. \gray{\LifASTRacket{}} \\ \hline
  12252. \gray{\LwhileASTRacket{}} \\ \hline
  12253. \gray{\LtupASTRacket{}} \\ \hline
  12254. \LfunASTRacket \\
  12255. \begin{array}{lcl}
  12256. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12257. \end{array}
  12258. \end{array}
  12259. \]
  12260. \fi}
  12261. {\if\edition\pythonEd
  12262. \[
  12263. \begin{array}{l}
  12264. \gray{\LintASTPython{}} \\ \hline
  12265. \gray{\LvarASTPython{}} \\ \hline
  12266. \gray{\LifASTPython{}} \\ \hline
  12267. \gray{\LwhileASTPython} \\ \hline
  12268. \gray{\LtupASTPython} \\ \hline
  12269. \LfunASTPython \\
  12270. \begin{array}{rcl}
  12271. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12272. \end{array}
  12273. \end{array}
  12274. \]
  12275. \fi}
  12276. \end{minipage}
  12277. }
  12278. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12279. \label{fig:Lfun-syntax}
  12280. \end{figure}
  12281. The program in Figure~\ref{fig:Lfun-function-example} is a
  12282. representative example of defining and using functions in \LangFun{}.
  12283. We define a function \code{map} that applies some other function
  12284. \code{f} to both elements of a tuple and returns a new tuple
  12285. containing the results. We also define a function \code{inc}. The
  12286. program applies \code{map} to \code{inc} and
  12287. %
  12288. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12289. %
  12290. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12291. %
  12292. from which we return \code{42}.
  12293. \begin{figure}[tbp]
  12294. {\if\edition\racketEd
  12295. \begin{lstlisting}
  12296. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12297. : (Vector Integer Integer)
  12298. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12299. (define (inc [x : Integer]) : Integer
  12300. (+ x 1))
  12301. (vector-ref (map inc (vector 0 41)) 1)
  12302. \end{lstlisting}
  12303. \fi}
  12304. {\if\edition\pythonEd
  12305. \begin{lstlisting}
  12306. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12307. return f(v[0]), f(v[1])
  12308. def inc(x : int) -> int:
  12309. return x + 1
  12310. print( map(inc, (0, 41))[1] )
  12311. \end{lstlisting}
  12312. \fi}
  12313. \caption{Example of using functions in \LangFun{}.}
  12314. \label{fig:Lfun-function-example}
  12315. \end{figure}
  12316. The definitional interpreter for \LangFun{} is in
  12317. Figure~\ref{fig:interp-Lfun}. The case for the
  12318. %
  12319. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12320. %
  12321. AST is responsible for setting up the mutual recursion between the
  12322. top-level function definitions.
  12323. %
  12324. \racket{We use the classic back-patching
  12325. \index{subject}{back-patching} approach that uses mutable variables
  12326. and makes two passes over the function
  12327. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12328. top-level environment using a mutable cons cell for each function
  12329. definition. Note that the \code{lambda} value for each function is
  12330. incomplete; it does not yet include the environment. Once the
  12331. top-level environment is constructed, we then iterate over it and
  12332. update the \code{lambda} values to use the top-level environment.}
  12333. %
  12334. \python{We create a dictionary named \code{env} and fill it in
  12335. by mapping each function name to a new \code{Function} value,
  12336. each of which stores a reference to the \code{env}.
  12337. (We define the class \code{Function} for this purpose.)}
  12338. %
  12339. To interpret a function \racket{application}\python{call}, we match
  12340. the result of the function expression to obtain a function value. We
  12341. then extend the function's environment with the mapping of parameters to
  12342. argument values. Finally, we interpret the body of the function in
  12343. this extended environment.
  12344. \begin{figure}[tp]
  12345. {\if\edition\racketEd
  12346. \begin{lstlisting}
  12347. (define interp-Lfun-class
  12348. (class interp-Lvec-class
  12349. (super-new)
  12350. (define/override ((interp-exp env) e)
  12351. (define recur (interp-exp env))
  12352. (match e
  12353. [(Apply fun args)
  12354. (define fun-val (recur fun))
  12355. (define arg-vals (for/list ([e args]) (recur e)))
  12356. (match fun-val
  12357. [`(function (,xs ...) ,body ,fun-env)
  12358. (define params-args (for/list ([x xs] [arg arg-vals])
  12359. (cons x (box arg))))
  12360. (define new-env (append params-args fun-env))
  12361. ((interp-exp new-env) body)]
  12362. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12363. [else ((super interp-exp env) e)]
  12364. ))
  12365. (define/public (interp-def d)
  12366. (match d
  12367. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12368. (cons f (box `(function ,xs ,body ())))]))
  12369. (define/override (interp-program p)
  12370. (match p
  12371. [(ProgramDefsExp info ds body)
  12372. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12373. (for/list ([f (in-dict-values top-level)])
  12374. (set-box! f (match (unbox f)
  12375. [`(function ,xs ,body ())
  12376. `(function ,xs ,body ,top-level)])))
  12377. ((interp-exp top-level) body))]))
  12378. ))
  12379. (define (interp-Lfun p)
  12380. (send (new interp-Lfun-class) interp-program p))
  12381. \end{lstlisting}
  12382. \fi}
  12383. {\if\edition\pythonEd
  12384. \begin{lstlisting}
  12385. class InterpLfun(InterpLtup):
  12386. def apply_fun(self, fun, args, e):
  12387. match fun:
  12388. case Function(name, xs, body, env):
  12389. new_env = env.copy().update(zip(xs, args))
  12390. return self.interp_stmts(body, new_env)
  12391. case _:
  12392. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12393. def interp_exp(self, e, env):
  12394. match e:
  12395. case Call(Name('input_int'), []):
  12396. return super().interp_exp(e, env)
  12397. case Call(func, args):
  12398. f = self.interp_exp(func, env)
  12399. vs = [self.interp_exp(arg, env) for arg in args]
  12400. return self.apply_fun(f, vs, e)
  12401. case _:
  12402. return super().interp_exp(e, env)
  12403. def interp_stmts(self, ss, env):
  12404. if len(ss) == 0:
  12405. return
  12406. match ss[0]:
  12407. case Return(value):
  12408. return self.interp_exp(value, env)
  12409. case FunctionDef(name, params, bod, dl, returns, comment):
  12410. ps = [x for (x,t) in params]
  12411. env[name] = Function(name, ps, bod, env)
  12412. return self.interp_stmts(ss[1:], env)
  12413. case _:
  12414. return super().interp_stmts(ss, env)
  12415. def interp(self, p):
  12416. match p:
  12417. case Module(ss):
  12418. env = {}
  12419. self.interp_stmts(ss, env)
  12420. if 'main' in env.keys():
  12421. self.apply_fun(env['main'], [], None)
  12422. case _:
  12423. raise Exception('interp: unexpected ' + repr(p))
  12424. \end{lstlisting}
  12425. \fi}
  12426. \caption{Interpreter for the \LangFun{} language.}
  12427. \label{fig:interp-Lfun}
  12428. \end{figure}
  12429. %\margincomment{TODO: explain type checker}
  12430. The type checker for \LangFun{} is in
  12431. Figure~\ref{fig:type-check-Lfun}.
  12432. %
  12433. \python{(We omit the code that parses function parameters into the
  12434. simpler abstract syntax.)}
  12435. %
  12436. Similar to the interpreter, the case for the
  12437. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12438. %
  12439. AST is responsible for setting up the mutual recursion between the
  12440. top-level function definitions. We begin by create a mapping
  12441. \code{env} from every function name to its type. We then type check
  12442. the program using this mapping.
  12443. %
  12444. In the case for function \racket{application}\python{call}, we match
  12445. the type of the function expression to a function type and check that
  12446. the types of the argument expressions are equal to the function's
  12447. parameter types. The type of the \racket{application}\python{call} as
  12448. a whole is the return type from the function type.
  12449. \begin{figure}[tp]
  12450. {\if\edition\racketEd
  12451. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12452. (define type-check-Lfun-class
  12453. (class type-check-Lvec-class
  12454. (super-new)
  12455. (inherit check-type-equal?)
  12456. (define/public (type-check-apply env e es)
  12457. (define-values (e^ ty) ((type-check-exp env) e))
  12458. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12459. ((type-check-exp env) e)))
  12460. (match ty
  12461. [`(,ty^* ... -> ,rt)
  12462. (for ([arg-ty ty*] [param-ty ty^*])
  12463. (check-type-equal? arg-ty param-ty (Apply e es)))
  12464. (values e^ e* rt)]))
  12465. (define/override (type-check-exp env)
  12466. (lambda (e)
  12467. (match e
  12468. [(FunRef f n)
  12469. (values (FunRef f n) (dict-ref env f))]
  12470. [(Apply e es)
  12471. (define-values (e^ es^ rt) (type-check-apply env e es))
  12472. (values (Apply e^ es^) rt)]
  12473. [(Call e es)
  12474. (define-values (e^ es^ rt) (type-check-apply env e es))
  12475. (values (Call e^ es^) rt)]
  12476. [else ((super type-check-exp env) e)])))
  12477. (define/public (type-check-def env)
  12478. (lambda (e)
  12479. (match e
  12480. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12481. (define new-env (append (map cons xs ps) env))
  12482. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12483. (check-type-equal? ty^ rt body)
  12484. (Def f p:t* rt info body^)])))
  12485. (define/public (fun-def-type d)
  12486. (match d
  12487. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12488. (define/override (type-check-program e)
  12489. (match e
  12490. [(ProgramDefsExp info ds body)
  12491. (define env (for/list ([d ds])
  12492. (cons (Def-name d) (fun-def-type d))))
  12493. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12494. (define-values (body^ ty) ((type-check-exp env) body))
  12495. (check-type-equal? ty 'Integer body)
  12496. (ProgramDefsExp info ds^ body^)]))))
  12497. (define (type-check-Lfun p)
  12498. (send (new type-check-Lfun-class) type-check-program p))
  12499. \end{lstlisting}
  12500. \fi}
  12501. {\if\edition\pythonEd
  12502. \begin{lstlisting}
  12503. class TypeCheckLfun(TypeCheckLtup):
  12504. def type_check_exp(self, e, env):
  12505. match e:
  12506. case Call(Name('input_int'), []):
  12507. return super().type_check_exp(e, env)
  12508. case Call(func, args):
  12509. func_t = self.type_check_exp(func, env)
  12510. args_t = [self.type_check_exp(arg, env) for arg in args]
  12511. match func_t:
  12512. case FunctionType(params_t, return_t):
  12513. for (arg_t, param_t) in zip(args_t, params_t):
  12514. check_type_equal(param_t, arg_t, e)
  12515. return return_t
  12516. case _:
  12517. raise Exception('type_check_exp: in call, unexpected ' +
  12518. repr(func_t))
  12519. case _:
  12520. return super().type_check_exp(e, env)
  12521. def type_check_stmts(self, ss, env):
  12522. if len(ss) == 0:
  12523. return
  12524. match ss[0]:
  12525. case FunctionDef(name, params, body, dl, returns, comment):
  12526. new_env = env.copy().update(params)
  12527. rt = self.type_check_stmts(body, new_env)
  12528. check_type_equal(returns, rt, ss[0])
  12529. return self.type_check_stmts(ss[1:], env)
  12530. case Return(value):
  12531. return self.type_check_exp(value, env)
  12532. case _:
  12533. return super().type_check_stmts(ss, env)
  12534. def type_check(self, p):
  12535. match p:
  12536. case Module(body):
  12537. env = {}
  12538. for s in body:
  12539. match s:
  12540. case FunctionDef(name, params, bod, dl, returns, comment):
  12541. if name in env:
  12542. raise Exception('type_check: function ' +
  12543. repr(name) + ' defined twice')
  12544. params_t = [t for (x,t) in params]
  12545. env[name] = FunctionType(params_t, returns)
  12546. self.type_check_stmts(body, env)
  12547. case _:
  12548. raise Exception('type_check: unexpected ' + repr(p))
  12549. \end{lstlisting}
  12550. \fi}
  12551. \caption{Type checker for the \LangFun{} language.}
  12552. \label{fig:type-check-Lfun}
  12553. \end{figure}
  12554. \clearpage
  12555. \section{Functions in x86}
  12556. \label{sec:fun-x86}
  12557. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12558. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12559. %% \margincomment{\tiny Talk about the return address on the
  12560. %% stack and what callq and retq does.\\ --Jeremy }
  12561. The x86 architecture provides a few features to support the
  12562. implementation of functions. We have already seen that there are
  12563. labels in x86 so that one can refer to the location of an instruction,
  12564. as is needed for jump instructions. Labels can also be used to mark
  12565. the beginning of the instructions for a function. Going further, we
  12566. can obtain the address of a label by using the \key{leaq}
  12567. instruction. For example, the following puts the address of the
  12568. \code{inc} label into the \code{rbx} register.
  12569. \begin{lstlisting}
  12570. leaq inc(%rip), %rbx
  12571. \end{lstlisting}
  12572. Recall from Section~\ref{sec:select-instructions-gc} that
  12573. \verb!inc(%rip)! is an example of instruction-pointer relative
  12574. addressing. It computes the address of \code{inc}.
  12575. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12576. to functions whose locations were given by a label, such as
  12577. \code{read\_int}. To support function calls in this chapter we instead
  12578. will be jumping to functions whose location are given by an address in
  12579. a register, that is, we shall use \emph{indirect function calls}. The
  12580. x86 syntax for this is a \code{callq} instruction but with an asterisk
  12581. before the register name.\index{subject}{indirect function call}
  12582. \begin{lstlisting}
  12583. callq *%rbx
  12584. \end{lstlisting}
  12585. \subsection{Calling Conventions}
  12586. \label{sec:calling-conventions-fun}
  12587. \index{subject}{calling conventions}
  12588. The \code{callq} instruction provides partial support for implementing
  12589. functions: it pushes the return address on the stack and it jumps to
  12590. the target. However, \code{callq} does not handle
  12591. \begin{enumerate}
  12592. \item parameter passing,
  12593. \item pushing frames on the procedure call stack and popping them off,
  12594. or
  12595. \item determining how registers are shared by different functions.
  12596. \end{enumerate}
  12597. Regarding (1) parameter passing, recall that the x86-64 calling
  12598. convention for Unix-based system uses the following six registers to
  12599. pass arguments to a function, in this order.
  12600. \begin{lstlisting}
  12601. rdi rsi rdx rcx r8 r9
  12602. \end{lstlisting}
  12603. If there are more than six arguments, then the calling convention
  12604. mandates to use space on the frame of the caller for the rest of the
  12605. arguments. However, to ease the implementation of efficient tail calls
  12606. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12607. arguments.
  12608. %
  12609. The return value of the function is stored in register \code{rax}.
  12610. \index{subject}{prelude}\index{subject}{conclusion}
  12611. Regarding (2) frames \index{subject}{frame} and the procedure call
  12612. stack, \index{subject}{procedure call stack} recall from
  12613. Section~\ref{sec:x86} that the stack grows down and each function call
  12614. uses a chunk of space on the stack called a frame. The caller sets the
  12615. stack pointer, register \code{rsp}, to the last data item in its
  12616. frame. The callee must not change anything in the caller's frame, that
  12617. is, anything that is at or above the stack pointer. The callee is free
  12618. to use locations that are below the stack pointer.
  12619. Recall that we store variables of tuple type on the root stack. So
  12620. the prelude of a function needs to move the root stack pointer
  12621. \code{r15} up according to the number of variables of tuple type and
  12622. the conclusion needs to move the root stack pointer back down. Also,
  12623. the prelude must initialize to \code{0} this frame's slots in the root
  12624. stack to signal to the garbage collector that those slots do not yet
  12625. contain a valid pointer. Otherwise the garbage collector will
  12626. interpret the garbage bits in those slots as memory addresses and try
  12627. to traverse them, causing serious mayhem!
  12628. Regarding (3) the sharing of registers between different functions,
  12629. recall from Section~\ref{sec:calling-conventions} that the registers
  12630. are divided into two groups, the caller-saved registers and the
  12631. callee-saved registers. The caller should assume that all the
  12632. caller-saved registers get overwritten with arbitrary values by the
  12633. callee. For that reason we recommend in
  12634. Section~\ref{sec:calling-conventions} that variables that are live
  12635. during a function call should not be assigned to caller-saved
  12636. registers.
  12637. On the flip side, if the callee wants to use a callee-saved register,
  12638. the callee must save the contents of those registers on their stack
  12639. frame and then put them back prior to returning to the caller. For
  12640. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12641. the register allocator assigns a variable to a callee-saved register,
  12642. then the prelude of the \code{main} function must save that register
  12643. to the stack and the conclusion of \code{main} must restore it. This
  12644. recommendation now generalizes to all functions.
  12645. Recall that the base pointer, register \code{rbp}, is used as a
  12646. point-of-reference within a frame, so that each local variable can be
  12647. accessed at a fixed offset from the base pointer
  12648. (Section~\ref{sec:x86}).
  12649. %
  12650. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12651. and callee frames.
  12652. \begin{figure}[tbp]
  12653. \centering
  12654. \begin{tabular}{r|r|l|l} \hline
  12655. Caller View & Callee View & Contents & Frame \\ \hline
  12656. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12657. 0(\key{\%rbp}) & & old \key{rbp} \\
  12658. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12659. \ldots & & \ldots \\
  12660. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12661. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12662. \ldots & & \ldots \\
  12663. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12664. %% & & \\
  12665. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12666. %% & \ldots & \ldots \\
  12667. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12668. \hline
  12669. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12670. & 0(\key{\%rbp}) & old \key{rbp} \\
  12671. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12672. & \ldots & \ldots \\
  12673. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12674. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12675. & \ldots & \ldots \\
  12676. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12677. \end{tabular}
  12678. \caption{Memory layout of caller and callee frames.}
  12679. \label{fig:call-frames}
  12680. \end{figure}
  12681. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12682. %% local variables and for storing the values of callee-saved registers
  12683. %% (we shall refer to all of these collectively as ``locals''), and that
  12684. %% at the beginning of a function we move the stack pointer \code{rsp}
  12685. %% down to make room for them.
  12686. %% We recommend storing the local variables
  12687. %% first and then the callee-saved registers, so that the local variables
  12688. %% can be accessed using \code{rbp} the same as before the addition of
  12689. %% functions.
  12690. %% To make additional room for passing arguments, we shall
  12691. %% move the stack pointer even further down. We count how many stack
  12692. %% arguments are needed for each function call that occurs inside the
  12693. %% body of the function and find their maximum. Adding this number to the
  12694. %% number of locals gives us how much the \code{rsp} should be moved at
  12695. %% the beginning of the function. In preparation for a function call, we
  12696. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12697. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12698. %% so on.
  12699. %% Upon calling the function, the stack arguments are retrieved by the
  12700. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12701. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12702. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12703. %% the layout of the caller and callee frames. Notice how important it is
  12704. %% that we correctly compute the maximum number of arguments needed for
  12705. %% function calls; if that number is too small then the arguments and
  12706. %% local variables will smash into each other!
  12707. \subsection{Efficient Tail Calls}
  12708. \label{sec:tail-call}
  12709. In general, the amount of stack space used by a program is determined
  12710. by the longest chain of nested function calls. That is, if function
  12711. $f_1$ calls $f_2$, $f_2$ calls $f_3$, and so on to $f_n$, then the
  12712. amount of stack space is linear in $n$. The depth $n$ can grow quite
  12713. large if functions are recursive. However, in some cases we can
  12714. arrange to use only a constant amount of space for a long chain of
  12715. nested function calls.
  12716. A \emph{tail call}\index{subject}{tail call} is a function call that
  12717. happens as the last action in a function body.
  12718. For example, in the following
  12719. program, the recursive call to \code{tail\_sum} is a tail call.
  12720. \begin{center}
  12721. {\if\edition\racketEd
  12722. \begin{lstlisting}
  12723. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12724. (if (eq? n 0)
  12725. r
  12726. (tail_sum (- n 1) (+ n r))))
  12727. (+ (tail_sum 3 0) 36)
  12728. \end{lstlisting}
  12729. \fi}
  12730. {\if\edition\pythonEd
  12731. \begin{lstlisting}
  12732. def tail_sum(n : int, r : int) -> int:
  12733. if n == 0:
  12734. return r
  12735. else:
  12736. return tail_sum(n - 1, n + r)
  12737. print( tail_sum(3, 0) + 36)
  12738. \end{lstlisting}
  12739. \fi}
  12740. \end{center}
  12741. At a tail call, the frame of the caller is no longer needed, so we can
  12742. pop the caller's frame before making the tail call. With this
  12743. approach, a recursive function that only makes tail calls ends up
  12744. using a constant amount of stack space. Functional languages like
  12745. Racket rely heavily on recursive functions, so the definition of
  12746. Racket \emph{requires} that all tail calls be optimized in this way.
  12747. \index{subject}{frame}
  12748. Some care is needed with regards to argument passing in tail calls.
  12749. As mentioned above, for arguments beyond the sixth, the convention is
  12750. to use space in the caller's frame for passing arguments. But for a
  12751. tail call we pop the caller's frame and can no longer use it. An
  12752. alternative is to use space in the callee's frame for passing
  12753. arguments. However, this option is also problematic because the caller
  12754. and callee's frames overlap in memory. As we begin to copy the
  12755. arguments from their sources in the caller's frame, the target
  12756. locations in the callee's frame might collide with the sources for
  12757. later arguments! We solve this problem by using the heap instead of
  12758. the stack for passing more than six arguments
  12759. (Section~\ref{sec:limit-functions-r4}).
  12760. As mentioned above, for a tail call we pop the caller's frame prior to
  12761. making the tail call. The instructions for popping a frame are the
  12762. instructions that we usually place in the conclusion of a
  12763. function. Thus, we also need to place such code immediately before
  12764. each tail call. These instructions include restoring the callee-saved
  12765. registers, so it is fortunate that the argument passing registers are
  12766. all caller-saved registers!
  12767. One last note regarding which instruction to use to make the tail
  12768. call. When the callee is finished, it should not return to the current
  12769. function, but it should return to the function that called the current
  12770. one. Thus, the return address that is already on the stack is the
  12771. right one and we should not use \key{callq} to make the tail call, as
  12772. that would overwrite the return address. Instead we simply use the
  12773. \key{jmp} instruction. Like the indirect function call, we write an
  12774. \emph{indirect jump}\index{subject}{indirect jump} with a register
  12775. prefixed with an asterisk. We recommend using \code{rax} to hold the
  12776. jump target because the conclusion can overwrite just about everything
  12777. else.
  12778. \begin{lstlisting}
  12779. jmp *%rax
  12780. \end{lstlisting}
  12781. \section{Shrink \LangFun{}}
  12782. \label{sec:shrink-r4}
  12783. The \code{shrink} pass performs a minor modification to ease the
  12784. later passes. This pass introduces an explicit \code{main} function
  12785. that gobbles up all the top-level statements of the module.
  12786. %
  12787. \racket{It also changes the top \code{ProgramDefsExp} form to
  12788. \code{ProgramDefs}.}
  12789. {\if\edition\racketEd
  12790. \begin{lstlisting}
  12791. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12792. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12793. \end{lstlisting}
  12794. where $\itm{mainDef}$ is
  12795. \begin{lstlisting}
  12796. (Def 'main '() 'Integer '() |$\Exp'$|)
  12797. \end{lstlisting}
  12798. \fi}
  12799. {\if\edition\pythonEd
  12800. \begin{lstlisting}
  12801. Module(|$\Def\ldots\Stmt\ldots$|)
  12802. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12803. \end{lstlisting}
  12804. where $\itm{mainDef}$ is
  12805. \begin{lstlisting}
  12806. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12807. \end{lstlisting}
  12808. \fi}
  12809. \section{Reveal Functions and the \LangFunRef{} language}
  12810. \label{sec:reveal-functions-r4}
  12811. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12812. in that it conflates the use of function names and local
  12813. variables. This is a problem because we need to compile the use of a
  12814. function name differently than the use of a local variable. In
  12815. particular, we use \code{leaq} to convert the function name (a label
  12816. in x86) to an address in a register. Thus, we create a new pass that
  12817. changes function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where
  12818. $n$ is the arity of the function.\python{\footnote{The arity is not
  12819. needed in this chapter but is used in Chapter~\ref{ch:Ldyn}.}}
  12820. This pass is named \code{reveal\_functions} and the output language
  12821. is \LangFunRef{}.
  12822. %is defined in Figure~\ref{fig:f1-syntax}.
  12823. %% The concrete syntax for a
  12824. %% function reference is $\CFUNREF{f}$.
  12825. %% \begin{figure}[tp]
  12826. %% \centering
  12827. %% \fbox{
  12828. %% \begin{minipage}{0.96\textwidth}
  12829. %% {\if\edition\racketEd
  12830. %% \[
  12831. %% \begin{array}{lcl}
  12832. %% \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  12833. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12834. %% \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12835. %% \end{array}
  12836. %% \]
  12837. %% \fi}
  12838. %% {\if\edition\pythonEd
  12839. %% \[
  12840. %% \begin{array}{lcl}
  12841. %% \Exp &::=& \FUNREF{\Var}{\Int}\\
  12842. %% \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12843. %% \end{array}
  12844. %% \]
  12845. %% \fi}
  12846. %% \end{minipage}
  12847. %% }
  12848. %% \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12849. %% (Figure~\ref{fig:Lfun-syntax}).}
  12850. %% \label{fig:f1-syntax}
  12851. %% \end{figure}
  12852. %% Distinguishing between calls in tail position and non-tail position
  12853. %% requires the pass to have some notion of context. We recommend using
  12854. %% two mutually recursive functions, one for processing expressions in
  12855. %% tail position and another for the rest.
  12856. \racket{Placing this pass after \code{uniquify} will make sure that
  12857. there are no local variables and functions that share the same
  12858. name.}
  12859. %
  12860. The \code{reveal\_functions} pass should come before the
  12861. \code{remove\_complex\_operands} pass because function references
  12862. should be categorized as complex expressions.
  12863. \section{Limit Functions}
  12864. \label{sec:limit-functions-r4}
  12865. Recall that we wish to limit the number of function parameters to six
  12866. so that we do not need to use the stack for argument passing, which
  12867. makes it easier to implement efficient tail calls. However, because
  12868. the input language \LangFun{} supports arbitrary numbers of function
  12869. arguments, we have some work to do!
  12870. This pass transforms functions and function calls that involve more
  12871. than six arguments to pass the first five arguments as usual, but it
  12872. packs the rest of the arguments into a tuple and passes it as the
  12873. sixth argument.
  12874. Each function definition with seven or more parameters is transformed as
  12875. follows.
  12876. {\if\edition\racketEd
  12877. \begin{lstlisting}
  12878. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12879. |$\Rightarrow$|
  12880. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12881. \end{lstlisting}
  12882. \fi}
  12883. {\if\edition\pythonEd
  12884. \begin{lstlisting}
  12885. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12886. |$\Rightarrow$|
  12887. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12888. |$T_r$|, None, |$\itm{body}'$|, None)
  12889. \end{lstlisting}
  12890. \fi}
  12891. %
  12892. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12893. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12894. the $k$th element of the tuple, where $k = i - 6$.
  12895. %
  12896. {\if\edition\racketEd
  12897. \begin{lstlisting}
  12898. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12899. \end{lstlisting}
  12900. \fi}
  12901. {\if\edition\pythonEd
  12902. \begin{lstlisting}
  12903. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12904. \end{lstlisting}
  12905. \fi}
  12906. For function calls with too many arguments, the \code{limit\_functions}
  12907. pass transforms them in the following way.
  12908. \begin{tabular}{lll}
  12909. \begin{minipage}{0.3\textwidth}
  12910. {\if\edition\racketEd
  12911. \begin{lstlisting}
  12912. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12913. \end{lstlisting}
  12914. \fi}
  12915. {\if\edition\pythonEd
  12916. \begin{lstlisting}
  12917. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12918. \end{lstlisting}
  12919. \fi}
  12920. \end{minipage}
  12921. &
  12922. $\Rightarrow$
  12923. &
  12924. \begin{minipage}{0.5\textwidth}
  12925. {\if\edition\racketEd
  12926. \begin{lstlisting}
  12927. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12928. \end{lstlisting}
  12929. \fi}
  12930. {\if\edition\pythonEd
  12931. \begin{lstlisting}
  12932. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12933. \end{lstlisting}
  12934. \fi}
  12935. \end{minipage}
  12936. \end{tabular}
  12937. \section{Remove Complex Operands}
  12938. \label{sec:rco-r4}
  12939. The primary decisions to make for this pass are whether to classify
  12940. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12941. atomic or complex expressions. Recall that an atomic expression will
  12942. end up as an immediate argument of an x86 instruction. Function
  12943. application will be translated to a sequence of instructions, so
  12944. \racket{\code{Apply}}\python{\code{Call}} must be classified as
  12945. complex expression. On the other hand, the arguments of
  12946. \racket{\code{Apply}}\python{\code{Call}} should be atomic
  12947. expressions.
  12948. %
  12949. Regarding \code{FunRef}, as discussed above, the function label needs
  12950. to be converted to an address using the \code{leaq} instruction. Thus,
  12951. even though \code{FunRef} seems rather simple, it needs to be
  12952. classified as a complex expression so that we generate an assignment
  12953. statement with a left-hand side that can serve as the target of the
  12954. \code{leaq}.
  12955. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12956. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12957. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12958. %
  12959. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12960. % TODO: Return?
  12961. %% Figure~\ref{fig:Lfun-anf-syntax} defines the output language
  12962. %% \LangFunANF{} of this pass.
  12963. %% \begin{figure}[tp]
  12964. %% \centering
  12965. %% \fbox{
  12966. %% \begin{minipage}{0.96\textwidth}
  12967. %% \small
  12968. %% \[
  12969. %% \begin{array}{rcl}
  12970. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12971. %% \MID \VOID{} } \\
  12972. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12973. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12974. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12975. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12976. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12977. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12978. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12979. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12980. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12981. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12982. %% \end{array}
  12983. %% \]
  12984. %% \end{minipage}
  12985. %% }
  12986. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12987. %% \label{fig:Lfun-anf-syntax}
  12988. %% \end{figure}
  12989. \section{Explicate Control and the \LangCFun{} language}
  12990. \label{sec:explicate-control-r4}
  12991. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12992. output of \code{explicate\_control}.
  12993. %
  12994. %% \racket{(The concrete syntax is given in
  12995. %% Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12996. %
  12997. The auxiliary functions for assignment\racket{ and tail contexts} should
  12998. be updated with cases for
  12999. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  13000. function for predicate context should be updated for
  13001. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  13002. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  13003. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  13004. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  13005. auxiliary function for processing function definitions. This code is
  13006. similar to the case for \code{Program} in \LangVec{}. The top-level
  13007. \code{explicate\_control} function that handles the \code{ProgramDefs}
  13008. form of \LangFun{} can then apply this new function to all the
  13009. function definitions.
  13010. {\if\edition\pythonEd
  13011. The translation of \code{Return} statements requires a new auxiliary
  13012. function to handle expressions in tail context, called
  13013. \code{explicate\_tail}. The function should take an expression and the
  13014. dictionary of basic blocks and produce a list of statements in the
  13015. \LangCFun{} language. The \code{explicate\_tail} function should
  13016. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  13017. and a default case for other kinds of expressions. The default case
  13018. should produce a \code{Return} statement. The case for \code{Call}
  13019. should change it into \code{TailCall}. The other cases should
  13020. recursively process their subexpressions and statements, choosing the
  13021. appropriate explicate functions for the various contexts.
  13022. \fi}
  13023. \newcommand{\CfunASTRacket}{
  13024. \begin{array}{lcl}
  13025. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  13026. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  13027. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  13028. \end{array}
  13029. }
  13030. \newcommand{\CfunASTPython}{
  13031. \begin{array}{lcl}
  13032. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  13033. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  13034. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  13035. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  13036. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  13037. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  13038. \end{array}
  13039. }
  13040. \begin{figure}[tp]
  13041. \fbox{
  13042. \begin{minipage}{0.96\textwidth}
  13043. \small
  13044. {\if\edition\racketEd
  13045. \[
  13046. \begin{array}{l}
  13047. \gray{\CvarASTRacket} \\ \hline
  13048. \gray{\CifASTRacket} \\ \hline
  13049. \gray{\CloopASTRacket} \\ \hline
  13050. \gray{\CtupASTRacket} \\ \hline
  13051. \CfunASTRacket \\
  13052. \begin{array}{lcl}
  13053. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13054. \end{array}
  13055. \end{array}
  13056. \]
  13057. \fi}
  13058. {\if\edition\pythonEd
  13059. \[
  13060. \begin{array}{l}
  13061. \gray{\CifASTPython} \\ \hline
  13062. \gray{\CtupASTPython} \\ \hline
  13063. \CfunASTPython \\
  13064. \begin{array}{lcl}
  13065. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13066. \end{array}
  13067. \end{array}
  13068. \]
  13069. \fi}
  13070. \end{minipage}
  13071. }
  13072. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  13073. \label{fig:c3-syntax}
  13074. \end{figure}
  13075. \clearpage
  13076. \section{Select Instructions and the \LangXIndCall{} Language}
  13077. \label{sec:select-r4}
  13078. \index{subject}{instruction selection}
  13079. The output of select instructions is a program in the \LangXIndCall{}
  13080. language, whose concrete syntax is defined in
  13081. Figure~\ref{fig:x86-3-concrete} and abstract syntax is defined in
  13082. Figure~\ref{fig:x86-3}. We use the \code{align} directive on the
  13083. labels of function definitions to make sure the bottom three bits are
  13084. zero, which we make use of in Chapter~\ref{ch:Ldyn}. We discuss the
  13085. new instructions as needed in this section. \index{subject}{x86}
  13086. \newcommand{\GrammarXIndCall}{
  13087. \begin{array}{lcl}
  13088. \Instr &::=& \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13089. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13090. \Block &::= & \Instr^{+} \\
  13091. \Def &::= & \code{.globl}\,\code{.align 8}\,\itm{label}\; (\itm{label}\key{:}\, \Block)^{*}
  13092. \end{array}
  13093. }
  13094. \newcommand{\ASTXIndCallRacket}{
  13095. \begin{array}{lcl}
  13096. \Instr &::=& \INDCALLQ{\Arg}{\itm{int}}
  13097. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13098. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13099. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13100. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP}
  13101. \end{array}
  13102. }
  13103. \begin{figure}[tp]
  13104. \fbox{
  13105. \begin{minipage}{0.96\textwidth}
  13106. \small
  13107. \[
  13108. \begin{array}{l}
  13109. \gray{\GrammarXInt} \\ \hline
  13110. \gray{\GrammarXIf} \\ \hline
  13111. \gray{\GrammarXGlobal} \\ \hline
  13112. \GrammarXIndCall \\
  13113. \begin{array}{lcl}
  13114. \LangXIndCallM{} &::= & \Def^{*}
  13115. \end{array}
  13116. \end{array}
  13117. \]
  13118. \end{minipage}
  13119. }
  13120. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  13121. \label{fig:x86-3-concrete}
  13122. \end{figure}
  13123. \begin{figure}[tp]
  13124. \fbox{
  13125. \begin{minipage}{0.96\textwidth}
  13126. \small
  13127. {\if\edition\racketEd
  13128. \[
  13129. \begin{array}{l}
  13130. \gray{\ASTXIntRacket} \\ \hline
  13131. \gray{\ASTXIfRacket} \\ \hline
  13132. \gray{\ASTXGlobalRacket} \\ \hline
  13133. \ASTXIndCallRacket \\
  13134. \begin{array}{lcl}
  13135. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13136. \end{array}
  13137. \end{array}
  13138. \]
  13139. \fi}
  13140. {\if\edition\pythonEd
  13141. \[
  13142. \begin{array}{lcl}
  13143. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13144. \MID \BYTEREG{\Reg} } \\
  13145. &\MID& \gray{ \GLOBAL{\itm{label}} } \MID \FUNREF{\itm{label}}{\Int} \\
  13146. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13147. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13148. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13149. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13150. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13151. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13152. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13153. \end{array}
  13154. \]
  13155. \fi}
  13156. \end{minipage}
  13157. }
  13158. \caption{The abstract syntax of \LangXIndCall{} (extends
  13159. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13160. \label{fig:x86-3}
  13161. \end{figure}
  13162. An assignment of a function reference to a variable becomes a
  13163. load-effective-address instruction as follows, where $\itm{lhs}'$ is
  13164. the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{} to \Arg{} in
  13165. \LangXIndCallVar{}. The \code{FunRef} becomes a \code{Global} AST
  13166. node, whose concrete syntax is instruction-pointer relative
  13167. addressing.
  13168. \begin{center}
  13169. \begin{tabular}{lcl}
  13170. \begin{minipage}{0.35\textwidth}
  13171. {\if\edition\racketEd
  13172. \begin{lstlisting}
  13173. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13174. \end{lstlisting}
  13175. \fi}
  13176. {\if\edition\pythonEd
  13177. \begin{lstlisting}
  13178. |$\itm{lhs}$| = FunRef(|$f$| |$n$|);
  13179. \end{lstlisting}
  13180. \fi}
  13181. \end{minipage}
  13182. &
  13183. $\Rightarrow$\qquad\qquad
  13184. &
  13185. \begin{minipage}{0.3\textwidth}
  13186. \begin{lstlisting}
  13187. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13188. \end{lstlisting}
  13189. \end{minipage}
  13190. \end{tabular}
  13191. \end{center}
  13192. Regarding function definitions, we need to remove the parameters and
  13193. instead perform parameter passing using the conventions discussed in
  13194. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13195. registers. We recommend turning the parameters into local variables
  13196. and generating instructions at the beginning of the function to move
  13197. from the argument passing registers
  13198. (Section~\ref{sec:calling-conventions-fun}) to these local variables.
  13199. {\if\edition\racketEd
  13200. \begin{lstlisting}
  13201. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13202. |$\Rightarrow$|
  13203. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13204. \end{lstlisting}
  13205. \fi}
  13206. {\if\edition\pythonEd
  13207. \begin{lstlisting}
  13208. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13209. |$\Rightarrow$|
  13210. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13211. \end{lstlisting}
  13212. \fi}
  13213. The basic blocks $B'$ are the same as $B$ except that the
  13214. \code{start} block is modified to add the instructions for moving from
  13215. the argument registers to the parameter variables. So the \code{start}
  13216. block of $B$ shown on the left is changed to the code on the right.
  13217. \begin{center}
  13218. \begin{minipage}{0.3\textwidth}
  13219. \begin{lstlisting}
  13220. start:
  13221. |$\itm{instr}_1$|
  13222. |$\cdots$|
  13223. |$\itm{instr}_n$|
  13224. \end{lstlisting}
  13225. \end{minipage}
  13226. $\Rightarrow$
  13227. \begin{minipage}{0.3\textwidth}
  13228. \begin{lstlisting}
  13229. start:
  13230. movq %rdi, |$x_1$|
  13231. movq %rsi, |$x_2$|
  13232. |$\cdots$|
  13233. |$\itm{instr}_1$|
  13234. |$\cdots$|
  13235. |$\itm{instr}_n$|
  13236. \end{lstlisting}
  13237. \end{minipage}
  13238. \end{center}
  13239. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13240. parameters the function expects, but the parameters are no longer in
  13241. the syntax of function definitions. Instead, add an entry to
  13242. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13243. to construct $\itm{info}'$.}
  13244. By changing the parameters to local variables, we are giving the
  13245. register allocator control over which registers or stack locations to
  13246. use for them. If you implemented the move-biasing challenge
  13247. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13248. assign the parameter variables to the corresponding argument register,
  13249. in which case the \code{patch\_instructions} pass will remove the
  13250. \code{movq} instruction. This happens in the example translation in
  13251. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13252. the \code{add} function.
  13253. %
  13254. Also, note that the register allocator will perform liveness analysis
  13255. on this sequence of move instructions and build the interference
  13256. graph. So, for example, $x_1$ will be marked as interfering with
  13257. \code{rsi} and that will prevent the assignment of $x_1$ to
  13258. \code{rsi}, which is good, because that would overwrite the argument
  13259. that needs to move into $x_2$.
  13260. Next, consider the compilation of function calls. In the mirror image
  13261. of the handling of parameters in function definitions, the arguments
  13262. are moved to the argument passing registers. Note that the function
  13263. is not given as a label, but its address is produced by the argument
  13264. $\itm{arg}_0$. So we translate the call into an indirect function
  13265. call. The return value from the function is stored in \code{rax}, so
  13266. it needs to be moved into the \itm{lhs}.
  13267. \begin{lstlisting}
  13268. |\itm{lhs}| = |$\CALL{\itm{arg}_0}{\itm{arg}_1~\itm{arg}_2 \ldots}$|
  13269. |$\Rightarrow$|
  13270. movq |$\itm{arg}_1$|, %rdi
  13271. movq |$\itm{arg}_2$|, %rsi
  13272. |$\vdots$|
  13273. callq *|$\itm{arg}_0$|
  13274. movq %rax, |$\itm{lhs}$|
  13275. \end{lstlisting}
  13276. The \code{IndirectCallq} AST node includes an integer for the arity of
  13277. the function, i.e., the number of parameters. That information is
  13278. useful in the \code{uncover\_live} pass for determining which
  13279. argument-passing registers are potentially read during the call.
  13280. For tail calls, the parameter passing is the same as non-tail calls:
  13281. generate instructions to move the arguments into the argument
  13282. passing registers. After that we need to pop the frame from the
  13283. procedure call stack. However, we do not yet know how big the frame
  13284. is; that gets determined during register allocation. So instead of
  13285. generating those instructions here, we invent a new instruction that
  13286. means ``pop the frame and then do an indirect jump'', which we name
  13287. \code{TailJmp}. The abstract syntax for this instruction includes an
  13288. argument that specifies where to jump and an integer that represents
  13289. the arity of the function being called.
  13290. Recall that we use the label \code{start} for the initial block of a
  13291. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13292. the conclusion of the program with \code{conclusion}, so that
  13293. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13294. by a jump to \code{conclusion}. With the addition of function
  13295. definitions, there is a start block and conclusion for each function,
  13296. but their labels need to be unique. We recommend prepending the
  13297. function's name to \code{start} and \code{conclusion}, respectively,
  13298. to obtain unique labels.
  13299. \section{Register Allocation}
  13300. \label{sec:register-allocation-r4}
  13301. The addition of functions requires some changes to all three aspects
  13302. of register allocation, which we discuss in the following subsections.
  13303. \subsection{Liveness Analysis}
  13304. \label{sec:liveness-analysis-r4}
  13305. \index{subject}{liveness analysis}
  13306. %% The rest of the passes need only minor modifications to handle the new
  13307. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13308. %% \code{leaq}.
  13309. The \code{IndirectCallq} instruction should be treated like
  13310. \code{Callq} regarding its written locations $W$, in that they should
  13311. include all the caller-saved registers. Recall that the reason for
  13312. that is to force variables that are live across a function call to be assigned to callee-saved
  13313. registers or to be spilled to the stack.
  13314. Regarding the set of read locations $R$, the arity field of
  13315. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13316. argument-passing registers should be considered as read by those
  13317. instructions. Also, the target field of \code{TailJmp} and
  13318. \code{IndirectCallq} should be included in the set of read locations
  13319. $R$.
  13320. \subsection{Build Interference Graph}
  13321. \label{sec:build-interference-r4}
  13322. With the addition of function definitions, we compute a separate interference
  13323. graph for each function (not just one for the whole program).
  13324. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13325. spill tuple-typed variables that are live during a call to
  13326. \code{collect}, the garbage collector. With the addition of functions
  13327. to our language, we need to revisit this issue. Functions that perform
  13328. allocation contain calls to the collector. Thus, we should not only
  13329. spill a tuple-typed variable when it is live during a call to
  13330. \code{collect}, but we should spill the variable if it is live during
  13331. call to any user-defined function. Thus, in the
  13332. \code{build\_interference} pass, we recommend adding interference
  13333. edges between call-live tuple-typed variables and the callee-saved
  13334. registers (in addition to the usual addition of edges between
  13335. call-live variables and the caller-saved registers).
  13336. \subsection{Allocate Registers}
  13337. The primary change to the \code{allocate\_registers} pass is adding an
  13338. auxiliary function for handling definitions (the \Def{} non-terminal
  13339. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13340. logic is the same as described in
  13341. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13342. allocation is performed many times, once for each function definition,
  13343. instead of just once for the whole program.
  13344. \section{Patch Instructions}
  13345. In \code{patch\_instructions}, you should deal with the x86
  13346. idiosyncrasy that the destination argument of \code{leaq} must be a
  13347. register. Additionally, you should ensure that the argument of
  13348. \code{TailJmp} is \itm{rax}, our reserved register---because we
  13349. trample many other registers before the tail call (as explained in the
  13350. next section).
  13351. \section{Prelude and Conclusion}
  13352. Now that register allocation is complete, we can translate the
  13353. \code{TailJmp} into a sequence of instructions. A naive translation of
  13354. \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}. However,
  13355. before the jump we need to pop the current frame to achieve efficient
  13356. tail calls. This sequence of instructions is the same as the code for
  13357. the conclusion of a function, except the \code{retq} is replaced with
  13358. \code{jmp *$\itm{arg}$}.
  13359. Regarding function definitions, we generate a prelude and conclusion
  13360. for each one. This code is similar to the prelude and conclusion
  13361. generated for the \code{main} function in Chapter~\ref{ch:Lvec}. To
  13362. review, the prelude of every function should carry out the following
  13363. steps.
  13364. % TODO: .align the functions!
  13365. \begin{enumerate}
  13366. %% \item Start with \code{.global} and \code{.align} directives followed
  13367. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13368. %% example.)
  13369. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13370. pointer.
  13371. \item Push to the stack all of the callee-saved registers that were
  13372. used for register allocation.
  13373. \item Move the stack pointer \code{rsp} down to make room for the
  13374. regular spills. (Aligned to 16 bytes.)
  13375. \item Move the root stack pointer \code{r15} up by the size of the
  13376. root-stack frame for this function, which depends on the number of
  13377. spilled tuple-typed variables. \label{root-stack-init}
  13378. \item Initialize to zero all new entries in the root-stack frame.
  13379. \item Jump to the start block.
  13380. \end{enumerate}
  13381. The prelude of the \code{main} function has an additional task: call
  13382. the \code{initialize} function to set up the garbage collector and
  13383. then move the value of the global \code{rootstack\_begin} in
  13384. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13385. above, which depends on \code{r15}.
  13386. The conclusion of every function should do the following.
  13387. \begin{enumerate}
  13388. \item Move the stack pointer back up past the regular spills.
  13389. \item Restore the callee-saved registers by popping them from the
  13390. stack.
  13391. \item Move the root stack pointer back down by the size of the
  13392. root-stack frame for this function.
  13393. \item Restore \code{rbp} by popping it from the stack.
  13394. \item Return to the caller with the \code{retq} instruction.
  13395. \end{enumerate}
  13396. \begin{exercise}\normalfont\normalsize
  13397. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13398. Create 8 new programs that use functions, including examples that pass
  13399. functions and return functions from other functions, recursive
  13400. functions, functions that create vectors, and functions that make tail
  13401. calls. Test your compiler on these new programs and all of your
  13402. previously created test programs.
  13403. \end{exercise}
  13404. \begin{figure}[tbp]
  13405. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13406. \node (Lfun) at (0,2) {\large \LangFun{}};
  13407. \node (Lfun-1) at (3,2) {\large \LangFun{}};
  13408. \node (Lfun-2) at (6,2) {\large \LangFun{}};
  13409. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13410. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13411. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13412. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  13413. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  13414. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13415. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13416. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13417. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13418. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13419. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13420. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13421. \path[->,bend left=15] (Lfun) edge [above] node
  13422. {\ttfamily\footnotesize shrink} (Lfun-1);
  13423. \path[->,bend left=15] (Lfun-1) edge [above] node
  13424. {\ttfamily\footnotesize uniquify} (Lfun-2);
  13425. \path[->,bend left=15] (Lfun-2) edge [above] node
  13426. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13427. \path[->,bend left=15] (F1-1) edge [left] node
  13428. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13429. \path[->,bend left=15] (F1-2) edge [below] node
  13430. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13431. \path[->,bend left=15] (F1-3) edge [below] node
  13432. {\ttfamily\footnotesize uncover\_get!} (F1-4);
  13433. \path[->,bend right=15] (F1-4) edge [above] node
  13434. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  13435. \path[->,bend right=15] (F1-5) edge [left] node
  13436. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13437. \path[->,bend right=15] (C3-2) edge [left] node
  13438. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13439. \path[->,bend left=15] (x86-2) edge [left] node
  13440. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13441. \path[->,bend right=15] (x86-2-1) edge [below] node
  13442. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13443. \path[->,bend right=15] (x86-2-2) edge [left] node
  13444. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13445. \path[->,bend left=15] (x86-3) edge [above] node
  13446. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13447. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize prelude.} (x86-5);
  13448. \end{tikzpicture}
  13449. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13450. \label{fig:Lfun-passes}
  13451. \end{figure}
  13452. Figure~\ref{fig:Lfun-passes} gives an overview of the passes for
  13453. compiling \LangFun{} to x86.
  13454. \section{An Example Translation}
  13455. \label{sec:functions-example}
  13456. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13457. function in \LangFun{} to x86. The figure also includes the results of the
  13458. \code{explicate\_control} and \code{select\_instructions} passes.
  13459. \begin{figure}[htbp]
  13460. \begin{tabular}{ll}
  13461. \begin{minipage}{0.4\textwidth}
  13462. % s3_2.rkt
  13463. {\if\edition\racketEd
  13464. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13465. (define (add [x : Integer]
  13466. [y : Integer])
  13467. : Integer
  13468. (+ x y))
  13469. (add 40 2)
  13470. \end{lstlisting}
  13471. \fi}
  13472. {\if\edition\pythonEd
  13473. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13474. def add(x:int, y:int) -> int:
  13475. return x + y
  13476. print(add(40, 2))
  13477. \end{lstlisting}
  13478. \fi}
  13479. $\Downarrow$
  13480. {\if\edition\racketEd
  13481. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13482. (define (add86 [x87 : Integer]
  13483. [y88 : Integer])
  13484. : Integer
  13485. add86start:
  13486. return (+ x87 y88);
  13487. )
  13488. (define (main) : Integer ()
  13489. mainstart:
  13490. tmp89 = (fun-ref add86 2);
  13491. (tail-call tmp89 40 2)
  13492. )
  13493. \end{lstlisting}
  13494. \fi}
  13495. {\if\edition\pythonEd
  13496. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13497. def add(x:int, y:int) -> int:
  13498. addstart:
  13499. return x + y
  13500. def main() -> int:
  13501. mainstart:
  13502. fun.0 = add
  13503. tmp.1 = fun.0(40, 2)
  13504. print(tmp.1)
  13505. return 0
  13506. \end{lstlisting}
  13507. \fi}
  13508. \end{minipage}
  13509. &
  13510. $\Rightarrow$
  13511. \begin{minipage}{0.5\textwidth}
  13512. {\if\edition\racketEd
  13513. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13514. (define (add86) : Integer
  13515. add86start:
  13516. movq %rdi, x87
  13517. movq %rsi, y88
  13518. movq x87, %rax
  13519. addq y88, %rax
  13520. jmp inc1389conclusion
  13521. )
  13522. (define (main) : Integer
  13523. mainstart:
  13524. leaq (fun-ref add86 2), tmp89
  13525. movq $40, %rdi
  13526. movq $2, %rsi
  13527. tail-jmp tmp89
  13528. )
  13529. \end{lstlisting}
  13530. \fi}
  13531. {\if\edition\pythonEd
  13532. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13533. def add() -> int:
  13534. addstart:
  13535. movq %rdi, x
  13536. movq %rsi, y
  13537. movq x, %rax
  13538. addq y, %rax
  13539. jmp addconclusion
  13540. def main() -> int:
  13541. mainstart:
  13542. leaq add, fun.0
  13543. movq $40, %rdi
  13544. movq $2, %rsi
  13545. callq *fun.0
  13546. movq %rax, tmp.1
  13547. movq tmp.1, %rdi
  13548. callq print_int
  13549. movq $0, %rax
  13550. jmp mainconclusion
  13551. \end{lstlisting}
  13552. \fi}
  13553. $\Downarrow$
  13554. \end{minipage}
  13555. \end{tabular}
  13556. \begin{tabular}{ll}
  13557. \begin{minipage}{0.3\textwidth}
  13558. {\if\edition\racketEd
  13559. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13560. .globl add86
  13561. .align 8
  13562. add86:
  13563. pushq %rbp
  13564. movq %rsp, %rbp
  13565. jmp add86start
  13566. add86start:
  13567. movq %rdi, %rax
  13568. addq %rsi, %rax
  13569. jmp add86conclusion
  13570. add86conclusion:
  13571. popq %rbp
  13572. retq
  13573. \end{lstlisting}
  13574. \fi}
  13575. {\if\edition\pythonEd
  13576. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13577. .align 8
  13578. add:
  13579. pushq %rbp
  13580. movq %rsp, %rbp
  13581. subq $0, %rsp
  13582. jmp addstart
  13583. addstart:
  13584. movq %rdi, %rdx
  13585. movq %rsi, %rcx
  13586. movq %rdx, %rax
  13587. addq %rcx, %rax
  13588. jmp addconclusion
  13589. addconclusion:
  13590. subq $0, %r15
  13591. addq $0, %rsp
  13592. popq %rbp
  13593. retq
  13594. \end{lstlisting}
  13595. \fi}
  13596. \end{minipage}
  13597. &
  13598. \begin{minipage}{0.5\textwidth}
  13599. {\if\edition\racketEd
  13600. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13601. .globl main
  13602. .align 8
  13603. main:
  13604. pushq %rbp
  13605. movq %rsp, %rbp
  13606. movq $16384, %rdi
  13607. movq $16384, %rsi
  13608. callq initialize
  13609. movq rootstack_begin(%rip), %r15
  13610. jmp mainstart
  13611. mainstart:
  13612. leaq add86(%rip), %rcx
  13613. movq $40, %rdi
  13614. movq $2, %rsi
  13615. movq %rcx, %rax
  13616. popq %rbp
  13617. jmp *%rax
  13618. mainconclusion:
  13619. popq %rbp
  13620. retq
  13621. \end{lstlisting}
  13622. \fi}
  13623. {\if\edition\pythonEd
  13624. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13625. .globl main
  13626. .align 8
  13627. main:
  13628. pushq %rbp
  13629. movq %rsp, %rbp
  13630. subq $0, %rsp
  13631. movq $65536, %rdi
  13632. movq $65536, %rsi
  13633. callq initialize
  13634. movq rootstack_begin(%rip), %r15
  13635. jmp mainstart
  13636. mainstart:
  13637. leaq add(%rip), %rcx
  13638. movq $40, %rdi
  13639. movq $2, %rsi
  13640. callq *%rcx
  13641. movq %rax, %rcx
  13642. movq %rcx, %rdi
  13643. callq print_int
  13644. movq $0, %rax
  13645. jmp mainconclusion
  13646. mainconclusion:
  13647. subq $0, %r15
  13648. addq $0, %rsp
  13649. popq %rbp
  13650. retq
  13651. \end{lstlisting}
  13652. \fi}
  13653. \end{minipage}
  13654. \end{tabular}
  13655. \caption{Example compilation of a simple function to x86.}
  13656. \label{fig:add-fun}
  13657. \end{figure}
  13658. % Challenge idea: inlining! (simple version)
  13659. % Further Reading
  13660. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13661. \chapter{Lexically Scoped Functions}
  13662. \label{ch:Llambda}
  13663. \index{subject}{lambda}
  13664. \index{subject}{lexical scoping}
  13665. This chapter studies lexically scoped functions. Lexical scoping means
  13666. that a function's body may refer to variables whose binding site is
  13667. outside of the function, in an enclosing scope.
  13668. %
  13669. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13670. \LangLam{}, which extends \LangFun{} with the \key{lambda} form for
  13671. creating lexically scoped functions. The body of the \key{lambda}
  13672. refers to three variables: \code{x}, \code{y}, and \code{z}. The
  13673. binding sites for \code{x} and \code{y} are outside of the
  13674. \key{lambda}. Variable \code{y} is \racket{bound by the enclosing
  13675. \key{let}}\python{a local variable of function \code{f}} and
  13676. \code{x} is a parameter of function \code{f}. Note that function
  13677. \code{f} returns the \key{lambda} as its result value. The main
  13678. expression of the program includes two calls to \code{f} with
  13679. different arguments for \code{x}, first \code{5} then \code{3}. The
  13680. functions returned from \code{f} are bound to variables \code{g} and
  13681. \code{h}. Even though these two functions were created by the same
  13682. \code{lambda}, they are really different functions because they use
  13683. different values for \code{x}. Applying \code{g} to \code{11} produces
  13684. \code{20} whereas applying \code{h} to \code{15} produces \code{22},
  13685. so the result of the program is \code{42}.
  13686. \begin{figure}[btp]
  13687. {\if\edition\racketEd
  13688. % lambda_test_21.rkt
  13689. \begin{lstlisting}
  13690. (define (f [x : Integer]) : (Integer -> Integer)
  13691. (let ([y 4])
  13692. (lambda: ([z : Integer]) : Integer
  13693. (+ x (+ y z)))))
  13694. (let ([g (f 5)])
  13695. (let ([h (f 3)])
  13696. (+ (g 11) (h 15))))
  13697. \end{lstlisting}
  13698. \fi}
  13699. {\if\edition\pythonEd
  13700. \begin{lstlisting}
  13701. def f(x : int) -> Callable[[int], int]:
  13702. y = 4
  13703. return lambda z: x + y + z
  13704. g = f(5)
  13705. h = f(3)
  13706. print( g(11) + h(15) )
  13707. \end{lstlisting}
  13708. \fi}
  13709. \caption{Example of a lexically scoped function.}
  13710. \label{fig:lexical-scoping}
  13711. \end{figure}
  13712. The approach that we take for implementing lexically scoped functions
  13713. is to compile them into top-level function definitions, translating
  13714. from \LangLam{} into \LangFun{}. However, the compiler must give
  13715. special treatment to variable occurrences such as \code{x} and
  13716. \code{y} in the body of the \code{lambda} of
  13717. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13718. may not refer to variables defined outside of it. To identify such
  13719. variable occurrences, we review the standard notion of free variable.
  13720. \begin{definition}
  13721. A variable is \textbf{free in expression} $e$ if the variable occurs
  13722. inside $e$ but does not have an enclosing definition that is also in
  13723. $e$.\index{subject}{free variable}
  13724. \end{definition}
  13725. For example, in the expression
  13726. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13727. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13728. only \code{x} and \code{y} are free in the following expression
  13729. because \code{z} is defined by the \code{lambda}.
  13730. {\if\edition\racketEd
  13731. \begin{lstlisting}
  13732. (lambda: ([z : Integer]) : Integer
  13733. (+ x (+ y z)))
  13734. \end{lstlisting}
  13735. \fi}
  13736. {\if\edition\pythonEd
  13737. \begin{lstlisting}
  13738. lambda z: x + y + z
  13739. \end{lstlisting}
  13740. \fi}
  13741. %
  13742. So the free variables of a \code{lambda} are the ones that need
  13743. special treatment. We need to transport, at runtime, the values of
  13744. those variables from the point where the \code{lambda} was created to
  13745. the point where the \code{lambda} is applied. An efficient solution to
  13746. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13747. of the free variables together with a function pointer into a tuple,
  13748. an arrangement called a \emph{flat closure} (which we shorten to just
  13749. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  13750. %
  13751. By design, we have all the ingredients to make closures:
  13752. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13753. function pointers. The function pointer resides at index $0$ and the
  13754. values for the free variables fill in the rest of the tuple.
  13755. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13756. how closures work. It is a three-step dance. The program calls
  13757. function \code{f}, which creates a closure for the \code{lambda}. The
  13758. closure is a tuple whose first element is a pointer to the top-level
  13759. function that we will generate for the \code{lambda}, the second
  13760. element is the value of \code{x}, which is \code{5}, and the third
  13761. element is \code{4}, the value of \code{y}. The closure does not
  13762. contain an element for \code{z} because \code{z} is not a free
  13763. variable of the \code{lambda}. Creating the closure is step 1 of the
  13764. dance. The closure is returned from \code{f} and bound to \code{g}, as
  13765. shown in Figure~\ref{fig:closures}.
  13766. %
  13767. The second call to \code{f} creates another closure, this time with
  13768. \code{3} in the second slot (for \code{x}). This closure is also
  13769. returned from \code{f} but bound to \code{h}, which is also shown in
  13770. Figure~\ref{fig:closures}.
  13771. \begin{figure}[tbp]
  13772. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13773. \caption{Flat closure representations for the two functions
  13774. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13775. \label{fig:closures}
  13776. \end{figure}
  13777. Continuing with the example, consider the application of \code{g} to
  13778. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13779. obtain the function pointer from the first element of the closure and
  13780. call it, passing in the closure itself and then the regular arguments,
  13781. in this case \code{11}. This technique for applying a closure is step
  13782. 2 of the dance.
  13783. %
  13784. But doesn't this \code{lambda} only take 1 argument, for parameter
  13785. \code{z}? The third and final step of the dance is generating a
  13786. top-level function for a \code{lambda}. We add an additional
  13787. parameter for the closure and we insert an initialization at the beginning
  13788. of the function for each free variable, to bind those variables to the
  13789. appropriate elements from the closure parameter.
  13790. %
  13791. This three-step dance is known as \emph{closure conversion}. We
  13792. discuss the details of closure conversion in
  13793. Section~\ref{sec:closure-conversion} and show the code generated from
  13794. the example in Section~\ref{sec:example-lambda}. But first we define
  13795. the syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13796. \section{The \LangLam{} Language}
  13797. \label{sec:r5}
  13798. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13799. functions and lexical scoping, is defined in
  13800. Figures~\ref{fig:Llam-concrete-syntax} and \ref{fig:Llam-syntax}. It adds
  13801. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13802. syntax for function application.
  13803. %
  13804. \python{The syntax also includes an assignment statement that includes
  13805. a type annotation for the variable on the left-hand side, which
  13806. facilitates the type checking of \code{lambda} expressions that we
  13807. discuss later in this section.}
  13808. %
  13809. \racket{The \code{procedure-arity} operation returns the number of parameters
  13810. of a given function, an operation that we need for the translation
  13811. of dynamic typing in Chapter~\ref{ch:Ldyn}.}
  13812. %
  13813. \python{The \code{arity} operation returns the number of parameters of
  13814. a given function, an operation that we need for the translation
  13815. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  13816. The \code{arity} operation is not in Python, but the same functionality
  13817. is available in a more complex form. We include \code{arity} in the
  13818. \LangLam{} source language to enable testing.}
  13819. \newcommand{\LlambdaGrammarRacket}{
  13820. \begin{array}{lcl}
  13821. \Exp &::=& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} \\
  13822. &\MID& \LP \key{procedure-arity}~\Exp\RP
  13823. \end{array}
  13824. }
  13825. \newcommand{\LlambdaASTRacket}{
  13826. \begin{array}{lcl}
  13827. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}\\
  13828. \itm{op} &::=& \code{procedure-arity}
  13829. \end{array}
  13830. }
  13831. \newcommand{\LlambdaGrammarPython}{
  13832. \begin{array}{lcl}
  13833. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  13834. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13835. \end{array}
  13836. }
  13837. \newcommand{\LlambdaASTPython}{
  13838. \begin{array}{lcl}
  13839. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  13840. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13841. \end{array}
  13842. }
  13843. % include AnnAssign in ASTPython
  13844. \begin{figure}[tp]
  13845. \centering
  13846. \fbox{
  13847. \begin{minipage}{0.96\textwidth}
  13848. \small
  13849. {\if\edition\racketEd
  13850. \[
  13851. \begin{array}{l}
  13852. \gray{\LintGrammarRacket{}} \\ \hline
  13853. \gray{\LvarGrammarRacket{}} \\ \hline
  13854. \gray{\LifGrammarRacket{}} \\ \hline
  13855. \gray{\LwhileGrammarRacket} \\ \hline
  13856. \gray{\LtupGrammarRacket} \\ \hline
  13857. \gray{\LfunGrammarRacket} \\ \hline
  13858. \LlambdaGrammarRacket \\
  13859. \begin{array}{lcl}
  13860. \LangLamM{} &::=& \Def\ldots \; \Exp
  13861. \end{array}
  13862. \end{array}
  13863. \]
  13864. \fi}
  13865. {\if\edition\pythonEd
  13866. \[
  13867. \begin{array}{l}
  13868. \gray{\LintGrammarPython{}} \\ \hline
  13869. \gray{\LvarGrammarPython{}} \\ \hline
  13870. \gray{\LifGrammarPython{}} \\ \hline
  13871. \gray{\LwhileGrammarPython} \\ \hline
  13872. \gray{\LtupGrammarPython} \\ \hline
  13873. \gray{\LfunGrammarPython} \\ \hline
  13874. \LlambdaGrammarPython \\
  13875. \begin{array}{lcl}
  13876. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13877. \end{array}
  13878. \end{array}
  13879. \]
  13880. \fi}
  13881. \end{minipage}
  13882. }
  13883. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-concrete-syntax})
  13884. with \key{lambda}.}
  13885. \label{fig:Llam-concrete-syntax}
  13886. \end{figure}
  13887. \begin{figure}[tp]
  13888. \centering
  13889. \fbox{
  13890. \begin{minipage}{0.96\textwidth}
  13891. \small
  13892. {\if\edition\racketEd
  13893. \[
  13894. \begin{array}{l}
  13895. \gray{\LintOpAST} \\ \hline
  13896. \gray{\LvarASTRacket{}} \\ \hline
  13897. \gray{\LifASTRacket{}} \\ \hline
  13898. \gray{\LwhileASTRacket{}} \\ \hline
  13899. \gray{\LtupASTRacket{}} \\ \hline
  13900. \gray{\LfunASTRacket} \\ \hline
  13901. \LlambdaASTRacket \\
  13902. \begin{array}{lcl}
  13903. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13904. \end{array}
  13905. \end{array}
  13906. \]
  13907. \fi}
  13908. {\if\edition\pythonEd
  13909. \[
  13910. \begin{array}{l}
  13911. \gray{\LintASTPython} \\ \hline
  13912. \gray{\LvarASTPython{}} \\ \hline
  13913. \gray{\LifASTPython{}} \\ \hline
  13914. \gray{\LwhileASTPython{}} \\ \hline
  13915. \gray{\LtupASTPython{}} \\ \hline
  13916. \gray{\LfunASTPython} \\ \hline
  13917. \LlambdaASTPython \\
  13918. \begin{array}{lcl}
  13919. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13920. \end{array}
  13921. \end{array}
  13922. \]
  13923. \fi}
  13924. \end{minipage}
  13925. }
  13926. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Lfun-syntax}).}
  13927. \label{fig:Llam-syntax}
  13928. \end{figure}
  13929. \index{subject}{interpreter}
  13930. \label{sec:interp-Llambda}
  13931. Figure~\ref{fig:interp-Llambda} shows the definitional interpreter for
  13932. \LangLam{}. The case for \key{Lambda} saves the current environment
  13933. inside the returned function value. Recall that during function
  13934. application, the environment stored in the function value, extended
  13935. with the mapping of parameters to argument values, is used to
  13936. interpret the body of the function.
  13937. \begin{figure}[tbp]
  13938. {\if\edition\racketEd
  13939. \begin{lstlisting}
  13940. (define interp-Llambda-class
  13941. (class interp-Lfun-class
  13942. (super-new)
  13943. (define/override (interp-op op)
  13944. (match op
  13945. ['procedure-arity
  13946. (lambda (v)
  13947. (match v
  13948. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13949. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13950. [else (super interp-op op)]))
  13951. (define/override ((interp-exp env) e)
  13952. (define recur (interp-exp env))
  13953. (match e
  13954. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13955. `(function ,xs ,body ,env)]
  13956. [else ((super interp-exp env) e)]))
  13957. ))
  13958. (define (interp-Llambda p)
  13959. (send (new interp-Llambda-class) interp-program p))
  13960. \end{lstlisting}
  13961. \fi}
  13962. {\if\edition\pythonEd
  13963. \begin{lstlisting}
  13964. class InterpLlambda(InterpLfun):
  13965. def arity(self, v):
  13966. match v:
  13967. case Function(name, params, body, env):
  13968. return len(params)
  13969. case _:
  13970. raise Exception('Llambda arity unexpected ' + repr(v))
  13971. def interp_exp(self, e, env):
  13972. match e:
  13973. case Call(Name('arity'), [fun]):
  13974. f = self.interp_exp(fun, env)
  13975. return self.arity(f)
  13976. case Lambda(params, body):
  13977. return Function('lambda', params, [Return(body)], env)
  13978. case _:
  13979. return super().interp_exp(e, env)
  13980. def interp_stmts(self, ss, env):
  13981. if len(ss) == 0:
  13982. return
  13983. match ss[0]:
  13984. case AnnAssign(lhs, typ, value, simple):
  13985. env[lhs.id] = self.interp_exp(value, env)
  13986. return self.interp_stmts(ss[1:], env)
  13987. case _:
  13988. return super().interp_stmts(ss, env)
  13989. \end{lstlisting}
  13990. \fi}
  13991. \caption{Interpreter for \LangLam{}.}
  13992. \label{fig:interp-Llambda}
  13993. \end{figure}
  13994. \label{sec:type-check-r5}
  13995. \index{subject}{type checking}
  13996. {\if\edition\racketEd
  13997. %
  13998. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13999. \key{lambda} form. The body of the \key{lambda} is checked in an
  14000. environment that includes the current environment (because it is
  14001. lexically scoped) and also includes the \key{lambda}'s parameters. We
  14002. require the body's type to match the declared return type.
  14003. %
  14004. \fi}
  14005. {\if\edition\pythonEd
  14006. %
  14007. Figures~\ref{fig:type-check-Llambda} and
  14008. \ref{fig:type-check-Llambda-part2} define the type checker for
  14009. \LangLam{}, which is more complex than one might expect. The reason
  14010. for the added complexity is that the syntax of \key{lambda} does not
  14011. include type annotations for the parameters or return type. Instead
  14012. they must be inferred. There are many approaches of type inference to
  14013. choose from of varying degrees of complexity. We choose one of the
  14014. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  14015. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  14016. this book is compilation, not type inference.
  14017. The main idea of bidirectional type inference is to add an auxiliary
  14018. function, here named \code{check\_exp}, that takes an expected type
  14019. and checks whether the given expression is of that type. Thus, in
  14020. \code{check\_exp}, type information flows in a top-down manner with
  14021. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  14022. function, where type information flows in a primarily bottom-up
  14023. manner.
  14024. %
  14025. The idea then is to use \code{check\_exp} in all the places where we
  14026. already know what the type of an expression should be, such as in the
  14027. \code{return} statement of a top-level function definition, or on the
  14028. right-hand side of an annotated assignment statement.
  14029. Getting back to \code{lambda}, it is straightforward to check a
  14030. \code{lambda} inside \code{check\_exp} because the expected type
  14031. provides the parameter types and the return type. On the other hand,
  14032. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  14033. that we do not allow \code{lambda} in contexts where we don't already
  14034. know its type. This restriction does not incur a loss of
  14035. expressiveness for \LangLam{} because it is straightforward to modify
  14036. a program to sidestep the restriction, for example, by using an
  14037. annotated assignment statement to assign the \code{lambda} to a
  14038. temporary variable.
  14039. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  14040. checker records their type in a \code{has\_type} field. This type
  14041. information is used later in this chapter.
  14042. %
  14043. \fi}
  14044. \begin{figure}[tbp]
  14045. {\if\edition\racketEd
  14046. \begin{lstlisting}
  14047. (define (type-check-Llambda env)
  14048. (lambda (e)
  14049. (match e
  14050. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  14051. (define-values (new-body bodyT)
  14052. ((type-check-exp (append (map cons xs Ts) env)) body))
  14053. (define ty `(,@Ts -> ,rT))
  14054. (cond
  14055. [(equal? rT bodyT)
  14056. (values (HasType (Lambda params rT new-body) ty) ty)]
  14057. [else
  14058. (error "mismatch in return type" bodyT rT)])]
  14059. ...
  14060. )))
  14061. \end{lstlisting}
  14062. \fi}
  14063. {\if\edition\pythonEd
  14064. \begin{lstlisting}
  14065. class TypeCheckLlambda(TypeCheckLfun):
  14066. def type_check_exp(self, e, env):
  14067. match e:
  14068. case Name(id):
  14069. e.has_type = env[id]
  14070. return env[id]
  14071. case Lambda(params, body):
  14072. raise Exception('cannot synthesize a type for a lambda')
  14073. case Call(Name('arity'), [func]):
  14074. func_t = self.type_check_exp(func, env)
  14075. match func_t:
  14076. case FunctionType(params_t, return_t):
  14077. return IntType()
  14078. case _:
  14079. raise Exception('in arity, unexpected ' + repr(func_t))
  14080. case _:
  14081. return super().type_check_exp(e, env)
  14082. def check_exp(self, e, ty, env):
  14083. match e:
  14084. case Lambda(params, body):
  14085. e.has_type = ty
  14086. match ty:
  14087. case FunctionType(params_t, return_t):
  14088. new_env = env.copy().update(zip(params, params_t))
  14089. self.check_exp(body, return_t, new_env)
  14090. case _:
  14091. raise Exception('lambda does not have type ' + str(ty))
  14092. case Call(func, args):
  14093. func_t = self.type_check_exp(func, env)
  14094. match func_t:
  14095. case FunctionType(params_t, return_t):
  14096. for (arg, param_t) in zip(args, params_t):
  14097. self.check_exp(arg, param_t, env)
  14098. self.check_type_equal(return_t, ty, e)
  14099. case _:
  14100. raise Exception('type_check_exp: in call, unexpected ' + \
  14101. repr(func_t))
  14102. case _:
  14103. t = self.type_check_exp(e, env)
  14104. self.check_type_equal(t, ty, e)
  14105. \end{lstlisting}
  14106. \fi}
  14107. \caption{Type checking \LangLam{}\python{, part 1}.}
  14108. \label{fig:type-check-Llambda}
  14109. \end{figure}
  14110. {\if\edition\pythonEd
  14111. \begin{figure}[tbp]
  14112. \begin{lstlisting}
  14113. def check_stmts(self, ss, return_ty, env):
  14114. if len(ss) == 0:
  14115. return
  14116. match ss[0]:
  14117. case FunctionDef(name, params, body, dl, returns, comment):
  14118. new_env = env.copy().update(params)
  14119. rt = self.check_stmts(body, returns, new_env)
  14120. self.check_stmts(ss[1:], return_ty, env)
  14121. case Return(value):
  14122. self.check_exp(value, return_ty, env)
  14123. case Assign([Name(id)], value):
  14124. if id in env:
  14125. self.check_exp(value, env[id], env)
  14126. else:
  14127. env[id] = self.type_check_exp(value, env)
  14128. self.check_stmts(ss[1:], return_ty, env)
  14129. case Assign([Subscript(tup, Constant(index), Store())], value):
  14130. tup_t = self.type_check_exp(tup, env)
  14131. match tup_t:
  14132. case TupleType(ts):
  14133. self.check_exp(value, ts[index], env)
  14134. case _:
  14135. raise Exception('expected a tuple, not ' + repr(tup_t))
  14136. self.check_stmts(ss[1:], return_ty, env)
  14137. case AnnAssign(Name(id), ty_annot, value, simple):
  14138. ss[0].annotation = ty_annot
  14139. if id in env:
  14140. self.check_type_equal(env[id], ty_annot)
  14141. else:
  14142. env[id] = ty_annot
  14143. self.check_exp(value, ty_annot, env)
  14144. self.check_stmts(ss[1:], return_ty, env)
  14145. case _:
  14146. self.type_check_stmts(ss, env)
  14147. def type_check(self, p):
  14148. match p:
  14149. case Module(body):
  14150. env = {}
  14151. for s in body:
  14152. match s:
  14153. case FunctionDef(name, params, bod, dl, returns, comment):
  14154. params_t = [t for (x,t) in params]
  14155. env[name] = FunctionType(params_t, returns)
  14156. self.check_stmts(body, int, env)
  14157. \end{lstlisting}
  14158. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14159. \label{fig:type-check-Llambda-part2}
  14160. \end{figure}
  14161. \fi}
  14162. \clearpage
  14163. \section{Assignment and Lexically Scoped Functions}
  14164. \label{sec:assignment-scoping}
  14165. The combination of lexically-scoped functions and assignment to
  14166. variables raises a challenge with the flat-closure approach to
  14167. implementing lexically-scoped functions. Consider the following
  14168. example in which function \code{f} has a free variable \code{x} that
  14169. is changed after \code{f} is created but before the call to \code{f}.
  14170. % loop_test_11.rkt
  14171. {\if\edition\racketEd
  14172. \begin{lstlisting}
  14173. (let ([x 0])
  14174. (let ([y 0])
  14175. (let ([z 20])
  14176. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14177. (begin
  14178. (set! x 10)
  14179. (set! y 12)
  14180. (f y))))))
  14181. \end{lstlisting}
  14182. \fi}
  14183. {\if\edition\pythonEd
  14184. % box_free_assign.py
  14185. \begin{lstlisting}
  14186. def g(z : int) -> int:
  14187. x = 0
  14188. y = 0
  14189. f : Callable[[int],int] = lambda a: a + x + z
  14190. x = 10
  14191. y = 12
  14192. return f(y)
  14193. print( g(20) )
  14194. \end{lstlisting}
  14195. \fi} The correct output for this example is \code{42} because the call
  14196. to \code{f} is required to use the current value of \code{x} (which is
  14197. \code{10}). Unfortunately, the closure conversion pass
  14198. (Section~\ref{sec:closure-conversion}) generates code for the
  14199. \code{lambda} that copies the old value of \code{x} into a
  14200. closure. Thus, if we naively apply closure conversion, the output of
  14201. this program would be \code{32}.
  14202. A first attempt at solving this problem would be to save a pointer to
  14203. \code{x} in the closure and change the occurrences of \code{x} inside
  14204. the lambda to dereference the pointer. Of course, this would require
  14205. assigning \code{x} to the stack and not to a register. However, the
  14206. problem goes a bit deeper.
  14207. Consider the following example that returns a function that refers to
  14208. a local variable of the enclosing function.
  14209. \begin{center}
  14210. \begin{minipage}{\textwidth}
  14211. {\if\edition\racketEd
  14212. \begin{lstlisting}
  14213. (define (f []) : Integer
  14214. (let ([x 0])
  14215. (let ([g (lambda: () : Integer x)])
  14216. (begin
  14217. (set! x 42)
  14218. g))))
  14219. ((f))
  14220. \end{lstlisting}
  14221. \fi}
  14222. {\if\edition\pythonEd
  14223. % counter.py
  14224. \begin{lstlisting}
  14225. def f():
  14226. x = 0
  14227. g = lambda: x
  14228. x = 42
  14229. return g
  14230. print( f()() )
  14231. \end{lstlisting}
  14232. \fi}
  14233. \end{minipage}
  14234. \end{center}
  14235. In this example, the lifetime of \code{x} extends beyond the lifetime
  14236. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14237. stack frame for the call to \code{f}, it would be gone by the time we
  14238. call \code{g}, leaving us with dangling pointers for
  14239. \code{x}. This example demonstrates that when a variable occurs free
  14240. inside a function, its lifetime becomes indefinite. Thus, the value of
  14241. the variable needs to live on the heap. The verb
  14242. \emph{box}\index{subject}{box} is often used for allocating a single
  14243. value on the heap, producing a pointer, and
  14244. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14245. %
  14246. We introduce a new pass named \code{convert\_assignments} to address
  14247. this challenge.
  14248. %
  14249. \python{But before diving into that, we have one more
  14250. problem to discuss.}
  14251. \if\edition\pythonEd
  14252. \section{Uniquify Variables}
  14253. \label{sec:uniquify-lambda}
  14254. With the addition of \code{lambda} we have a complication to deal
  14255. with: name shadowing. Consider the following program with a function
  14256. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14257. \code{lambda} expressions. The first \code{lambda} has a parameter
  14258. that is also named \code{x}.
  14259. \begin{lstlisting}
  14260. def f(x:int, y:int) -> Callable[[int], int]:
  14261. g : Callable[[int],int] = (lambda x: x + y)
  14262. h : Callable[[int],int] = (lambda y: x + y)
  14263. x = input_int()
  14264. return g
  14265. print(f(0, 10)(32))
  14266. \end{lstlisting}
  14267. Many of our compiler passes rely on being able to connect variable
  14268. uses with their definitions using just the name of the variable,
  14269. including new passes in this chapter. However, in the above example
  14270. the name of the variable does not uniquely determine its
  14271. definition. To solve this problem we recommend implementing a pass
  14272. named \code{uniquify} that renames every variable in the program to
  14273. make sure they are all unique.
  14274. The following shows the result of \code{uniquify} for the above
  14275. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14276. and the \code{x} parameter of the \code{lambda} is renamed to
  14277. \code{x\_4}.
  14278. \begin{lstlisting}
  14279. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14280. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14281. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14282. x_0 = input_int()
  14283. return g_2
  14284. def main() -> int :
  14285. print(f(0, 10)(32))
  14286. return 0
  14287. \end{lstlisting}
  14288. \fi
  14289. %% \section{Reveal Functions}
  14290. %% \label{sec:reveal-functions-r5}
  14291. %% \racket{To support the \code{procedure-arity} operator we need to
  14292. %% communicate the arity of a function to the point of closure
  14293. %% creation.}
  14294. %% %
  14295. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14296. %% function at runtime. Thus, we need to communicate the arity of a
  14297. %% function to the point of closure creation.}
  14298. %% %
  14299. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14300. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14301. %% \[
  14302. %% \begin{array}{lcl}
  14303. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14304. %% \end{array}
  14305. %% \]
  14306. \section{Assignment Conversion}
  14307. \label{sec:convert-assignments}
  14308. The purpose of the \code{convert\_assignments} pass is to address the
  14309. challenge regarding the interaction between variable assignments and
  14310. closure conversion. First we identify which variables need to be
  14311. boxed, then we transform the program to box those variables. In
  14312. general, boxing introduces runtime overhead that we would like to
  14313. avoid, so we should box as few variables as possible. We recommend
  14314. boxing the variables in the intersection of the following two sets of
  14315. variables:
  14316. \begin{enumerate}
  14317. \item The variables that are free in a \code{lambda}.
  14318. \item The variables that appear on the left-hand side of an
  14319. assignment.
  14320. \end{enumerate}
  14321. The first condition is a must but the second condition is
  14322. conservative. It is possible to develop a more liberal condition using
  14323. static program analysis.
  14324. Consider again the first example from
  14325. Section~\ref{sec:assignment-scoping}:
  14326. %
  14327. {\if\edition\racketEd
  14328. \begin{lstlisting}
  14329. (let ([x 0])
  14330. (let ([y 0])
  14331. (let ([z 20])
  14332. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14333. (begin
  14334. (set! x 10)
  14335. (set! y 12)
  14336. (f y))))))
  14337. \end{lstlisting}
  14338. \fi}
  14339. {\if\edition\pythonEd
  14340. \begin{lstlisting}
  14341. def g(z : int) -> int:
  14342. x = 0
  14343. y = 0
  14344. f : Callable[[int],int] = lambda a: a + x + z
  14345. x = 10
  14346. y = 12
  14347. return f(y)
  14348. print( g(20) )
  14349. \end{lstlisting}
  14350. \fi}
  14351. %
  14352. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14353. variables \code{x} and \code{z} occur free inside the
  14354. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14355. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14356. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14357. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14358. with a tuple write. The output of \code{convert\_assignments} for
  14359. this example is as follows.
  14360. %
  14361. {\if\edition\racketEd
  14362. \begin{lstlisting}
  14363. (define (main) : Integer
  14364. (let ([x0 (vector 0)])
  14365. (let ([y1 0])
  14366. (let ([z2 20])
  14367. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14368. (+ a3 (+ (vector-ref x0 0) z2)))])
  14369. (begin
  14370. (vector-set! x0 0 10)
  14371. (set! y1 12)
  14372. (f4 y1)))))))
  14373. \end{lstlisting}
  14374. \fi}
  14375. %
  14376. {\if\edition\pythonEd
  14377. \begin{lstlisting}
  14378. def g(z : int)-> int:
  14379. x = (uninitialized(int),)
  14380. x[0] = 0
  14381. y = 0
  14382. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14383. x[0] = 10
  14384. y = 12
  14385. return f(y)
  14386. def main() -> int:
  14387. print(g(20))
  14388. return 0
  14389. \end{lstlisting}
  14390. \fi}
  14391. To compute the free variables of all the \code{lambda} expressions, we
  14392. recommend defining two auxiliary functions:
  14393. \begin{enumerate}
  14394. \item \code{free\_variables} computes the free variables of an expression, and
  14395. \item \code{free\_in\_lambda} collects all of the variables that are
  14396. free in any of the \code{lambda} expressions, using
  14397. \code{free\_variables} in the case for each \code{lambda}.
  14398. \end{enumerate}
  14399. {\if\edition\racketEd
  14400. %
  14401. To compute the variables that are assigned-to, we recommend using the
  14402. \code{collect-set!} function that we introduced in
  14403. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14404. forms such as \code{Lambda}.
  14405. %
  14406. \fi}
  14407. {\if\edition\pythonEd
  14408. %
  14409. To compute the variables that are assigned-to, we recommend defining
  14410. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14411. the set of variables that occur in the left-hand side of an assignment
  14412. statement, and otherwise returns the empty set.
  14413. %
  14414. \fi}
  14415. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14416. free in a \code{lambda} and that are assigned-to in the enclosing
  14417. function definition.
  14418. Next we discuss the \code{convert\_assignments} pass. In the case for
  14419. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14420. $\VAR{x}$ to a tuple read.
  14421. %
  14422. {\if\edition\racketEd
  14423. \begin{lstlisting}
  14424. (Var |$x$|)
  14425. |$\Rightarrow$|
  14426. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14427. \end{lstlisting}
  14428. \fi}
  14429. %
  14430. {\if\edition\pythonEd
  14431. \begin{lstlisting}
  14432. Name(|$x$|)
  14433. |$\Rightarrow$|
  14434. Subscript(Name(|$x$|), Constant(0), Load())
  14435. \end{lstlisting}
  14436. \fi}
  14437. %
  14438. \noindent In the case for assignment, recursively process the
  14439. right-hand side \itm{rhs} to obtain \itm{rhs'}. If the left-hand side
  14440. $x$ is in $\mathit{AF}$, translate the assignment into a tuple-write
  14441. as follows.
  14442. %
  14443. {\if\edition\racketEd
  14444. \begin{lstlisting}
  14445. (SetBang |$x$| |$\itm{rhs}$|)
  14446. |$\Rightarrow$|
  14447. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14448. \end{lstlisting}
  14449. \fi}
  14450. {\if\edition\pythonEd
  14451. \begin{lstlisting}
  14452. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14453. |$\Rightarrow$|
  14454. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14455. \end{lstlisting}
  14456. \fi}
  14457. %
  14458. {\if\edition\racketEd
  14459. The case for \code{Lambda} is non-trivial, but it is similar to the
  14460. case for function definitions, which we discuss next.
  14461. \fi}
  14462. %
  14463. To translate a function definition, we first compute $\mathit{AF}$,
  14464. the intersection of the variables that are free in a \code{lambda} and
  14465. that are assigned-to. We then apply assignment conversion to the body
  14466. of the function definition. Finally, we box the parameters of this
  14467. function definition that are in $\mathit{AF}$. For example,
  14468. the parameter \code{x} of the following function \code{g}
  14469. needs to be boxed.
  14470. {\if\edition\racketEd
  14471. \begin{lstlisting}
  14472. (define (g [x : Integer]) : Integer
  14473. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14474. (begin
  14475. (set! x 10)
  14476. (f 32))))
  14477. \end{lstlisting}
  14478. \fi}
  14479. %
  14480. {\if\edition\pythonEd
  14481. \begin{lstlisting}
  14482. def g(x : int) -> int:
  14483. f : Callable[[int],int] = lambda a: a + x
  14484. x = 10
  14485. return f(32)
  14486. \end{lstlisting}
  14487. \fi}
  14488. %
  14489. \noindent We box parameter \code{x} by creating a local variable named
  14490. \code{x} that is initialized to a tuple whose contents is the value of
  14491. the parameter, which has been renamed to \code{x\_0}.
  14492. %
  14493. {\if\edition\racketEd
  14494. \begin{lstlisting}
  14495. (define (g [x_0 : Integer]) : Integer
  14496. (let ([x (vector x_0)])
  14497. (let ([f (lambda: ([a : Integer]) : Integer
  14498. (+ a (vector-ref x 0)))])
  14499. (begin
  14500. (vector-set! x 0 10)
  14501. (f 32)))))
  14502. \end{lstlisting}
  14503. \fi}
  14504. %
  14505. {\if\edition\pythonEd
  14506. \begin{lstlisting}
  14507. def g(x_0 : int)-> int:
  14508. x = (x_0,)
  14509. f : Callable[[int], int] = (lambda a: a + x[0])
  14510. x[0] = 10
  14511. return f(32)
  14512. \end{lstlisting}
  14513. \fi}
  14514. \section{Closure Conversion}
  14515. \label{sec:closure-conversion}
  14516. \index{subject}{closure conversion}
  14517. The compiling of lexically-scoped functions into top-level function
  14518. definitions and flat closures is accomplished in the pass
  14519. \code{convert\_to\_closures} that comes after \code{reveal\_functions}
  14520. and before \code{limit\_functions}.
  14521. As usual, we implement the pass as a recursive function over the
  14522. AST. The interesting cases are the ones for \key{lambda} and function
  14523. application. We transform a \key{lambda} expression into an expression
  14524. that creates a closure, that is, a tuple whose first element is a
  14525. function pointer and the rest of the elements are the values of the
  14526. free variables of the \key{lambda}.
  14527. %
  14528. However, we use the \code{Closure} AST node instead of using a tuple
  14529. so that we can record the arity.
  14530. %
  14531. In the generated code below, \itm{fvs} is the free variables of the
  14532. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14533. %
  14534. \racket{The \itm{arity} is the number of parameters (the length of
  14535. \itm{ps}).}
  14536. %
  14537. {\if\edition\racketEd
  14538. \begin{lstlisting}
  14539. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14540. |$\Rightarrow$|
  14541. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14542. \end{lstlisting}
  14543. \fi}
  14544. %
  14545. {\if\edition\pythonEd
  14546. \begin{lstlisting}
  14547. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14548. |$\Rightarrow$|
  14549. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14550. \end{lstlisting}
  14551. \fi}
  14552. %
  14553. In addition to transforming each \key{Lambda} AST node into a
  14554. tuple, we create a top-level function definition for each
  14555. \key{Lambda}, as shown below.\\
  14556. \begin{minipage}{0.8\textwidth}
  14557. {\if\edition\racketEd
  14558. \begin{lstlisting}
  14559. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14560. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14561. ...
  14562. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14563. |\itm{body'}|)...))
  14564. \end{lstlisting}
  14565. \fi}
  14566. {\if\edition\pythonEd
  14567. \begin{lstlisting}
  14568. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14569. |$\itm{fvs}_1$| = clos[1]
  14570. |$\ldots$|
  14571. |$\itm{fvs}_n$| = clos[|$n$|]
  14572. |\itm{body'}|
  14573. \end{lstlisting}
  14574. \fi}
  14575. \end{minipage}\\
  14576. The \code{clos} parameter refers to the closure. Translate the type
  14577. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14578. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14579. \itm{closTy} is a tuple type whose first element type is
  14580. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14581. the element types are the types of the free variables in the
  14582. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14583. is non-trivial to give a type to the function in the closure's type.%
  14584. %
  14585. \footnote{To give an accurate type to a closure, we would need to add
  14586. existential types to the type checker~\citep{Minamide:1996ys}.}
  14587. %
  14588. %% The dummy type is considered to be equal to any other type during type
  14589. %% checking.
  14590. The free variables become local variables that are initialized with
  14591. their values in the closure.
  14592. Closure conversion turns every function into a tuple, so the type
  14593. annotations in the program must also be translated. We recommend
  14594. defining an auxiliary recursive function for this purpose. Function
  14595. types should be translated as follows.
  14596. %
  14597. {\if\edition\racketEd
  14598. \begin{lstlisting}
  14599. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14600. |$\Rightarrow$|
  14601. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14602. \end{lstlisting}
  14603. \fi}
  14604. {\if\edition\pythonEd
  14605. \begin{lstlisting}
  14606. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14607. |$\Rightarrow$|
  14608. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14609. \end{lstlisting}
  14610. \fi}
  14611. %
  14612. The above type says that the first thing in the tuple is a
  14613. function. The first parameter of the function is a tuple (a closure)
  14614. and the rest of the parameters are the ones from the original
  14615. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14616. omits the types of the free variables because 1) those types are not
  14617. available in this context and 2) we do not need them in the code that
  14618. is generated for function application. So this type only describes the
  14619. first component of the closure tuple. At runtime the tuple may have
  14620. more components, but we ignore them at this point.
  14621. We transform function application into code that retrieves the
  14622. function from the closure and then calls the function, passing the
  14623. closure as the first argument. We place $e'$ in a temporary variable
  14624. to avoid code duplication.
  14625. \begin{center}
  14626. \begin{minipage}{\textwidth}
  14627. {\if\edition\racketEd
  14628. \begin{lstlisting}
  14629. (Apply |$e$| |$\itm{es}$|)
  14630. |$\Rightarrow$|
  14631. (Let |$\itm{tmp}$| |$e'$|
  14632. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons (Var |$\itm{tmp}$|) |$\itm{es'}$|)))
  14633. \end{lstlisting}
  14634. \fi}
  14635. %
  14636. {\if\edition\pythonEd
  14637. \begin{lstlisting}
  14638. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14639. |$\Rightarrow$|
  14640. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14641. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14642. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14643. \end{lstlisting}
  14644. \fi}
  14645. \end{minipage}
  14646. \end{center}
  14647. There is also the question of what to do with references to top-level
  14648. function definitions. To maintain a uniform translation of function
  14649. application, we turn function references into closures.
  14650. \begin{tabular}{lll}
  14651. \begin{minipage}{0.3\textwidth}
  14652. {\if\edition\racketEd
  14653. \begin{lstlisting}
  14654. (FunRef |$f$| |$n$|)
  14655. \end{lstlisting}
  14656. \fi}
  14657. {\if\edition\pythonEd
  14658. \begin{lstlisting}
  14659. FunRef(|$f$|, |$n$|)
  14660. \end{lstlisting}
  14661. \fi}
  14662. \end{minipage}
  14663. &
  14664. $\Rightarrow$
  14665. &
  14666. \begin{minipage}{0.5\textwidth}
  14667. {\if\edition\racketEd
  14668. \begin{lstlisting}
  14669. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14670. \end{lstlisting}
  14671. \fi}
  14672. {\if\edition\pythonEd
  14673. \begin{lstlisting}
  14674. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14675. \end{lstlisting}
  14676. \fi}
  14677. \end{minipage}
  14678. \end{tabular} \\
  14679. We no longer need the annotated assignment statement \code{AnnAssign}
  14680. to support the type checking of \code{lambda} expressions, so we
  14681. translate it to a regular \code{Assign} statement.
  14682. The top-level function definitions need to be updated to take an extra
  14683. closure parameter but that parameter is ignored in the body of those
  14684. functions.
  14685. \section{An Example Translation}
  14686. \label{sec:example-lambda}
  14687. Figure~\ref{fig:lexical-functions-example} shows the result of
  14688. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14689. program demonstrating lexical scoping that we discussed at the
  14690. beginning of this chapter.
  14691. \begin{figure}[tbp]
  14692. \begin{minipage}{0.8\textwidth}
  14693. {\if\edition\racketEd
  14694. % tests/lambda_test_6.rkt
  14695. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14696. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14697. (let ([y8 4])
  14698. (lambda: ([z9 : Integer]) : Integer
  14699. (+ x7 (+ y8 z9)))))
  14700. (define (main) : Integer
  14701. (let ([g0 ((fun-ref f6 1) 5)])
  14702. (let ([h1 ((fun-ref f6 1) 3)])
  14703. (+ (g0 11) (h1 15)))))
  14704. \end{lstlisting}
  14705. $\Rightarrow$
  14706. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14707. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14708. (let ([y8 4])
  14709. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  14710. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14711. (let ([x7 (vector-ref fvs3 1)])
  14712. (let ([y8 (vector-ref fvs3 2)])
  14713. (+ x7 (+ y8 z9)))))
  14714. (define (main) : Integer
  14715. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  14716. ((vector-ref clos5 0) clos5 5))])
  14717. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  14718. ((vector-ref clos6 0) clos6 3))])
  14719. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14720. \end{lstlisting}
  14721. \fi}
  14722. %
  14723. {\if\edition\pythonEd
  14724. % free_var.py
  14725. \begin{lstlisting}
  14726. def f(x : int) -> Callable[[int], int]:
  14727. y = 4
  14728. return lambda z: x + y + z
  14729. g = f(5)
  14730. h = f(3)
  14731. print( g(11) + h(15) )
  14732. \end{lstlisting}
  14733. $\Rightarrow$
  14734. \begin{lstlisting}
  14735. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14736. x = fvs_1[1]
  14737. y = fvs_1[2]
  14738. return x + y[0] + z
  14739. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14740. y = (777,)
  14741. y[0] = 4
  14742. return (lambda_0, x, y)
  14743. def main() -> int:
  14744. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14745. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14746. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14747. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14748. return 0
  14749. \end{lstlisting}
  14750. \fi}
  14751. \end{minipage}
  14752. \caption{Example of closure conversion.}
  14753. \label{fig:lexical-functions-example}
  14754. \end{figure}
  14755. \begin{exercise}\normalfont\normalsize
  14756. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14757. Create 5 new programs that use \key{lambda} functions and make use of
  14758. lexical scoping. Test your compiler on these new programs and all of
  14759. your previously created test programs.
  14760. \end{exercise}
  14761. \section{Expose Allocation}
  14762. \label{sec:expose-allocation-r5}
  14763. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  14764. that allocates and initializes a tuple, similar to the translation of
  14765. the tuple creation in Section~\ref{sec:expose-allocation}.
  14766. The only difference is replacing the use of
  14767. \ALLOC{\itm{len}}{\itm{type}} with
  14768. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14769. \section{Explicate Control and \LangCLam{}}
  14770. \label{sec:explicate-r5}
  14771. The output language of \code{explicate\_control} is \LangCLam{} whose
  14772. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  14773. %
  14774. \racket{The only differences with respect to \LangCFun{} is the
  14775. addition of the \code{AllocateClosure} form to the grammar for
  14776. $\Exp$ and the \code{procedure-arity} operator. The handling of
  14777. \code{AllocateClosure} in the \code{explicate\_control} pass is
  14778. similar to the handling of other expressions such as primitive
  14779. operators.}
  14780. %
  14781. \python{The differences with respect to \LangCFun{} are the
  14782. additions of \code{Uninitialized}, \code{AllocateClosure},
  14783. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  14784. \code{explicate\_control} pass is similar to the handling of other
  14785. expressions such as primitive operators.}
  14786. \newcommand{\ClambdaASTRacket}{
  14787. \begin{array}{lcl}
  14788. \Exp &::= & \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14789. \itm{op} &::= & \code{procedure-arity}
  14790. \end{array}
  14791. }
  14792. \newcommand{\ClambdaASTPython}{
  14793. \begin{array}{lcl}
  14794. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  14795. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  14796. &\MID& \ARITY{\Atm}
  14797. \end{array}
  14798. }
  14799. \begin{figure}[tp]
  14800. \fbox{
  14801. \begin{minipage}{0.96\textwidth}
  14802. \small
  14803. {\if\edition\racketEd
  14804. \[
  14805. \begin{array}{l}
  14806. \gray{\CvarASTRacket} \\ \hline
  14807. \gray{\CifASTRacket} \\ \hline
  14808. \gray{\CloopASTRacket} \\ \hline
  14809. \gray{\CtupASTRacket} \\ \hline
  14810. \gray{\CfunASTRacket} \\ \hline
  14811. \ClambdaASTRacket \\
  14812. \begin{array}{lcl}
  14813. \LangCLamM{} & ::= & \PROGRAMDEFS{\itm{info}}{\Def^{*}}
  14814. \end{array}
  14815. \end{array}
  14816. \]
  14817. \fi}
  14818. {\if\edition\pythonEd
  14819. \[
  14820. \begin{array}{l}
  14821. \gray{\CifASTPython} \\ \hline
  14822. \gray{\CtupASTPython} \\ \hline
  14823. \gray{\CfunASTPython} \\ \hline
  14824. \ClambdaASTPython \\
  14825. \begin{array}{lcl}
  14826. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14827. \end{array}
  14828. \end{array}
  14829. \]
  14830. \fi}
  14831. \end{minipage}
  14832. }
  14833. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14834. \label{fig:Clam-syntax}
  14835. \end{figure}
  14836. \section{Select Instructions}
  14837. \label{sec:select-instructions-Llambda}
  14838. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14839. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14840. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14841. that you should place the \itm{arity} in the tag that is stored at
  14842. position $0$ of the vector. Recall that in
  14843. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14844. was not used. We store the arity in the $5$ bits starting at position
  14845. $58$.
  14846. \racket{Compile the \code{procedure-arity} operator into a sequence of
  14847. instructions that access the tag from position $0$ of the vector and
  14848. extract the $5$-bits starting at position $58$ from the tag.}
  14849. %
  14850. \python{Compile a call to the \code{arity} operator to a sequence of
  14851. instructions that access the tag from position $0$ of the tuple
  14852. (representing a closure) and extract the $5$-bits starting at position
  14853. $58$ from the tag.}
  14854. \begin{figure}[p]
  14855. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14856. \node (Lfun) at (0,2) {\large \LangLam{}};
  14857. \node (Lfun-2) at (3,2) {\large \LangLam{}};
  14858. \node (Lfun-3) at (6,2) {\large \LangLam{}};
  14859. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14860. \node (F1-1) at (12,2) {\large \LangLamFunRef{}};
  14861. \node (F1-2) at (12,0) {\large \LangFunRef{}};
  14862. \node (F1-3) at (9,0) {\large \LangFunRef{}};
  14863. \node (F1-4) at (6,0) {\large \LangFunRefAlloc{}};
  14864. \node (F1-5) at (3,0) {\large \LangFunRefAlloc{}};
  14865. \node (F1-6) at (0,0) {\large \LangFunANF{}};
  14866. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14867. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14868. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14869. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14870. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14871. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14872. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14873. \path[->,bend left=15] (Lfun) edge [above] node
  14874. {\ttfamily\footnotesize shrink} (Lfun-2);
  14875. \path[->,bend left=15] (Lfun-2) edge [above] node
  14876. {\ttfamily\footnotesize uniquify} (Lfun-3);
  14877. \path[->,bend left=15] (Lfun-3) edge [above] node
  14878. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14879. \path[->,bend left=15] (F1-0) edge [above] node
  14880. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  14881. \path[->,bend left=15] (F1-1) edge [left] node
  14882. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14883. \path[->,bend left=15] (F1-2) edge [below] node
  14884. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14885. \path[->,bend right=15] (F1-3) edge [above] node
  14886. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14887. \path[->,bend left=15] (F1-4) edge [below] node
  14888. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  14889. \path[->,bend right=15] (F1-5) edge [above] node
  14890. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  14891. \path[->,bend right=15] (F1-6) edge [right] node
  14892. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14893. \path[->,bend left=15] (C3-2) edge [left] node
  14894. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14895. \path[->,bend right=15] (x86-2) edge [left] node
  14896. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14897. \path[->,bend right=15] (x86-2-1) edge [below] node
  14898. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14899. \path[->,bend right=15] (x86-2-2) edge [left] node
  14900. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14901. \path[->,bend left=15] (x86-3) edge [above] node
  14902. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14903. \path[->,bend left=15] (x86-4) edge [right] node
  14904. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  14905. \end{tikzpicture}
  14906. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14907. functions.}
  14908. \label{fig:Llambda-passes}
  14909. \end{figure}
  14910. Figure~\ref{fig:Llambda-passes} provides an overview of the passes
  14911. needed for the compilation of \LangLam{}.
  14912. \clearpage
  14913. \section{Challenge: Optimize Closures}
  14914. \label{sec:optimize-closures}
  14915. In this chapter we compiled lexically-scoped functions into a
  14916. relatively efficient representation: flat closures. However, even this
  14917. representation comes with some overhead. For example, consider the
  14918. following program with a function \code{tail\_sum} that does not have
  14919. any free variables and where all the uses of \code{tail\_sum} are in
  14920. applications where we know that only \code{tail\_sum} is being applied
  14921. (and not any other functions).
  14922. \begin{center}
  14923. \begin{minipage}{0.95\textwidth}
  14924. {\if\edition\racketEd
  14925. \begin{lstlisting}
  14926. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14927. (if (eq? n 0)
  14928. s
  14929. (tail_sum (- n 1) (+ n s))))
  14930. (+ (tail_sum 3 0) 36)
  14931. \end{lstlisting}
  14932. \fi}
  14933. {\if\edition\pythonEd
  14934. \begin{lstlisting}
  14935. def tail_sum(n : int, s : int) -> int:
  14936. if n == 0:
  14937. return s
  14938. else:
  14939. return tail_sum(n - 1, n + s)
  14940. print( tail_sum(3, 0) + 36)
  14941. \end{lstlisting}
  14942. \fi}
  14943. \end{minipage}
  14944. \end{center}
  14945. As described in this chapter, we uniformly apply closure conversion to
  14946. all functions, obtaining the following output for this program.
  14947. \begin{center}
  14948. \begin{minipage}{0.95\textwidth}
  14949. {\if\edition\racketEd
  14950. \begin{lstlisting}
  14951. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14952. (if (eq? n2 0)
  14953. s3
  14954. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  14955. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14956. (define (main) : Integer
  14957. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  14958. ((vector-ref clos6 0) clos6 3 0)) 27))
  14959. \end{lstlisting}
  14960. \fi}
  14961. {\if\edition\pythonEd
  14962. \begin{lstlisting}
  14963. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14964. if n_0 == 0:
  14965. return s_1
  14966. else:
  14967. return (let clos_2 = (tail_sum,)
  14968. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14969. def main() -> int :
  14970. print((let clos_4 = (tail_sum,)
  14971. in clos_4[0](clos_4, 3, 0)) + 36)
  14972. return 0
  14973. \end{lstlisting}
  14974. \fi}
  14975. \end{minipage}
  14976. \end{center}
  14977. In the previous chapter, there would be no allocation in the program
  14978. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14979. the above program allocates memory for each closure and the calls to
  14980. \code{tail\_sum} are indirect. These two differences incur
  14981. considerable overhead in a program such as this one, where the
  14982. allocations and indirect calls occur inside a tight loop.
  14983. One might think that this problem is trivial to solve: can't we just
  14984. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  14985. and compile them to direct calls instead of treating it like a call to
  14986. a closure? We would also drop the new \code{fvs} parameter of
  14987. \code{tail\_sum}.
  14988. %
  14989. However, this problem is not so trivial because a global function may
  14990. ``escape'' and become involved in applications that also involve
  14991. closures. Consider the following example in which the application
  14992. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14993. application, because the \code{lambda} may flow into \code{f}, but the
  14994. \code{inc} function might also flow into \code{f}.
  14995. \begin{center}
  14996. \begin{minipage}{\textwidth}
  14997. % lambda_test_30.rkt
  14998. {\if\edition\racketEd
  14999. \begin{lstlisting}
  15000. (define (inc [x : Integer]) : Integer
  15001. (+ x 1))
  15002. (let ([y (read)])
  15003. (let ([f (if (eq? (read) 0)
  15004. inc
  15005. (lambda: ([x : Integer]) : Integer (- x y)))])
  15006. (f 41)))
  15007. \end{lstlisting}
  15008. \fi}
  15009. {\if\edition\pythonEd
  15010. \begin{lstlisting}
  15011. def add1(x : int) -> int:
  15012. return x + 1
  15013. y = input_int()
  15014. g : Callable[[int], int] = lambda x: x - y
  15015. f = add1 if input_int() == 0 else g
  15016. print( f(41) )
  15017. \end{lstlisting}
  15018. \fi}
  15019. \end{minipage}
  15020. \end{center}
  15021. If a global function name is used in any way other than as the
  15022. operator in a direct call, then we say that the function
  15023. \emph{escapes}. If a global function does not escape, then we do not
  15024. need to perform closure conversion on the function.
  15025. \begin{exercise}\normalfont\normalsize
  15026. Implement an auxiliary function for detecting which global
  15027. functions escape. Using that function, implement an improved version
  15028. of closure conversion that does not apply closure conversion to
  15029. global functions that do not escape but instead compiles them as
  15030. regular functions. Create several new test cases that check whether
  15031. you properly detect whether global functions escape or not.
  15032. \end{exercise}
  15033. So far we have reduced the overhead of calling global functions, but
  15034. it would also be nice to reduce the overhead of calling a
  15035. \code{lambda} when we can determine at compile time which
  15036. \code{lambda} will be called. We refer to such calls as \emph{known
  15037. calls}. Consider the following example in which a \code{lambda} is
  15038. bound to \code{f} and then applied.
  15039. {\if\edition\racketEd
  15040. % lambda_test_9.rkt
  15041. \begin{lstlisting}
  15042. (let ([y (read)])
  15043. (let ([f (lambda: ([x : Integer]) : Integer
  15044. (+ x y))])
  15045. (f 21)))
  15046. \end{lstlisting}
  15047. \fi}
  15048. {\if\edition\pythonEd
  15049. \begin{lstlisting}
  15050. y = input_int()
  15051. f : Callable[[int],int] = lambda x: x + y
  15052. print( f(21) )
  15053. \end{lstlisting}
  15054. \fi}
  15055. %
  15056. \noindent Closure conversion compiles the application
  15057. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  15058. %
  15059. {\if\edition\racketEd
  15060. \begin{lstlisting}
  15061. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15062. (let ([y2 (vector-ref fvs6 1)])
  15063. (+ x3 y2)))
  15064. (define (main) : Integer
  15065. (let ([y2 (read)])
  15066. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15067. ((vector-ref f4 0) f4 21))))
  15068. \end{lstlisting}
  15069. \fi}
  15070. {\if\edition\pythonEd
  15071. \begin{lstlisting}
  15072. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15073. y_1 = fvs_4[1]
  15074. return x_2 + y_1[0]
  15075. def main() -> int:
  15076. y_1 = (777,)
  15077. y_1[0] = input_int()
  15078. f_0 = (lambda_3, y_1)
  15079. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15080. return 0
  15081. \end{lstlisting}
  15082. \fi}
  15083. %
  15084. \noindent but we can instead compile the application
  15085. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15086. %
  15087. {\if\edition\racketEd
  15088. \begin{lstlisting}
  15089. (define (main) : Integer
  15090. (let ([y2 (read)])
  15091. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15092. ((fun-ref lambda5 1) f4 21))))
  15093. \end{lstlisting}
  15094. \fi}
  15095. {\if\edition\pythonEd
  15096. \begin{lstlisting}
  15097. def main() -> int:
  15098. y_1 = (777,)
  15099. y_1[0] = input_int()
  15100. f_0 = (lambda_3, y_1)
  15101. print(lambda_3(f_0, 21))
  15102. return 0
  15103. \end{lstlisting}
  15104. \fi}
  15105. The problem of determining which \code{lambda} will be called from a
  15106. particular application is quite challenging in general and the topic
  15107. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15108. following exercise we recommend that you compile an application to a
  15109. direct call when the operator is a variable and \racket{the variable
  15110. is \code{let}-bound to a closure}\python{the previous assignment to
  15111. the variable is a closure}. This can be accomplished by maintaining
  15112. an environment mapping variables to function names. Extend the
  15113. environment whenever you encounter a closure on the right-hand side of
  15114. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15115. name of the global function for the closure. This pass should come
  15116. after closure conversion.
  15117. \begin{exercise}\normalfont\normalsize
  15118. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15119. compiles known calls into direct calls. Verify that your compiler is
  15120. successful in this regard on several example programs.
  15121. \end{exercise}
  15122. These exercises only scratches the surface of optimizing of
  15123. closures. A good next step for the interested reader is to look at the
  15124. work of \citet{Keep:2012ab}.
  15125. \section{Further Reading}
  15126. The notion of lexically scoped functions predates modern computers by
  15127. about a decade. They were invented by \citet{Church:1932aa}, who
  15128. proposed the lambda calculus as a foundation for logic. Anonymous
  15129. functions were included in the LISP~\citep{McCarthy:1960dz}
  15130. programming language but were initially dynamically scoped. The Scheme
  15131. dialect of LISP adopted lexical scoping and
  15132. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15133. Scheme programs. However, environments were represented as linked
  15134. lists, so variable look-up was linear in the size of the
  15135. environment. \citet{Appel91} gives a detailed description of several
  15136. closure representations. In this chapter we represent environments
  15137. using flat closures, which were invented by
  15138. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15139. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15140. closures, variable look-up is constant time but the time to create a
  15141. closure is proportional to the number of its free variables. Flat
  15142. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15143. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15144. % todo: related work on assignment conversion (e.g. orbit and rabbit
  15145. % compilers)
  15146. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15147. \chapter{Dynamic Typing}
  15148. \label{ch:Ldyn}
  15149. \index{subject}{dynamic typing}
  15150. In this chapter we learn how to compile \LangDyn{}, a dynamically
  15151. typed language that is a subset of \racket{Racket}\python{Python}. The
  15152. focus on dynamic typing is in contrast to the previous chapters, which
  15153. have studied the compilation of statically typed languages. In
  15154. dynamically typed languages such as \LangDyn{}, a particular
  15155. expression may produce a value of a different type each time it is
  15156. executed. Consider the following example with a conditional \code{if}
  15157. expression that may return a Boolean or an integer depending on the
  15158. input to the program.
  15159. % part of dynamic_test_25.rkt
  15160. {\if\edition\racketEd
  15161. \begin{lstlisting}
  15162. (not (if (eq? (read) 1) #f 0))
  15163. \end{lstlisting}
  15164. \fi}
  15165. {\if\edition\pythonEd
  15166. \begin{lstlisting}
  15167. not (False if input_int() == 1 else 0)
  15168. \end{lstlisting}
  15169. \fi}
  15170. Languages that allow expressions to produce different kinds of values
  15171. are called \emph{polymorphic}, a word composed of the Greek roots
  15172. ``poly'', meaning ``many'', and ``morph'', meaning ``form''. There
  15173. are several kinds of polymorphism in programming languages, such as
  15174. subtype polymorphism and parametric
  15175. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15176. study in this chapter does not have a special name but it is the kind
  15177. that arises in dynamically typed languages.
  15178. Another characteristic of dynamically typed languages is that
  15179. primitive operations, such as \code{not}, are often defined to operate
  15180. on many different types of values. In fact, in
  15181. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15182. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15183. given anything else it returns \FALSE{}.
  15184. Furthermore, even when primitive operations restrict their inputs to
  15185. values of a certain type, this restriction is enforced at runtime
  15186. instead of during compilation. For example, the tuple read
  15187. operation
  15188. \racket{\code{(vector-ref \#t 0)}}
  15189. \python{\code{True[0]}}
  15190. results in a run-time error because the first argument must
  15191. be a tuple, not a Boolean.
  15192. \section{The \LangDyn{} Language}
  15193. \newcommand{\LdynGrammarRacket}{
  15194. \begin{array}{rcl}
  15195. \Exp &::=& \LP\Exp \; \Exp\ldots\RP
  15196. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15197. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15198. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15199. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP
  15200. \end{array}
  15201. }
  15202. \newcommand{\LdynASTRacket}{
  15203. \begin{array}{lcl}
  15204. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  15205. \MID \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15206. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp}
  15207. \end{array}
  15208. }
  15209. \begin{figure}[tp]
  15210. \centering
  15211. \fbox{
  15212. \begin{minipage}{0.97\textwidth}
  15213. \small
  15214. {\if\edition\racketEd
  15215. \[
  15216. \begin{array}{l}
  15217. \gray{\LintGrammarRacket{}} \\ \hline
  15218. \gray{\LvarGrammarRacket{}} \\ \hline
  15219. \gray{\LifGrammarRacket{}} \\ \hline
  15220. \gray{\LwhileGrammarRacket} \\ \hline
  15221. \gray{\LtupGrammarRacket} \\ \hline
  15222. \LdynGrammarRacket \\
  15223. \begin{array}{rcl}
  15224. \LangDynM{} &::=& \Def\ldots\; \Exp
  15225. \end{array}
  15226. \end{array}
  15227. \]
  15228. \fi}
  15229. {\if\edition\pythonEd
  15230. \[
  15231. \begin{array}{rcl}
  15232. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15233. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15234. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15235. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15236. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15237. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15238. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15239. \MID \CLEN{\Exp} \\
  15240. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15241. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15242. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15243. \MID \Var\mathop{\key{=}}\Exp \\
  15244. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15245. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15246. &\MID& \CRETURN{\Exp} \\
  15247. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15248. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15249. \end{array}
  15250. \]
  15251. \fi}
  15252. \end{minipage}
  15253. }
  15254. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15255. \label{fig:r7-concrete-syntax}
  15256. \end{figure}
  15257. \begin{figure}[tp]
  15258. \centering
  15259. \fbox{
  15260. \begin{minipage}{0.96\textwidth}
  15261. \small
  15262. {\if\edition\racketEd
  15263. \[
  15264. \begin{array}{l}
  15265. \gray{\LintASTRacket{}} \\ \hline
  15266. \gray{\LvarASTRacket{}} \\ \hline
  15267. \gray{\LifASTRacket{}} \\ \hline
  15268. \gray{\LwhileASTRacket} \\ \hline
  15269. \gray{\LtupASTRacket} \\ \hline
  15270. \LdynASTRacket \\
  15271. \begin{array}{lcl}
  15272. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15273. \end{array}
  15274. \end{array}
  15275. \]
  15276. \fi}
  15277. {\if\edition\pythonEd
  15278. \[
  15279. \begin{array}{rcl}
  15280. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15281. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15282. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15283. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15284. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15285. &\MID & \code{Is()} \\
  15286. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15287. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15288. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15289. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15290. \MID \VAR{\Var{}} \\
  15291. &\MID& \BOOL{\itm{bool}}
  15292. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15293. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15294. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15295. &\MID& \LEN{\Exp} \\
  15296. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15297. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15298. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15299. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15300. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15301. &\MID& \RETURN{\Exp} \\
  15302. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15303. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15304. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15305. \end{array}
  15306. \]
  15307. \fi}
  15308. \end{minipage}
  15309. }
  15310. \caption{The abstract syntax of \LangDyn{}.}
  15311. \label{fig:r7-syntax}
  15312. \end{figure}
  15313. The concrete and abstract syntax of \LangDyn{} is defined in
  15314. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15315. %
  15316. There is no type checker for \LangDyn{} because it only checks types
  15317. at runtime.
  15318. The definitional interpreter for \LangDyn{} is presented in
  15319. \racket{Figure~\ref{fig:interp-Ldyn}}
  15320. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15321. and its auxiliary functions are defined in
  15322. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15323. \INT{n}. Instead of simply returning the integer \code{n} (as
  15324. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15325. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15326. value} that combines an underlying value with a tag that identifies
  15327. what kind of value it is. We define the following \racket{struct}\python{class}
  15328. to represented tagged values.
  15329. %
  15330. {\if\edition\racketEd
  15331. \begin{lstlisting}
  15332. (struct Tagged (value tag) #:transparent)
  15333. \end{lstlisting}
  15334. \fi}
  15335. {\if\edition\pythonEd
  15336. \begin{minipage}{\textwidth}
  15337. \begin{lstlisting}
  15338. @dataclass(eq=True)
  15339. class Tagged(Value):
  15340. value : Value
  15341. tag : str
  15342. def __str__(self):
  15343. return str(self.value)
  15344. \end{lstlisting}
  15345. \end{minipage}
  15346. \fi}
  15347. %
  15348. \racket{The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15349. \code{Vector}, and \code{Procedure}.}
  15350. %
  15351. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15352. \code{'tuple'}, and \code{'function'}.}
  15353. %
  15354. Tags are closely related to types but don't always capture all the
  15355. information that a type does.
  15356. %
  15357. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15358. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15359. Any)} is tagged with \code{Procedure}.}
  15360. %
  15361. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15362. is tagged with \code{'tuple'} and a function of type
  15363. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15364. is tagged with \code{'function'}.}
  15365. Next consider the match case for accessing the element of a tuple.
  15366. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15367. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15368. argument is a tuple and the second is an integer.
  15369. \racket{
  15370. If they are not, a \code{trapped-error} is raised. Recall from
  15371. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15372. raises a \code{trapped-error} error, the compiled code must also
  15373. signal an error by exiting with return code \code{255}. A
  15374. \code{trapped-error} is also raised if the index is not less than the
  15375. length of the vector.
  15376. }
  15377. %
  15378. \python{If they are not, an exception is raised. The compiled code
  15379. must also signal an error by exiting with return code \code{255}. A
  15380. exception is also raised if the index is not less than the length of the
  15381. tuple or if it is negative.}
  15382. \begin{figure}[tbp]
  15383. {\if\edition\racketEd
  15384. \begin{lstlisting}
  15385. (define ((interp-Ldyn-exp env) ast)
  15386. (define recur (interp-Ldyn-exp env))
  15387. (match ast
  15388. [(Var x) (dict-ref env x)]
  15389. [(Int n) (Tagged n 'Integer)]
  15390. [(Bool b) (Tagged b 'Boolean)]
  15391. [(Lambda xs rt body)
  15392. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15393. [(Prim 'vector es)
  15394. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15395. [(Prim 'vector-ref (list e1 e2))
  15396. (define vec (recur e1)) (define i (recur e2))
  15397. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15398. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15399. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15400. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15401. [(Prim 'vector-set! (list e1 e2 e3))
  15402. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15403. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15404. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15405. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15406. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15407. (Tagged (void) 'Void)]
  15408. [(Let x e body) ((interp-Ldyn-exp (cons (cons x (recur e)) env)) body)]
  15409. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15410. [(Prim 'or (list e1 e2))
  15411. (define v1 (recur e1))
  15412. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15413. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15414. [(Prim op (list e1))
  15415. #:when (set-member? type-predicates op)
  15416. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15417. [(Prim op es)
  15418. (define args (map recur es))
  15419. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15420. (unless (for/or ([expected-tags (op-tags op)])
  15421. (equal? expected-tags tags))
  15422. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15423. (tag-value
  15424. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15425. [(If q t f)
  15426. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15427. [(Apply f es)
  15428. (define new-f (recur f)) (define args (map recur es))
  15429. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15430. (match f-val
  15431. [`(function ,xs ,body ,lam-env)
  15432. (unless (eq? (length xs) (length args))
  15433. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15434. (define new-env (append (map cons xs args) lam-env))
  15435. ((interp-Ldyn-exp new-env) body)]
  15436. [else (error "interp-Ldyn-exp, expected function, not" f-val)])]))
  15437. \end{lstlisting}
  15438. \fi}
  15439. {\if\edition\pythonEd
  15440. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15441. class InterpLdyn(InterpLlambda):
  15442. def interp_exp(self, e, env):
  15443. match e:
  15444. case Constant(n):
  15445. return self.tag(super().interp_exp(e, env))
  15446. case Tuple(es, Load()):
  15447. return self.tag(super().interp_exp(e, env))
  15448. case Lambda(params, body):
  15449. return self.tag(super().interp_exp(e, env))
  15450. case Call(Name('input_int'), []):
  15451. return self.tag(super().interp_exp(e, env))
  15452. case BinOp(left, Add(), right):
  15453. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15454. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15455. case BinOp(left, Sub(), right):
  15456. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15457. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15458. case UnaryOp(USub(), e1):
  15459. v = self.interp_exp(e1, env)
  15460. return self.tag(- self.untag(v, 'int', e))
  15461. case IfExp(test, body, orelse):
  15462. v = self.interp_exp(test, env)
  15463. if self.untag(v, 'bool', e):
  15464. return self.interp_exp(body, env)
  15465. else:
  15466. return self.interp_exp(orelse, env)
  15467. case UnaryOp(Not(), e1):
  15468. v = self.interp_exp(e1, env)
  15469. return self.tag(not self.untag(v, 'bool', e))
  15470. case BoolOp(And(), values):
  15471. left = values[0]; right = values[1]
  15472. l = self.interp_exp(left, env)
  15473. if self.untag(l, 'bool', e):
  15474. return self.interp_exp(right, env)
  15475. else:
  15476. return self.tag(False)
  15477. case BoolOp(Or(), values):
  15478. left = values[0]; right = values[1]
  15479. l = self.interp_exp(left, env)
  15480. if self.untag(l, 'bool', e):
  15481. return self.tag(True)
  15482. else:
  15483. return self.interp_exp(right, env)
  15484. case Compare(left, [cmp], [right]):
  15485. l = self.interp_exp(left, env)
  15486. r = self.interp_exp(right, env)
  15487. if l.tag == r.tag:
  15488. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15489. else:
  15490. raise Exception('interp Compare unexpected ' \
  15491. + repr(l) + ' ' + repr(r))
  15492. case Subscript(tup, index, Load()):
  15493. t = self.interp_exp(tup, env)
  15494. n = self.interp_exp(index, env)
  15495. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15496. case Call(Name('len'), [tup]):
  15497. t = self.interp_exp(tup, env)
  15498. return self.tag(len(self.untag(t, 'tuple', e)))
  15499. case _:
  15500. return self.tag(super().interp_exp(e, env))
  15501. \end{lstlisting}
  15502. \fi}
  15503. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  15504. \label{fig:interp-Ldyn}
  15505. \end{figure}
  15506. {\if\edition\pythonEd
  15507. \begin{figure}[tbp]
  15508. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15509. class InterpLdyn(InterpLlambda):
  15510. def interp_stmts(self, ss, env):
  15511. if len(ss) == 0:
  15512. return
  15513. match ss[0]:
  15514. case If(test, body, orelse):
  15515. v = self.interp_exp(test, env)
  15516. if self.untag(v, 'bool', ss[0]):
  15517. return self.interp_stmts(body + ss[1:], env)
  15518. else:
  15519. return self.interp_stmts(orelse + ss[1:], env)
  15520. case While(test, body, []):
  15521. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15522. self.interp_stmts(body, env)
  15523. return self.interp_stmts(ss[1:], env)
  15524. case Assign([Subscript(tup, index)], value):
  15525. tup = self.interp_exp(tup, env)
  15526. index = self.interp_exp(index, env)
  15527. tup_v = self.untag(tup, 'tuple', ss[0])
  15528. index_v = self.untag(index, 'int', ss[0])
  15529. tup_v[index_v] = self.interp_exp(value, env)
  15530. return self.interp_stmts(ss[1:], env)
  15531. case FunctionDef(name, params, bod, dl, returns, comment):
  15532. ps = [x for (x,t) in params]
  15533. env[name] = self.tag(Function(name, ps, bod, env))
  15534. return self.interp_stmts(ss[1:], env)
  15535. case _:
  15536. return super().interp_stmts(ss, env)
  15537. \end{lstlisting}
  15538. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  15539. \label{fig:interp-Ldyn-2}
  15540. \end{figure}
  15541. \fi}
  15542. \begin{figure}[tbp]
  15543. {\if\edition\racketEd
  15544. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15545. (define (interp-op op)
  15546. (match op
  15547. ['+ fx+]
  15548. ['- fx-]
  15549. ['read read-fixnum]
  15550. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15551. ['< (lambda (v1 v2)
  15552. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15553. ['<= (lambda (v1 v2)
  15554. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15555. ['> (lambda (v1 v2)
  15556. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15557. ['>= (lambda (v1 v2)
  15558. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15559. ['boolean? boolean?]
  15560. ['integer? fixnum?]
  15561. ['void? void?]
  15562. ['vector? vector?]
  15563. ['vector-length vector-length]
  15564. ['procedure? (match-lambda
  15565. [`(functions ,xs ,body ,env) #t] [else #f])]
  15566. [else (error 'interp-op "unknown operator" op)]))
  15567. (define (op-tags op)
  15568. (match op
  15569. ['+ '((Integer Integer))]
  15570. ['- '((Integer Integer) (Integer))]
  15571. ['read '(())]
  15572. ['not '((Boolean))]
  15573. ['< '((Integer Integer))]
  15574. ['<= '((Integer Integer))]
  15575. ['> '((Integer Integer))]
  15576. ['>= '((Integer Integer))]
  15577. ['vector-length '((Vector))]))
  15578. (define type-predicates
  15579. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15580. (define (tag-value v)
  15581. (cond [(boolean? v) (Tagged v 'Boolean)]
  15582. [(fixnum? v) (Tagged v 'Integer)]
  15583. [(procedure? v) (Tagged v 'Procedure)]
  15584. [(vector? v) (Tagged v 'Vector)]
  15585. [(void? v) (Tagged v 'Void)]
  15586. [else (error 'tag-value "unidentified value ~a" v)]))
  15587. (define (check-tag val expected ast)
  15588. (define tag (Tagged-tag val))
  15589. (unless (eq? tag expected)
  15590. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15591. \end{lstlisting}
  15592. \fi}
  15593. {\if\edition\pythonEd
  15594. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15595. class InterpLdyn(InterpLlambda):
  15596. def tag(self, v):
  15597. if v is True or v is False:
  15598. return Tagged(v, 'bool')
  15599. elif isinstance(v, int):
  15600. return Tagged(v, 'int')
  15601. elif isinstance(v, Function):
  15602. return Tagged(v, 'function')
  15603. elif isinstance(v, tuple):
  15604. return Tagged(v, 'tuple')
  15605. elif isinstance(v, type(None)):
  15606. return Tagged(v, 'none')
  15607. else:
  15608. raise Exception('tag: unexpected ' + repr(v))
  15609. def untag(self, v, expected_tag, ast):
  15610. match v:
  15611. case Tagged(val, tag) if tag == expected_tag:
  15612. return val
  15613. case _:
  15614. raise Exception('expected Tagged value with ' + expected_tag + ', not ' + ' ' + repr(v))
  15615. def apply_fun(self, fun, args, e):
  15616. f = self.untag(fun, 'function', e)
  15617. return super().apply_fun(f, args, e)
  15618. \end{lstlisting}
  15619. \fi}
  15620. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15621. \label{fig:interp-Ldyn-aux}
  15622. \end{figure}
  15623. \clearpage
  15624. \section{Representation of Tagged Values}
  15625. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15626. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15627. values at the bit level. Because almost every operation in \LangDyn{}
  15628. involves manipulating tagged values, the representation must be
  15629. efficient. Recall that all of our values are 64 bits. We shall steal
  15630. the 3 right-most bits to encode the tag. We use $001$ to identify
  15631. integers, $100$ for Booleans, $010$ for tuples, $011$ for procedures,
  15632. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  15633. function for mapping types to tag codes.
  15634. {\if\edition\racketEd
  15635. \begin{align*}
  15636. \itm{tagof}(\key{Integer}) &= 001 \\
  15637. \itm{tagof}(\key{Boolean}) &= 100 \\
  15638. \itm{tagof}(\LP\key{Vector} \ldots\RP) &= 010 \\
  15639. \itm{tagof}(\LP\ldots \key{->} \ldots\RP) &= 011 \\
  15640. \itm{tagof}(\key{Void}) &= 101
  15641. \end{align*}
  15642. \fi}
  15643. {\if\edition\pythonEd
  15644. \begin{align*}
  15645. \itm{tagof}(\key{IntType()}) &= 001 \\
  15646. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15647. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15648. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15649. \itm{tagof}(\key{type(None)}) &= 101
  15650. \end{align*}
  15651. \fi}
  15652. This stealing of 3 bits comes at some price: integers are now restricted
  15653. to the range from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15654. affect tuples and procedures because those values are addresses, and
  15655. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15656. they are always $000$. Thus, we do not lose information by overwriting
  15657. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15658. to recover the original address.
  15659. To make tagged values into first-class entities, we can give them a
  15660. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define
  15661. operations such as \code{Inject} and \code{Project} for creating and
  15662. using them, yielding the statically typed \LangAny{} intermediate
  15663. language. We describe how to compile \LangDyn{} to \LangAny{} in
  15664. Section~\ref{sec:compile-r7} but first we describe the \LangAny{}
  15665. language in greater detail.
  15666. \section{The \LangAny{} Language}
  15667. \label{sec:Rany-lang}
  15668. \newcommand{\LanyASTRacket}{
  15669. \begin{array}{lcl}
  15670. \Type &::= & \ANYTY \\
  15671. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15672. \MID \LP\key{Vector}\; \ANYTY\ldots\RP
  15673. \MID \LP\ANYTY\ldots \; \key{->}\; \ANYTY\RP\\
  15674. \itm{op} &::= & \code{any-vector-length}
  15675. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15676. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15677. \MID \code{procedure?} \MID \code{void?} \\
  15678. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15679. \end{array}
  15680. }
  15681. \newcommand{\LanyASTPython}{
  15682. \begin{array}{lcl}
  15683. \Type &::= & \key{AnyType()} \\
  15684. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15685. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15686. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  15687. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15688. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\INT{n}\RS}\\
  15689. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS}
  15690. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  15691. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  15692. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  15693. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  15694. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  15695. \end{array}
  15696. }
  15697. \begin{figure}[tp]
  15698. \centering
  15699. \fbox{
  15700. \begin{minipage}{0.96\textwidth}
  15701. \small
  15702. {\if\edition\racketEd
  15703. \[
  15704. \begin{array}{l}
  15705. \gray{\LintOpAST} \\ \hline
  15706. \gray{\LvarASTRacket{}} \\ \hline
  15707. \gray{\LifASTRacket{}} \\ \hline
  15708. \gray{\LwhileASTRacket{}} \\ \hline
  15709. \gray{\LtupASTRacket{}} \\ \hline
  15710. \gray{\LfunASTRacket} \\ \hline
  15711. \gray{\LlambdaASTRacket} \\ \hline
  15712. \LanyASTRacket \\
  15713. \begin{array}{lcl}
  15714. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15715. \end{array}
  15716. \end{array}
  15717. \]
  15718. \fi}
  15719. {\if\edition\pythonEd
  15720. \[
  15721. \begin{array}{l}
  15722. \gray{\LintASTPython} \\ \hline
  15723. \gray{\LvarASTPython{}} \\ \hline
  15724. \gray{\LifASTPython{}} \\ \hline
  15725. \gray{\LwhileASTPython{}} \\ \hline
  15726. \gray{\LtupASTPython{}} \\ \hline
  15727. \gray{\LfunASTPython} \\ \hline
  15728. \gray{\LlambdaASTPython} \\ \hline
  15729. \LanyASTPython \\
  15730. \begin{array}{lcl}
  15731. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15732. \end{array}
  15733. \end{array}
  15734. \]
  15735. \fi}
  15736. \end{minipage}
  15737. }
  15738. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Llam-syntax}).}
  15739. \label{fig:Lany-syntax}
  15740. \end{figure}
  15741. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Lany-syntax}.
  15742. %% \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  15743. %% Figure~\ref{fig:Lany-concrete-syntax}.)}
  15744. The $\INJECT{e}{T}$ form
  15745. converts the value produced by expression $e$ of type $T$ into a
  15746. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15747. produced by expression $e$ into a value of type $T$ or halts the
  15748. program if the type tag does not match $T$.
  15749. %
  15750. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15751. restricted to a flat type $\FType$, which simplifies the
  15752. implementation and corresponds with the needs for compiling \LangDyn{}.
  15753. The \racket{\code{any-vector}} operators
  15754. \python{\code{any\_tuple\_load} and \code{any\_len}}
  15755. adapt the tuple operations so that they can be applied to a value of
  15756. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  15757. tuple operations in that the index is not restricted to be a literal
  15758. integer in the grammar but is allowed to be any expression.
  15759. \racket{The type predicates such as
  15760. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  15761. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  15762. the predicate and they return {\FALSE} otherwise.}
  15763. The type checker for \LangAny{} is shown in
  15764. Figure~\ref{fig:type-check-Lany}
  15765. %
  15766. \racket{ and uses the auxiliary functions in
  15767. Figure~\ref{fig:type-check-Lany-aux}}.
  15768. %
  15769. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Lany} and
  15770. its auxiliary functions are in Figure~\ref{fig:interp-Lany-aux}.
  15771. \begin{figure}[btp]
  15772. {\if\edition\racketEd
  15773. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15774. (define type-check-Lany-class
  15775. (class type-check-Llambda-class
  15776. (super-new)
  15777. (inherit check-type-equal?)
  15778. (define/override (type-check-exp env)
  15779. (lambda (e)
  15780. (define recur (type-check-exp env))
  15781. (match e
  15782. [(Inject e1 ty)
  15783. (unless (flat-ty? ty)
  15784. (error 'type-check "may only inject from flat type, not ~a" ty))
  15785. (define-values (new-e1 e-ty) (recur e1))
  15786. (check-type-equal? e-ty ty e)
  15787. (values (Inject new-e1 ty) 'Any)]
  15788. [(Project e1 ty)
  15789. (unless (flat-ty? ty)
  15790. (error 'type-check "may only project to flat type, not ~a" ty))
  15791. (define-values (new-e1 e-ty) (recur e1))
  15792. (check-type-equal? e-ty 'Any e)
  15793. (values (Project new-e1 ty) ty)]
  15794. [(Prim 'any-vector-length (list e1))
  15795. (define-values (e1^ t1) (recur e1))
  15796. (check-type-equal? t1 'Any e)
  15797. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15798. [(Prim 'any-vector-ref (list e1 e2))
  15799. (define-values (e1^ t1) (recur e1))
  15800. (define-values (e2^ t2) (recur e2))
  15801. (check-type-equal? t1 'Any e)
  15802. (check-type-equal? t2 'Integer e)
  15803. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15804. [(Prim 'any-vector-set! (list e1 e2 e3))
  15805. (define-values (e1^ t1) (recur e1))
  15806. (define-values (e2^ t2) (recur e2))
  15807. (define-values (e3^ t3) (recur e3))
  15808. (check-type-equal? t1 'Any e)
  15809. (check-type-equal? t2 'Integer e)
  15810. (check-type-equal? t3 'Any e)
  15811. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15812. [(Prim pred (list e1))
  15813. #:when (set-member? (type-predicates) pred)
  15814. (define-values (new-e1 e-ty) (recur e1))
  15815. (check-type-equal? e-ty 'Any e)
  15816. (values (Prim pred (list new-e1)) 'Boolean)]
  15817. [(Prim 'eq? (list arg1 arg2))
  15818. (define-values (e1 t1) (recur arg1))
  15819. (define-values (e2 t2) (recur arg2))
  15820. (match* (t1 t2)
  15821. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15822. [(other wise) (check-type-equal? t1 t2 e)])
  15823. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15824. [else ((super type-check-exp env) e)])))
  15825. ))
  15826. \end{lstlisting}
  15827. \fi}
  15828. {\if\edition\pythonEd
  15829. \begin{lstlisting}
  15830. class TypeCheckLany(TypeCheckLlambda):
  15831. def type_check_exp(self, e, env):
  15832. match e:
  15833. case Inject(value, typ):
  15834. self.check_exp(value, typ, env)
  15835. return AnyType()
  15836. case Project(value, typ):
  15837. self.check_exp(value, AnyType(), env)
  15838. return typ
  15839. case Call(Name('any_tuple_load'), [tup, index]):
  15840. self.check_exp(tup, AnyType(), env)
  15841. return AnyType()
  15842. case Call(Name('any_len'), [tup]):
  15843. self.check_exp(tup, AnyType(), env)
  15844. return IntType()
  15845. case Call(Name('arity'), [fun]):
  15846. ty = self.type_check_exp(fun, env)
  15847. match ty:
  15848. case FunctionType(ps, rt):
  15849. return IntType()
  15850. case TupleType([FunctionType(ps,rs)]):
  15851. return IntType()
  15852. case _:
  15853. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  15854. case Call(Name('make_any'), [value, tag]):
  15855. self.type_check_exp(value, env)
  15856. self.check_exp(tag, IntType(), env)
  15857. return AnyType()
  15858. case AnnLambda(params, returns, body):
  15859. new_env = {x:t for (x,t) in env.items()}
  15860. for (x,t) in params:
  15861. new_env[x] = t
  15862. return_t = self.type_check_exp(body, new_env)
  15863. self.check_type_equal(returns, return_t, e)
  15864. return FunctionType([t for (x,t) in params], return_t)
  15865. case _:
  15866. return super().type_check_exp(e, env)
  15867. \end{lstlisting}
  15868. \fi}
  15869. \caption{Type checker for the \LangAny{} language.}
  15870. \label{fig:type-check-Lany}
  15871. \end{figure}
  15872. {\if\edition\racketEd
  15873. \begin{figure}[tbp]
  15874. {\if\edition\racketEd
  15875. \begin{lstlisting}
  15876. (define/override (operator-types)
  15877. (append
  15878. '((integer? . ((Any) . Boolean))
  15879. (vector? . ((Any) . Boolean))
  15880. (procedure? . ((Any) . Boolean))
  15881. (void? . ((Any) . Boolean)))
  15882. (super operator-types)))
  15883. (define/public (type-predicates)
  15884. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15885. (define/public (flat-ty? ty)
  15886. (match ty
  15887. [(or `Integer `Boolean `Void) #t]
  15888. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15889. ['(Vectorof Any) #t]
  15890. [`(,ts ... -> ,rt)
  15891. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15892. [else #f]))
  15893. \end{lstlisting}
  15894. \fi}
  15895. \caption{Auxiliary methods for type checking \LangAny{}.}
  15896. \label{fig:type-check-Lany-aux}
  15897. \end{figure}
  15898. \fi}
  15899. \begin{figure}[btp]
  15900. {\if\edition\racketEd
  15901. \begin{lstlisting}
  15902. (define interp-Lany-class
  15903. (class interp-Llambda-class
  15904. (super-new)
  15905. (define/override (interp-op op)
  15906. (match op
  15907. ['boolean? (match-lambda
  15908. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15909. [else #f])]
  15910. ['integer? (match-lambda
  15911. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15912. [else #f])]
  15913. ['vector? (match-lambda
  15914. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15915. [else #f])]
  15916. ['procedure? (match-lambda
  15917. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15918. [else #f])]
  15919. ['eq? (match-lambda*
  15920. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15921. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15922. [ls (apply (super interp-op op) ls)])]
  15923. ['any-vector-ref (lambda (v i)
  15924. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15925. ['any-vector-set! (lambda (v i a)
  15926. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15927. ['any-vector-length (lambda (v)
  15928. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15929. [else (super interp-op op)]))
  15930. (define/override ((interp-exp env) e)
  15931. (define recur (interp-exp env))
  15932. (match e
  15933. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15934. [(Project e ty2) (apply-project (recur e) ty2)]
  15935. [else ((super interp-exp env) e)]))
  15936. ))
  15937. (define (interp-Lany p)
  15938. (send (new interp-Lany-class) interp-program p))
  15939. \end{lstlisting}
  15940. \fi}
  15941. {\if\edition\pythonEd
  15942. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15943. class InterpLany(InterpLlambda):
  15944. def interp_exp(self, e, env):
  15945. match e:
  15946. case Inject(value, typ):
  15947. v = self.interp_exp(value, env)
  15948. return Tagged(v, self.type_to_tag(typ))
  15949. case Project(value, typ):
  15950. v = self.interp_exp(value, env)
  15951. match v:
  15952. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  15953. return val
  15954. case _:
  15955. raise Exception('interp project to ' + repr(typ) \
  15956. + ' unexpected ' + repr(v))
  15957. case Call(Name('any_tuple_load'), [tup, index]):
  15958. tv = self.interp_exp(tup, env)
  15959. n = self.interp_exp(index, env)
  15960. match tv:
  15961. case Tagged(v, tag):
  15962. return v[n]
  15963. case _:
  15964. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15965. case Call(Name('any_tuple_store'), [tup, index, value]):
  15966. tv = self.interp_exp(tup, env)
  15967. n = self.interp_exp(index, env)
  15968. val = self.interp_exp(value, env)
  15969. match tv:
  15970. case Tagged(v, tag):
  15971. v[n] = val
  15972. return None
  15973. case _:
  15974. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15975. case Call(Name('any_len'), [value]):
  15976. v = self.interp_exp(value, env)
  15977. match v:
  15978. case Tagged(value, tag):
  15979. return len(value)
  15980. case _:
  15981. raise Exception('interp any_len unexpected ' + repr(v))
  15982. case Call(Name('arity'), [fun]):
  15983. f = self.interp_exp(fun, env)
  15984. return self.arity(f)
  15985. case _:
  15986. return super().interp_exp(e, env)
  15987. \end{lstlisting}
  15988. \fi}
  15989. \caption{Interpreter for \LangAny{}.}
  15990. \label{fig:interp-Lany}
  15991. \end{figure}
  15992. \begin{figure}[tbp]
  15993. {\if\edition\racketEd
  15994. \begin{lstlisting}
  15995. (define/public (apply-inject v tg) (Tagged v tg))
  15996. (define/public (apply-project v ty2)
  15997. (define tag2 (any-tag ty2))
  15998. (match v
  15999. [(Tagged v1 tag1)
  16000. (cond
  16001. [(eq? tag1 tag2)
  16002. (match ty2
  16003. [`(Vector ,ts ...)
  16004. (define l1 ((interp-op 'vector-length) v1))
  16005. (cond
  16006. [(eq? l1 (length ts)) v1]
  16007. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  16008. l1 (length ts))])]
  16009. [`(,ts ... -> ,rt)
  16010. (match v1
  16011. [`(function ,xs ,body ,env)
  16012. (cond [(eq? (length xs) (length ts)) v1]
  16013. [else
  16014. (error 'apply-project "arity mismatch ~a != ~a"
  16015. (length xs) (length ts))])]
  16016. [else (error 'apply-project "expected function not ~a" v1)])]
  16017. [else v1])]
  16018. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16019. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16020. \end{lstlisting}
  16021. \fi}
  16022. {\if\edition\pythonEd
  16023. \begin{lstlisting}
  16024. class InterpLany(InterpLlambda):
  16025. def type_to_tag(self, typ):
  16026. match typ:
  16027. case FunctionType(params, rt):
  16028. return 'function'
  16029. case TupleType(fields):
  16030. return 'tuple'
  16031. case t if t == int:
  16032. return 'int'
  16033. case t if t == bool:
  16034. return 'bool'
  16035. case IntType():
  16036. return 'int'
  16037. case BoolType():
  16038. return 'int'
  16039. case _:
  16040. raise Exception('type_to_tag unexpected ' + repr(typ))
  16041. def arity(self, v):
  16042. match v:
  16043. case Function(name, params, body, env):
  16044. return len(params)
  16045. case ClosureTuple(args, arity):
  16046. return arity
  16047. case _:
  16048. raise Exception('Lany arity unexpected ' + repr(v))
  16049. \end{lstlisting}
  16050. \fi}
  16051. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16052. \label{fig:interp-Lany-aux}
  16053. \end{figure}
  16054. \clearpage
  16055. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16056. \label{sec:compile-r7}
  16057. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16058. Figure~\ref{fig:compile-r7-Lany} shows the compilation of many of the
  16059. \LangDyn{} forms into \LangAny{}. An important invariant of this pass
  16060. is that given any subexpression $e$ in the \LangDyn{} program, the
  16061. pass will produce an expression $e'$ in \LangAny{} that has type
  16062. \ANYTY{}. For example, the first row in
  16063. Figure~\ref{fig:compile-r7-Lany} shows the compilation of the Boolean
  16064. \TRUE{}, which must be injected to produce an expression of type
  16065. \ANYTY{}.
  16066. %
  16067. The second row of Figure~\ref{fig:compile-r7-Lany}, the compilation of
  16068. addition, is representative of compilation for many primitive
  16069. operations: the arguments have type \ANYTY{} and must be projected to
  16070. \INTTYPE{} before the addition can be performed.
  16071. The compilation of \key{lambda} (third row of
  16072. Figure~\ref{fig:compile-r7-Lany}) shows what happens when we need to
  16073. produce type annotations: we simply use \ANYTY{}.
  16074. %
  16075. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16076. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16077. this pass has to account for some differences in behavior between
  16078. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16079. permissive than \LangAny{} regarding what kind of values can be used
  16080. in various places. For example, the condition of an \key{if} does
  16081. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16082. of the same type (in that case the result is \code{\#f}).}
  16083. \begin{figure}[btp]
  16084. \centering
  16085. {\if\edition\racketEd
  16086. \begin{tabular}{|lll|} \hline
  16087. \begin{minipage}{0.27\textwidth}
  16088. \begin{lstlisting}
  16089. #t
  16090. \end{lstlisting}
  16091. \end{minipage}
  16092. &
  16093. $\Rightarrow$
  16094. &
  16095. \begin{minipage}{0.65\textwidth}
  16096. \begin{lstlisting}
  16097. (inject #t Boolean)
  16098. \end{lstlisting}
  16099. \end{minipage}
  16100. \\[2ex]\hline
  16101. \begin{minipage}{0.27\textwidth}
  16102. \begin{lstlisting}
  16103. (+ |$e_1$| |$e_2$|)
  16104. \end{lstlisting}
  16105. \end{minipage}
  16106. &
  16107. $\Rightarrow$
  16108. &
  16109. \begin{minipage}{0.65\textwidth}
  16110. \begin{lstlisting}
  16111. (inject
  16112. (+ (project |$e'_1$| Integer)
  16113. (project |$e'_2$| Integer))
  16114. Integer)
  16115. \end{lstlisting}
  16116. \end{minipage}
  16117. \\[2ex]\hline
  16118. \begin{minipage}{0.27\textwidth}
  16119. \begin{lstlisting}
  16120. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  16121. \end{lstlisting}
  16122. \end{minipage}
  16123. &
  16124. $\Rightarrow$
  16125. &
  16126. \begin{minipage}{0.65\textwidth}
  16127. \begin{lstlisting}
  16128. (inject
  16129. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  16130. (Any|$\ldots$|Any -> Any))
  16131. \end{lstlisting}
  16132. \end{minipage}
  16133. \\[2ex]\hline
  16134. \begin{minipage}{0.27\textwidth}
  16135. \begin{lstlisting}
  16136. (|$e_0$| |$e_1 \ldots e_n$|)
  16137. \end{lstlisting}
  16138. \end{minipage}
  16139. &
  16140. $\Rightarrow$
  16141. &
  16142. \begin{minipage}{0.65\textwidth}
  16143. \begin{lstlisting}
  16144. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16145. \end{lstlisting}
  16146. \end{minipage}
  16147. \\[2ex]\hline
  16148. \begin{minipage}{0.27\textwidth}
  16149. \begin{lstlisting}
  16150. (vector-ref |$e_1$| |$e_2$|)
  16151. \end{lstlisting}
  16152. \end{minipage}
  16153. &
  16154. $\Rightarrow$
  16155. &
  16156. \begin{minipage}{0.65\textwidth}
  16157. \begin{lstlisting}
  16158. (any-vector-ref |$e_1'$| |$e_2'$|)
  16159. \end{lstlisting}
  16160. \end{minipage}
  16161. \\[2ex]\hline
  16162. \begin{minipage}{0.27\textwidth}
  16163. \begin{lstlisting}
  16164. (if |$e_1$| |$e_2$| |$e_3$|)
  16165. \end{lstlisting}
  16166. \end{minipage}
  16167. &
  16168. $\Rightarrow$
  16169. &
  16170. \begin{minipage}{0.65\textwidth}
  16171. \begin{lstlisting}
  16172. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16173. \end{lstlisting}
  16174. \end{minipage}
  16175. \\[2ex]\hline
  16176. \begin{minipage}{0.27\textwidth}
  16177. \begin{lstlisting}
  16178. (eq? |$e_1$| |$e_2$|)
  16179. \end{lstlisting}
  16180. \end{minipage}
  16181. &
  16182. $\Rightarrow$
  16183. &
  16184. \begin{minipage}{0.65\textwidth}
  16185. \begin{lstlisting}
  16186. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16187. \end{lstlisting}
  16188. \end{minipage}
  16189. \\[2ex]\hline
  16190. \begin{minipage}{0.27\textwidth}
  16191. \begin{lstlisting}
  16192. (not |$e_1$|)
  16193. \end{lstlisting}
  16194. \end{minipage}
  16195. &
  16196. $\Rightarrow$
  16197. &
  16198. \begin{minipage}{0.65\textwidth}
  16199. \begin{lstlisting}
  16200. (if (eq? |$e'_1$| (inject #f Boolean))
  16201. (inject #t Boolean) (inject #f Boolean))
  16202. \end{lstlisting}
  16203. \end{minipage}
  16204. \\[2ex]\hline
  16205. \end{tabular}
  16206. \fi}
  16207. {\if\edition\pythonEd
  16208. \begin{tabular}{|lll|} \hline
  16209. \begin{minipage}{0.22\textwidth}
  16210. \begin{lstlisting}
  16211. True
  16212. \end{lstlisting}
  16213. \end{minipage}
  16214. &
  16215. $\Rightarrow$
  16216. &
  16217. \begin{minipage}{0.7\textwidth}
  16218. \begin{lstlisting}
  16219. Inject(True, BoolType())
  16220. \end{lstlisting}
  16221. \end{minipage}
  16222. \\[2ex]\hline
  16223. \begin{minipage}{0.22\textwidth}
  16224. \begin{lstlisting}
  16225. |$e_1$| + |$e_2$|
  16226. \end{lstlisting}
  16227. \end{minipage}
  16228. &
  16229. $\Rightarrow$
  16230. &
  16231. \begin{minipage}{0.7\textwidth}
  16232. \begin{lstlisting}
  16233. Inject(Project(|$e'_1$|, IntType())
  16234. + Project(|$e'_2$|, IntType()),
  16235. IntType())
  16236. \end{lstlisting}
  16237. \end{minipage}
  16238. \\[2ex]\hline
  16239. \begin{minipage}{0.22\textwidth}
  16240. \begin{lstlisting}
  16241. lambda |$x_1 \ldots x_n$|: |$e$|
  16242. \end{lstlisting}
  16243. \end{minipage}
  16244. &
  16245. $\Rightarrow$
  16246. &
  16247. \begin{minipage}{0.7\textwidth}
  16248. \begin{lstlisting}
  16249. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|,(|$x_n$|,AnyType)], |$e'$|)
  16250. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16251. \end{lstlisting}
  16252. \end{minipage}
  16253. \\[2ex]\hline
  16254. \begin{minipage}{0.22\textwidth}
  16255. \begin{lstlisting}
  16256. |$e_0$|(|$e_1 \ldots e_n$|)
  16257. \end{lstlisting}
  16258. \end{minipage}
  16259. &
  16260. $\Rightarrow$
  16261. &
  16262. \begin{minipage}{0.7\textwidth}
  16263. \begin{lstlisting}
  16264. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16265. AnyType())), |$e'_1, \ldots, e'_n$|)
  16266. \end{lstlisting}
  16267. \end{minipage}
  16268. \\[2ex]\hline
  16269. \begin{minipage}{0.22\textwidth}
  16270. \begin{lstlisting}
  16271. |$e_1$|[|$e_2$|]
  16272. \end{lstlisting}
  16273. \end{minipage}
  16274. &
  16275. $\Rightarrow$
  16276. &
  16277. \begin{minipage}{0.7\textwidth}
  16278. \begin{lstlisting}
  16279. Call(Name('any_tuple_load'),[|$e_1'$|, |$e_2'$|])
  16280. \end{lstlisting}
  16281. \end{minipage}
  16282. \\[2ex]\hline
  16283. %% \begin{minipage}{0.22\textwidth}
  16284. %% \begin{lstlisting}
  16285. %% |$e_2$| if |$e_1$| else |$e_3$|
  16286. %% \end{lstlisting}
  16287. %% \end{minipage}
  16288. %% &
  16289. %% $\Rightarrow$
  16290. %% &
  16291. %% \begin{minipage}{0.7\textwidth}
  16292. %% \begin{lstlisting}
  16293. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16294. %% \end{lstlisting}
  16295. %% \end{minipage}
  16296. %% \\[2ex]\hline
  16297. %% \begin{minipage}{0.22\textwidth}
  16298. %% \begin{lstlisting}
  16299. %% (eq? |$e_1$| |$e_2$|)
  16300. %% \end{lstlisting}
  16301. %% \end{minipage}
  16302. %% &
  16303. %% $\Rightarrow$
  16304. %% &
  16305. %% \begin{minipage}{0.7\textwidth}
  16306. %% \begin{lstlisting}
  16307. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16308. %% \end{lstlisting}
  16309. %% \end{minipage}
  16310. %% \\[2ex]\hline
  16311. %% \begin{minipage}{0.22\textwidth}
  16312. %% \begin{lstlisting}
  16313. %% (not |$e_1$|)
  16314. %% \end{lstlisting}
  16315. %% \end{minipage}
  16316. %% &
  16317. %% $\Rightarrow$
  16318. %% &
  16319. %% \begin{minipage}{0.7\textwidth}
  16320. %% \begin{lstlisting}
  16321. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16322. %% (inject #t Boolean) (inject #f Boolean))
  16323. %% \end{lstlisting}
  16324. %% \end{minipage}
  16325. %% \\[2ex]\hline
  16326. \end{tabular}
  16327. \fi}
  16328. \caption{Cast Insertion}
  16329. \label{fig:compile-r7-Lany}
  16330. \end{figure}
  16331. \section{Reveal Casts}
  16332. \label{sec:reveal-casts-Lany}
  16333. % TODO: define R'_6
  16334. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16335. into a conditional expression that checks whether the value's tag
  16336. matches the target type; if it does, the value is converted to a value
  16337. of the target type by removing the tag; if it does not, the program
  16338. exits.
  16339. %
  16340. {\if\edition\racketEd
  16341. %
  16342. To perform these actions we need a new primitive operation,
  16343. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16344. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16345. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16346. underlying value from a tagged value. The \code{ValueOf} form
  16347. includes the type for the underlying value which is used by the type
  16348. checker. Finally, the \code{Exit} form ends the execution of the
  16349. program.
  16350. %
  16351. \fi}
  16352. %
  16353. {\if\edition\pythonEd
  16354. %
  16355. To perform these actions we need the \code{exit} function (from the C
  16356. standard library) and two new AST classes: \code{TagOf} and
  16357. \code{ValueOf}. The \code{exit} function ends the execution of the
  16358. program. The \code{TagOf} operation retrieves the type tag from a
  16359. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16360. the underlying value from a tagged value. The \code{ValueOf}
  16361. operation includes the type for the underlying value which is used by
  16362. the type checker.
  16363. %
  16364. \fi}
  16365. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16366. \code{Project} can be translated as follows.
  16367. \begin{center}
  16368. \begin{minipage}{1.0\textwidth}
  16369. {\if\edition\racketEd
  16370. \begin{lstlisting}
  16371. (Project |$e$| |$\FType$|)
  16372. |$\Rightarrow$|
  16373. (Let |$\itm{tmp}$| |$e'$|
  16374. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16375. (Int |$\itm{tagof}(\FType)$|)))
  16376. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16377. (Exit)))
  16378. \end{lstlisting}
  16379. \fi}
  16380. {\if\edition\pythonEd
  16381. \begin{lstlisting}
  16382. Project(|$e$|, |$\FType$|)
  16383. |$\Rightarrow$|
  16384. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16385. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16386. [Constant(|$\itm{tagof}(\FType)$|)]),
  16387. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16388. Call(Name('exit'), [])))
  16389. \end{lstlisting}
  16390. \fi}
  16391. \end{minipage}
  16392. \end{center}
  16393. If the target type of the projection is a tuple or function type, then
  16394. there is a bit more work to do. For tuples, check that the length of
  16395. the tuple type matches the length of the tuple. For functions, check
  16396. that the number of parameters in the function type matches the
  16397. function's arity.
  16398. Regarding \code{Inject}, we recommend compiling it to a slightly
  16399. lower-level primitive operation named \racket{\code{make-any}}\python{\code{make\_any}}. This operation
  16400. takes a tag instead of a type.
  16401. \begin{center}
  16402. \begin{minipage}{1.0\textwidth}
  16403. {\if\edition\racketEd
  16404. \begin{lstlisting}
  16405. (Inject |$e$| |$\FType$|)
  16406. |$\Rightarrow$|
  16407. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16408. \end{lstlisting}
  16409. \fi}
  16410. {\if\edition\pythonEd
  16411. \begin{lstlisting}
  16412. Inject(|$e$|, |$\FType$|)
  16413. |$\Rightarrow$|
  16414. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16415. \end{lstlisting}
  16416. \fi}
  16417. \end{minipage}
  16418. \end{center}
  16419. {\if\edition\pythonEd
  16420. %
  16421. The introduction of \code{make\_any} makes it difficult to use
  16422. bidirectional type checking because we no longer have an expected type
  16423. to use for type checking the expression $e'$. Thus, we run into
  16424. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16425. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16426. annotated lambda) whose parameters have type annotations and that
  16427. records the return type.
  16428. %
  16429. \fi}
  16430. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16431. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16432. translation of \code{Project}.}
  16433. {\if\edition\racketEd
  16434. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16435. combine the projection action with the vector operation. Also, the
  16436. read and write operations allow arbitrary expressions for the index so
  16437. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Lany})
  16438. cannot guarantee that the index is within bounds. Thus, we insert code
  16439. to perform bounds checking at runtime. The translation for
  16440. \code{any-vector-ref} is as follows and the other two operations are
  16441. translated in a similar way.
  16442. \begin{center}
  16443. \begin{minipage}{0.95\textwidth}
  16444. \begin{lstlisting}
  16445. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16446. |$\Rightarrow$|
  16447. (Let |$v$| |$e'_1$|
  16448. (Let |$i$| |$e'_2$|
  16449. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16450. (If (Prim '< (list (Var |$i$|) (Prim 'any-vector-length (list (Var |$v$|)))))
  16451. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16452. (Exit))
  16453. (Exit))))
  16454. \end{lstlisting}
  16455. \end{minipage}
  16456. \end{center}
  16457. \fi}
  16458. %
  16459. {\if\edition\pythonEd
  16460. %
  16461. The \code{any\_tuple\_load} operation combines the projection action
  16462. with the load operation. Also, the load operation allows arbitrary
  16463. expressions for the index so the type checker for \LangAny{}
  16464. (Figure~\ref{fig:type-check-Lany}) cannot guarantee that the index is
  16465. within bounds. Thus, we insert code to perform bounds checking at
  16466. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16467. \begin{lstlisting}
  16468. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16469. |$\Rightarrow$|
  16470. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16471. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16472. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  16473. Call(Name('any_tuple_load'), [|$t$|, |$i$|]),
  16474. Call(Name('exit'), [])),
  16475. Call(Name('exit'), [])))
  16476. \end{lstlisting}
  16477. \fi}
  16478. {\if\edition\pythonEd
  16479. \section{Assignment Conversion}
  16480. \label{sec:convert-assignments-Lany}
  16481. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16482. \code{AnnLambda} AST classes.
  16483. \section{Closure Conversion}
  16484. \label{sec:closure-conversion-Lany}
  16485. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16486. \code{AnnLambda} AST classes.
  16487. \fi}
  16488. \section{Remove Complex Operands}
  16489. \label{sec:rco-Lany}
  16490. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16491. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16492. %
  16493. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16494. complex expressions. Their subexpressions must be atomic.}
  16495. \section{Explicate Control and \LangCAny{}}
  16496. \label{sec:explicate-Lany}
  16497. The output of \code{explicate\_control} is the \LangCAny{} language
  16498. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16499. %
  16500. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16501. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16502. note that the index argument of \code{vector-ref} and
  16503. \code{vector-set!} is an $\Atm$ instead of an integer, as it was in
  16504. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16505. %
  16506. \python{
  16507. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16508. and \code{explicate\_pred} as appropriately to handle the new expressions
  16509. in \LangCAny{}.
  16510. }
  16511. \newcommand{\CanyASTPython}{
  16512. \begin{array}{lcl}
  16513. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16514. &\MID& \key{TagOf}\LP \Atm \RP
  16515. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  16516. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS \Atm,\Atm \RS}\\
  16517. &\MID& \CALL{\VAR{\key{'any\_tuple\_store'}}}{\LS \Atm,\Atm,\Atm \RS}\\
  16518. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16519. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16520. \end{array}
  16521. }
  16522. \newcommand{\CanyASTRacket}{
  16523. \begin{array}{lcl}
  16524. \Exp &::= & \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16525. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16526. &\MID& \VALUEOF{\Atm}{\FType} \\
  16527. \Tail &::= & \LP\key{Exit}\RP
  16528. \end{array}
  16529. }
  16530. \begin{figure}[tp]
  16531. \fbox{
  16532. \begin{minipage}{0.96\textwidth}
  16533. \small
  16534. {\if\edition\racketEd
  16535. \[
  16536. \begin{array}{l}
  16537. \gray{\CvarASTRacket} \\ \hline
  16538. \gray{\CifASTRacket} \\ \hline
  16539. \gray{\CloopASTRacket} \\ \hline
  16540. \gray{\CtupASTRacket} \\ \hline
  16541. \gray{\CfunASTRacket} \\ \hline
  16542. \gray{\ClambdaASTRacket} \\ \hline
  16543. \CanyASTRacket \\
  16544. \begin{array}{lcl}
  16545. \LangCAnyM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  16546. \end{array}
  16547. \end{array}
  16548. \]
  16549. \fi}
  16550. {\if\edition\pythonEd
  16551. \[
  16552. \begin{array}{l}
  16553. \gray{\CifASTPython} \\ \hline
  16554. \gray{\CtupASTPython} \\ \hline
  16555. \gray{\CfunASTPython} \\ \hline
  16556. \gray{\ClambdaASTPython} \\ \hline
  16557. \CanyASTPython \\
  16558. \begin{array}{lcl}
  16559. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16560. \end{array}
  16561. \end{array}
  16562. \]
  16563. \fi}
  16564. \end{minipage}
  16565. }
  16566. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16567. \label{fig:c5-syntax}
  16568. \end{figure}
  16569. \section{Select Instructions}
  16570. \label{sec:select-Lany}
  16571. In the \code{select\_instructions} pass we translate the primitive
  16572. operations on the \ANYTY{} type to x86 instructions that manipulate
  16573. the 3 tag bits of the tagged value. In the following descriptions,
  16574. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16575. of translating $e$ into an x86 argument.
  16576. \paragraph{\racket{\code{make-any}}\python{\code{make\_any}}}
  16577. We recommend compiling the
  16578. \racket{\code{make-any}}\python{\code{make\_any}} operation as follows
  16579. if the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16580. shifts the destination to the left by the number of bits specified its
  16581. source argument (in this case $3$, the length of the tag) and it
  16582. preserves the sign of the integer. We use the \key{orq} instruction to
  16583. combine the tag and the value to form the tagged value. \\
  16584. %
  16585. {\if\edition\racketEd
  16586. \begin{lstlisting}
  16587. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16588. |$\Rightarrow$|
  16589. movq |$e'$|, |\itm{lhs'}|
  16590. salq $3, |\itm{lhs'}|
  16591. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16592. \end{lstlisting}
  16593. \fi}
  16594. %
  16595. {\if\edition\pythonEd
  16596. \begin{lstlisting}
  16597. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16598. |$\Rightarrow$|
  16599. movq |$e'$|, |\itm{lhs'}|
  16600. salq $3, |\itm{lhs'}|
  16601. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16602. \end{lstlisting}
  16603. \fi}
  16604. %
  16605. The instruction selection for tuples and procedures is different
  16606. because their is no need to shift them to the left. The rightmost 3
  16607. bits are already zeros so we simply combine the value and the tag
  16608. using \key{orq}. \\
  16609. %
  16610. {\if\edition\racketEd
  16611. \begin{center}
  16612. \begin{minipage}{\textwidth}
  16613. \begin{lstlisting}
  16614. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16615. |$\Rightarrow$|
  16616. movq |$e'$|, |\itm{lhs'}|
  16617. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16618. \end{lstlisting}
  16619. \end{minipage}
  16620. \end{center}
  16621. \fi}
  16622. %
  16623. {\if\edition\pythonEd
  16624. \begin{lstlisting}
  16625. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16626. |$\Rightarrow$|
  16627. movq |$e'$|, |\itm{lhs'}|
  16628. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16629. \end{lstlisting}
  16630. \fi}
  16631. \paragraph{\racket{\code{tag-of-any}}\python{\code{TagOf}}}
  16632. Recall that the \racket{\code{tag-of-any}}\python{\code{TagOf}}
  16633. operation extracts the type tag from a value of type \ANYTY{}. The
  16634. type tag is the bottom three bits, so we obtain the tag by taking the
  16635. bitwise-and of the value with $111$ ($7$ in decimal).
  16636. %
  16637. {\if\edition\racketEd
  16638. \begin{lstlisting}
  16639. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16640. |$\Rightarrow$|
  16641. movq |$e'$|, |\itm{lhs'}|
  16642. andq $7, |\itm{lhs'}|
  16643. \end{lstlisting}
  16644. \fi}
  16645. %
  16646. {\if\edition\pythonEd
  16647. \begin{lstlisting}
  16648. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16649. |$\Rightarrow$|
  16650. movq |$e'$|, |\itm{lhs'}|
  16651. andq $7, |\itm{lhs'}|
  16652. \end{lstlisting}
  16653. \fi}
  16654. \paragraph{\code{ValueOf}}
  16655. The instructions for \key{ValueOf} also differ depending on whether
  16656. the type $T$ is a pointer (tuple or function) or not (integer or
  16657. Boolean). The following shows the instruction selection for integers
  16658. and Booleans. We produce an untagged value by shifting it to the
  16659. right by 3 bits.
  16660. %
  16661. {\if\edition\racketEd
  16662. \begin{lstlisting}
  16663. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16664. |$\Rightarrow$|
  16665. movq |$e'$|, |\itm{lhs'}|
  16666. sarq $3, |\itm{lhs'}|
  16667. \end{lstlisting}
  16668. \fi}
  16669. %
  16670. {\if\edition\pythonEd
  16671. \begin{lstlisting}
  16672. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16673. |$\Rightarrow$|
  16674. movq |$e'$|, |\itm{lhs'}|
  16675. sarq $3, |\itm{lhs'}|
  16676. \end{lstlisting}
  16677. \fi}
  16678. %
  16679. In the case for tuples and procedures, we zero-out the rightmost 3
  16680. bits. We accomplish this by creating the bit pattern $\ldots 0111$
  16681. ($7$ in decimal) and apply bitwise-not to obtain $\ldots 11111000$ (-8
  16682. in decimal) which we \code{movq} into the destination $\itm{lhs'}$.
  16683. Finally, we apply \code{andq} with the tagged value to get the desired
  16684. result.
  16685. %
  16686. {\if\edition\racketEd
  16687. \begin{lstlisting}
  16688. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16689. |$\Rightarrow$|
  16690. movq $|$-8$|, |\itm{lhs'}|
  16691. andq |$e'$|, |\itm{lhs'}|
  16692. \end{lstlisting}
  16693. \fi}
  16694. %
  16695. {\if\edition\pythonEd
  16696. \begin{lstlisting}
  16697. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16698. |$\Rightarrow$|
  16699. movq $|$-8$|, |\itm{lhs'}|
  16700. andq |$e'$|, |\itm{lhs'}|
  16701. \end{lstlisting}
  16702. \fi}
  16703. %% \paragraph{Type Predicates} We leave it to the reader to
  16704. %% devise a sequence of instructions to implement the type predicates
  16705. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  16706. \paragraph{\racket{\code{any-vector-length}}\python{\code{any\_len}}}
  16707. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  16708. operation combines the effect of \code{ValueOf} with accessing the
  16709. length of a tuple from the tag stored at the zero index of the tuple.
  16710. {\if\edition\racketEd
  16711. \begin{lstlisting}
  16712. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  16713. |$\Longrightarrow$|
  16714. movq $|$-8$|, %r11
  16715. andq |$e_1'$|, %r11
  16716. movq 0(%r11), %r11
  16717. andq $126, %r11
  16718. sarq $1, %r11
  16719. movq %r11, |$\itm{lhs'}$|
  16720. \end{lstlisting}
  16721. \fi}
  16722. {\if\edition\pythonEd
  16723. \begin{lstlisting}
  16724. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  16725. |$\Longrightarrow$|
  16726. movq $|$-8$|, %r11
  16727. andq |$e_1'$|, %r11
  16728. movq 0(%r11), %r11
  16729. andq $126, %r11
  16730. sarq $1, %r11
  16731. movq %r11, |$\itm{lhs'}$|
  16732. \end{lstlisting}
  16733. \fi}
  16734. \paragraph{\racket{\code{any-vector-ref}}\python{\code{\code{any\_tuple\_load}}}}
  16735. This operation combines the effect of \code{ValueOf} with reading an
  16736. element of the tuple (see
  16737. Section~\ref{sec:select-instructions-gc}). However, the index may be
  16738. an arbitrary atom so instead of computing the offset at compile time,
  16739. we must generate instructions to compute the offset at runtime as
  16740. follows. Note the use of the new instruction \code{imulq}.
  16741. \begin{center}
  16742. \begin{minipage}{0.96\textwidth}
  16743. {\if\edition\racketEd
  16744. \begin{lstlisting}
  16745. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16746. |$\Longrightarrow$|
  16747. movq |$\neg 111$|, %r11
  16748. andq |$e_1'$|, %r11
  16749. movq |$e_2'$|, %rax
  16750. addq $1, %rax
  16751. imulq $8, %rax
  16752. addq %rax, %r11
  16753. movq 0(%r11) |$\itm{lhs'}$|
  16754. \end{lstlisting}
  16755. \fi}
  16756. %
  16757. {\if\edition\pythonEd
  16758. \begin{lstlisting}
  16759. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|]))
  16760. |$\Longrightarrow$|
  16761. movq $|$-8$|, %r11
  16762. andq |$e_1'$|, %r11
  16763. movq |$e_2'$|, %rax
  16764. addq $1, %rax
  16765. imulq $8, %rax
  16766. addq %rax, %r11
  16767. movq 0(%r11) |$\itm{lhs'}$|
  16768. \end{lstlisting}
  16769. \fi}
  16770. \end{minipage}
  16771. \end{center}
  16772. \paragraph{\racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}}}
  16773. The code generation for
  16774. \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  16775. analogous to the above translation for reading from a tuple.
  16776. \section{Register Allocation for \LangAny{}}
  16777. \label{sec:register-allocation-Lany}
  16778. \index{subject}{register allocation}
  16779. There is an interesting interaction between tagged values and garbage
  16780. collection that has an impact on register allocation. A variable of
  16781. type \ANYTY{} might refer to a tuple and therefore it might be a root
  16782. that needs to be inspected and copied during garbage collection. Thus,
  16783. we need to treat variables of type \ANYTY{} in a similar way to
  16784. variables of tuple type for purposes of register allocation. In
  16785. particular,
  16786. \begin{itemize}
  16787. \item If a variable of type \ANYTY{} is live during a function call,
  16788. then it must be spilled. This can be accomplished by changing
  16789. \code{build\_interference} to mark all variables of type \ANYTY{}
  16790. that are live after a \code{callq} as interfering with all the
  16791. registers.
  16792. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  16793. the root stack instead of the normal procedure call stack.
  16794. \end{itemize}
  16795. Another concern regarding the root stack is that the garbage collector
  16796. needs to differentiate between (1) plain old pointers to tuples, (2) a
  16797. tagged value that points to a tuple, and (3) a tagged value that is
  16798. not a tuple. We enable this differentiation by choosing not to use the
  16799. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  16800. reserved for identifying plain old pointers to tuples. That way, if
  16801. one of the first three bits is set, then we have a tagged value and
  16802. inspecting the tag can differentiate between tuples ($010$) and the
  16803. other kinds of values.
  16804. %% \begin{exercise}\normalfont
  16805. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  16806. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  16807. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  16808. %% compiler on these new programs and all of your previously created test
  16809. %% programs.
  16810. %% \end{exercise}
  16811. \begin{exercise}\normalfont\normalsize
  16812. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  16813. Create tests for \LangDyn{} by adapting ten of your previous test programs
  16814. by removing type annotations. Add 5 more tests programs that
  16815. specifically rely on the language being dynamically typed. That is,
  16816. they should not be legal programs in a statically typed language, but
  16817. nevertheless, they should be valid \LangDyn{} programs that run to
  16818. completion without error.
  16819. \end{exercise}
  16820. \begin{figure}[p]
  16821. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16822. \node (Lfun) at (0,4) {\large \LangDyn{}};
  16823. \node (Lfun-2) at (3,4) {\large \LangDyn{}};
  16824. \node (Lfun-3) at (6,4) {\large \LangDyn{}};
  16825. \node (Lfun-4) at (9,4) {\large \LangDynFunRef{}};
  16826. \node (Lfun-5) at (12,2) {\large \LangAnyFunRef{}};
  16827. \node (Lfun-6) at (9,2) {\large \LangAnyFunRef{}};
  16828. \node (Lfun-7) at (6,2) {\large \LangAnyFunRef{}};
  16829. \node (F1-2) at (3,2) {\large \LangAnyFunRef{}};
  16830. \node (F1-3) at (0,2) {\large \LangAnyFunRef{}};
  16831. \node (F1-4) at (0,0) {\large \LangAnyAlloc{}};
  16832. \node (F1-5) at (3,0) {\large \LangAnyAlloc{}};
  16833. \node (F1-6) at (6,0) {\large \LangAnyAlloc{}};
  16834. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  16835. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16836. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16837. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16838. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16839. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16840. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16841. \path[->,bend left=15] (Lfun) edge [above] node
  16842. {\ttfamily\footnotesize shrink} (Lfun-2);
  16843. \path[->,bend left=15] (Lfun-2) edge [above] node
  16844. {\ttfamily\footnotesize uniquify} (Lfun-3);
  16845. \path[->,bend left=15] (Lfun-3) edge [above] node
  16846. {\ttfamily\footnotesize reveal\_functions} (Lfun-4);
  16847. \path[->,bend left=15] (Lfun-4) edge [left] node
  16848. {\ttfamily\footnotesize cast\_insert} (Lfun-5);
  16849. \path[->,bend left=15] (Lfun-5) edge [below] node
  16850. {\ttfamily\footnotesize reveal\_casts} (Lfun-6);
  16851. \path[->,bend left=15] (Lfun-6) edge [below] node
  16852. {\ttfamily\footnotesize convert\_assign.} (Lfun-7);
  16853. \path[->,bend right=15] (Lfun-7) edge [above] node
  16854. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16855. \path[->,bend right=15] (F1-2) edge [above] node
  16856. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16857. \path[->,bend right=15] (F1-3) edge [right] node
  16858. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16859. \path[->,bend right=15] (F1-4) edge [below] node
  16860. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  16861. \path[->,bend left=15] (F1-5) edge [above] node
  16862. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  16863. \path[->,bend left=15] (F1-6) edge [right] node
  16864. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16865. \path[->,bend left=15] (C3-2) edge [left] node
  16866. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16867. \path[->,bend right=15] (x86-2) edge [left] node
  16868. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16869. \path[->,bend right=15] (x86-2-1) edge [below] node
  16870. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16871. \path[->,bend right=15] (x86-2-2) edge [left] node
  16872. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16873. \path[->,bend left=15] (x86-3) edge [above] node
  16874. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16875. \path[->,bend left=15] (x86-4) edge [right] node
  16876. {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  16877. \end{tikzpicture}
  16878. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  16879. \label{fig:Ldyn-passes}
  16880. \end{figure}
  16881. Figure~\ref{fig:Ldyn-passes} provides an overview of the passes needed
  16882. for the compilation of \LangDyn{}.
  16883. % Further Reading
  16884. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16885. %% {\if\edition\pythonEd
  16886. %% \chapter{Objects}
  16887. %% \label{ch:Lobject}
  16888. %% \index{subject}{objects}
  16889. %% \index{subject}{classes}
  16890. %% \fi}
  16891. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16892. \chapter{Gradual Typing}
  16893. \label{ch:Lgrad}
  16894. \index{subject}{gradual typing}
  16895. \if\edition\pythonEd
  16896. UNDER CONSTRUCTION
  16897. \fi
  16898. \if\edition\racketEd
  16899. This chapter studies a language, \LangGrad{}, in which the programmer
  16900. can choose between static and dynamic type checking in different parts
  16901. of a program, thereby mixing the statically typed \LangLam{} language
  16902. with the dynamically typed \LangDyn{}. There are several approaches to
  16903. mixing static and dynamic typing, including multi-language
  16904. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16905. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16906. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16907. programmer controls the amount of static versus dynamic checking by
  16908. adding or removing type annotations on parameters and
  16909. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16910. %
  16911. The concrete syntax of \LangGrad{} is defined in
  16912. Figure~\ref{fig:Lgrad-concrete-syntax} and its abstract syntax is defined
  16913. in Figure~\ref{fig:Lgrad-syntax}. The main syntactic difference between
  16914. \LangLam{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  16915. non-terminals that make type annotations optional. The return types
  16916. are not optional in the abstract syntax; the parser fills in
  16917. \code{Any} when the return type is not specified in the concrete
  16918. syntax.
  16919. \newcommand{\LgradGrammarRacket}{
  16920. \begin{array}{lcl}
  16921. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  16922. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16923. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16924. \Exp &::=& \LP\Exp \; \Exp \ldots\RP
  16925. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  16926. &\MID& \LP \key{procedure-arity}~\Exp\RP \\
  16927. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp}
  16928. \end{array}
  16929. }
  16930. \newcommand{\LgradASTRacket}{
  16931. \begin{array}{lcl}
  16932. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  16933. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16934. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}
  16935. \MID \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  16936. \itm{op} &::=& \code{procedure-arity} \\
  16937. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp}
  16938. \end{array}
  16939. }
  16940. \begin{figure}[tp]
  16941. \centering
  16942. \fbox{
  16943. \begin{minipage}{0.96\textwidth}
  16944. \small
  16945. \[
  16946. \begin{array}{l}
  16947. \gray{\LintGrammarRacket{}} \\ \hline
  16948. \gray{\LvarGrammarRacket{}} \\ \hline
  16949. \gray{\LifGrammarRacket{}} \\ \hline
  16950. \gray{\LwhileGrammarRacket} \\ \hline
  16951. \gray{\LtupGrammarRacket} \\ \hline
  16952. \LgradGrammarRacket \\
  16953. \begin{array}{lcl}
  16954. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  16955. \end{array}
  16956. \end{array}
  16957. \]
  16958. \end{minipage}
  16959. }
  16960. \caption{The concrete syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  16961. \label{fig:Lgrad-concrete-syntax}
  16962. \end{figure}
  16963. \begin{figure}[tp]
  16964. \centering
  16965. \fbox{
  16966. \begin{minipage}{0.96\textwidth}
  16967. \small
  16968. \[
  16969. \begin{array}{l}
  16970. \gray{\LintOpAST} \\ \hline
  16971. \gray{\LvarASTRacket{}} \\ \hline
  16972. \gray{\LifASTRacket{}} \\ \hline
  16973. \gray{\LwhileASTRacket{}} \\ \hline
  16974. \gray{\LtupASTRacket{}} \\ \hline
  16975. \LgradASTRacket \\
  16976. \begin{array}{lcl}
  16977. \LangGradM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  16978. \end{array}
  16979. \end{array}
  16980. \]
  16981. \end{minipage}
  16982. }
  16983. \caption{The abstract syntax of \LangGrad{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  16984. \label{fig:Lgrad-syntax}
  16985. \end{figure}
  16986. Both the type checker and the interpreter for \LangGrad{} require some
  16987. interesting changes to enable gradual typing, which we discuss in the
  16988. next two sections in the context of the \code{map} example from
  16989. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we revisit the
  16990. \code{map} example, omitting the type annotations from the \code{inc}
  16991. function.
  16992. \begin{figure}[btp]
  16993. % gradual_test_9.rkt
  16994. \begin{lstlisting}
  16995. (define (map [f : (Integer -> Integer)]
  16996. [v : (Vector Integer Integer)])
  16997. : (Vector Integer Integer)
  16998. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16999. (define (inc x) (+ x 1))
  17000. (vector-ref (map inc (vector 0 41)) 1)
  17001. \end{lstlisting}
  17002. \caption{A partially-typed version of the \code{map} example.}
  17003. \label{fig:gradual-map}
  17004. \end{figure}
  17005. \section{Type Checking \LangGrad{} and \LangCast{}}
  17006. \label{sec:gradual-type-check}
  17007. The type checker for \LangGrad{} uses the \code{Any} type for missing
  17008. parameter and return types. For example, the \code{x} parameter of
  17009. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  17010. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  17011. consider the \code{+} operator inside \code{inc}. It expects both
  17012. arguments to have type \code{Integer}, but its first argument \code{x}
  17013. has type \code{Any}. In a gradually typed language, such differences
  17014. are allowed so long as the types are \emph{consistent}, that is, they
  17015. are equal except in places where there is an \code{Any} type. The type
  17016. \code{Any} is consistent with every other type.
  17017. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  17018. \begin{figure}[tbp]
  17019. \begin{lstlisting}
  17020. (define/public (consistent? t1 t2)
  17021. (match* (t1 t2)
  17022. [('Integer 'Integer) #t]
  17023. [('Boolean 'Boolean) #t]
  17024. [('Void 'Void) #t]
  17025. [('Any t2) #t]
  17026. [(t1 'Any) #t]
  17027. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17028. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  17029. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17030. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  17031. (consistent? rt1 rt2))]
  17032. [(other wise) #f]))
  17033. \end{lstlisting}
  17034. \caption{The consistency predicate on types.}
  17035. \label{fig:consistent}
  17036. \end{figure}
  17037. Returning to the \code{map} example of
  17038. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  17039. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  17040. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  17041. because the two types are consistent. In particular, \code{->} is
  17042. equal to \code{->} and because \code{Any} is consistent with
  17043. \code{Integer}.
  17044. Next consider a program with an error, such as applying \code{map} to
  17045. a function that sometimes returns a Boolean, as shown in
  17046. Figure~\ref{fig:map-maybe-inc}. The type checker for \LangGrad{}
  17047. accepts this program because the type of \code{maybe-inc} is
  17048. consistent with the type of parameter \code{f} of \code{map}, that is,
  17049. \code{(Any -> Any)} is consistent with \code{(Integer ->
  17050. Integer)}. One might say that a gradual type checker is optimistic
  17051. in that it accepts programs that might execute without a runtime type
  17052. error.
  17053. %
  17054. Unfortunately, running this program with input \code{1} triggers an
  17055. error when the \code{maybe-inc} function returns \code{\#t}. The
  17056. \LangGrad{} language performs checking at runtime to ensure the
  17057. integrity of the static types, such as the \code{(Integer -> Integer)}
  17058. annotation on parameter \code{f} of \code{map}. This runtime checking
  17059. is carried out by a new \code{Cast} form that is inserted by the type
  17060. checker. Thus, the output of the type checker is a program in the
  17061. \LangCast{} language, which adds \code{Cast} and \ANYTY{} to
  17062. \LangLam{}.
  17063. %, as shown in Figure~\ref{fig:Lgrad-prime-syntax}.
  17064. %% \begin{figure}[tp]
  17065. %% \centering
  17066. %% \fbox{
  17067. %% \begin{minipage}{0.96\textwidth}
  17068. %% \small
  17069. %% \[
  17070. %% \begin{array}{lcl}
  17071. %% \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17072. %% \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17073. %% \end{array}
  17074. %% \]
  17075. %% \end{minipage}
  17076. %% }
  17077. %% \caption{The abstract syntax of \LangCast{}, extending \LangLam{} (Figure~\ref{fig:Lwhile-syntax}).}
  17078. %% \label{fig:Lgrad-prime-syntax}
  17079. %% \end{figure}
  17080. \begin{figure}[tbp]
  17081. \begin{lstlisting}
  17082. (define (map [f : (Integer -> Integer)]
  17083. [v : (Vector Integer Integer)])
  17084. : (Vector Integer Integer)
  17085. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17086. (define (inc x) (+ x 1))
  17087. (define (true) #t)
  17088. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  17089. (vector-ref (map maybe-inc (vector 0 41)) 0)
  17090. \end{lstlisting}
  17091. \caption{A variant of the \code{map} example with an error.}
  17092. \label{fig:map-maybe-inc}
  17093. \end{figure}
  17094. Figure~\ref{fig:map-cast} shows the output of the type checker for
  17095. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  17096. inserted every time the type checker sees two types that are
  17097. consistent but not equal. In the \code{inc} function, \code{x} is
  17098. cast to \code{Integer} and the result of the \code{+} is cast to
  17099. \code{Any}. In the call to \code{map}, the \code{inc} argument
  17100. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  17101. \begin{figure}[btp]
  17102. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17103. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17104. : (Vector Integer Integer)
  17105. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17106. (define (inc [x : Any]) : Any
  17107. (cast (+ (cast x Any Integer) 1) Integer Any))
  17108. (define (true) : Any (cast #t Boolean Any))
  17109. (define (maybe-inc [x : Any]) : Any
  17110. (if (eq? 0 (read)) (inc x) (true)))
  17111. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  17112. (vector 0 41)) 0)
  17113. \end{lstlisting}
  17114. \caption{Output of type checking \code{map}
  17115. and \code{maybe-inc}.}
  17116. \label{fig:map-cast}
  17117. \end{figure}
  17118. The type checker for \LangGrad{} is defined in
  17119. Figures~\ref{fig:type-check-Lgradual-1}, \ref{fig:type-check-Lgradual-2},
  17120. and \ref{fig:type-check-Lgradual-3}.
  17121. \begin{figure}[tbp]
  17122. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17123. (define type-check-gradual-class
  17124. (class type-check-Llambda-class
  17125. (super-new)
  17126. (inherit operator-types type-predicates)
  17127. (define/override (type-check-exp env)
  17128. (lambda (e)
  17129. (define recur (type-check-exp env))
  17130. (match e
  17131. [(Prim 'vector-length (list e1))
  17132. (define-values (e1^ t) (recur e1))
  17133. (match t
  17134. [`(Vector ,ts ...)
  17135. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17136. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17137. [(Prim 'vector-ref (list e1 e2))
  17138. (define-values (e1^ t1) (recur e1))
  17139. (define-values (e2^ t2) (recur e2))
  17140. (check-consistent? t2 'Integer e)
  17141. (match t1
  17142. [`(Vector ,ts ...)
  17143. (match e2^
  17144. [(Int i)
  17145. (unless (and (0 . <= . i) (i . < . (length ts)))
  17146. (error 'type-check "invalid index ~a in ~a" i e))
  17147. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17148. [else (define e1^^ (make-cast e1^ t1 'Any))
  17149. (define e2^^ (make-cast e2^ t2 'Integer))
  17150. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17151. ['Any
  17152. (define e2^^ (make-cast e2^ t2 'Integer))
  17153. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17154. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17155. [(Prim 'vector-set! (list e1 e2 e3) )
  17156. (define-values (e1^ t1) (recur e1))
  17157. (define-values (e2^ t2) (recur e2))
  17158. (define-values (e3^ t3) (recur e3))
  17159. (check-consistent? t2 'Integer e)
  17160. (match t1
  17161. [`(Vector ,ts ...)
  17162. (match e2^
  17163. [(Int i)
  17164. (unless (and (0 . <= . i) (i . < . (length ts)))
  17165. (error 'type-check "invalid index ~a in ~a" i e))
  17166. (check-consistent? (list-ref ts i) t3 e)
  17167. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17168. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17169. [else
  17170. (define e1^^ (make-cast e1^ t1 'Any))
  17171. (define e2^^ (make-cast e2^ t2 'Integer))
  17172. (define e3^^ (make-cast e3^ t3 'Any))
  17173. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17174. ['Any
  17175. (define e2^^ (make-cast e2^ t2 'Integer))
  17176. (define e3^^ (make-cast e3^ t3 'Any))
  17177. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17178. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17179. \end{lstlisting}
  17180. \caption{Type checker for the \LangGrad{} language, part 1.}
  17181. \label{fig:type-check-Lgradual-1}
  17182. \end{figure}
  17183. \begin{figure}[tbp]
  17184. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17185. [(Prim 'eq? (list e1 e2))
  17186. (define-values (e1^ t1) (recur e1))
  17187. (define-values (e2^ t2) (recur e2))
  17188. (check-consistent? t1 t2 e)
  17189. (define T (meet t1 t2))
  17190. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17191. 'Boolean)]
  17192. [(Prim 'not (list e1))
  17193. (define-values (e1^ t1) (recur e1))
  17194. (match t1
  17195. ['Any
  17196. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17197. (Bool #t) (Bool #f)))]
  17198. [else
  17199. (define-values (t-ret new-es^)
  17200. (type-check-op 'not (list t1) (list e1^) e))
  17201. (values (Prim 'not new-es^) t-ret)])]
  17202. [(Prim 'and (list e1 e2))
  17203. (recur (If e1 e2 (Bool #f)))]
  17204. [(Prim 'or (list e1 e2))
  17205. (define tmp (gensym 'tmp))
  17206. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17207. [(Prim op es)
  17208. #:when (not (set-member? explicit-prim-ops op))
  17209. (define-values (new-es ts)
  17210. (for/lists (exprs types) ([e es])
  17211. (recur e)))
  17212. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17213. (values (Prim op new-es^) t-ret)]
  17214. [(If e1 e2 e3)
  17215. (define-values (e1^ T1) (recur e1))
  17216. (define-values (e2^ T2) (recur e2))
  17217. (define-values (e3^ T3) (recur e3))
  17218. (check-consistent? T2 T3 e)
  17219. (match T1
  17220. ['Boolean
  17221. (define Tif (join T2 T3))
  17222. (values (If e1^ (make-cast e2^ T2 Tif)
  17223. (make-cast e3^ T3 Tif)) Tif)]
  17224. ['Any
  17225. (define Tif (meet T2 T3))
  17226. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17227. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17228. Tif)]
  17229. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17230. [(HasType e1 T)
  17231. (define-values (e1^ T1) (recur e1))
  17232. (check-consistent? T1 T)
  17233. (values (make-cast e1^ T1 T) T)]
  17234. [(SetBang x e1)
  17235. (define-values (e1^ T1) (recur e1))
  17236. (define varT (dict-ref env x))
  17237. (check-consistent? T1 varT e)
  17238. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17239. [(WhileLoop e1 e2)
  17240. (define-values (e1^ T1) (recur e1))
  17241. (check-consistent? T1 'Boolean e)
  17242. (define-values (e2^ T2) ((type-check-exp env) e2))
  17243. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17244. \end{lstlisting}
  17245. \caption{Type checker for the \LangGrad{} language, part 2.}
  17246. \label{fig:type-check-Lgradual-2}
  17247. \end{figure}
  17248. \begin{figure}[tbp]
  17249. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17250. [(Apply e1 e2s)
  17251. (define-values (e1^ T1) (recur e1))
  17252. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17253. (match T1
  17254. [`(,T1ps ... -> ,T1rt)
  17255. (for ([T2 T2s] [Tp T1ps])
  17256. (check-consistent? T2 Tp e))
  17257. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17258. (make-cast e2 src tgt)))
  17259. (values (Apply e1^ e2s^^) T1rt)]
  17260. [`Any
  17261. (define e1^^ (make-cast e1^ 'Any
  17262. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17263. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17264. (make-cast e2 src 'Any)))
  17265. (values (Apply e1^^ e2s^^) 'Any)]
  17266. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17267. [(Lambda params Tr e1)
  17268. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17269. (match p
  17270. [`[,x : ,T] (values x T)]
  17271. [(? symbol? x) (values x 'Any)])))
  17272. (define-values (e1^ T1)
  17273. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17274. (check-consistent? Tr T1 e)
  17275. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17276. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17277. [else ((super type-check-exp env) e)]
  17278. )))
  17279. \end{lstlisting}
  17280. \caption{Type checker for the \LangGrad{} language, part 3.}
  17281. \label{fig:type-check-Lgradual-3}
  17282. \end{figure}
  17283. \begin{figure}[tbp]
  17284. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17285. (define/public (join t1 t2)
  17286. (match* (t1 t2)
  17287. [('Integer 'Integer) 'Integer]
  17288. [('Boolean 'Boolean) 'Boolean]
  17289. [('Void 'Void) 'Void]
  17290. [('Any t2) t2]
  17291. [(t1 'Any) t1]
  17292. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17293. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17294. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17295. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17296. -> ,(join rt1 rt2))]))
  17297. (define/public (meet t1 t2)
  17298. (match* (t1 t2)
  17299. [('Integer 'Integer) 'Integer]
  17300. [('Boolean 'Boolean) 'Boolean]
  17301. [('Void 'Void) 'Void]
  17302. [('Any t2) 'Any]
  17303. [(t1 'Any) 'Any]
  17304. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17305. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17306. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17307. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17308. -> ,(meet rt1 rt2))]))
  17309. (define/public (make-cast e src tgt)
  17310. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17311. (define/public (check-consistent? t1 t2 e)
  17312. (unless (consistent? t1 t2)
  17313. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17314. (define/override (type-check-op op arg-types args e)
  17315. (match (dict-ref (operator-types) op)
  17316. [`(,param-types . ,return-type)
  17317. (for ([at arg-types] [pt param-types])
  17318. (check-consistent? at pt e))
  17319. (values return-type
  17320. (for/list ([e args] [s arg-types] [t param-types])
  17321. (make-cast e s t)))]
  17322. [else (error 'type-check-op "unrecognized ~a" op)]))
  17323. (define explicit-prim-ops
  17324. (set-union
  17325. (type-predicates)
  17326. (set 'procedure-arity 'eq?
  17327. 'vector 'vector-length 'vector-ref 'vector-set!
  17328. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17329. (define/override (fun-def-type d)
  17330. (match d
  17331. [(Def f params rt info body)
  17332. (define ps
  17333. (for/list ([p params])
  17334. (match p
  17335. [`[,x : ,T] T]
  17336. [(? symbol?) 'Any]
  17337. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17338. `(,@ps -> ,rt)]
  17339. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17340. \end{lstlisting}
  17341. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17342. \label{fig:type-check-Lgradual-aux}
  17343. \end{figure}
  17344. \clearpage
  17345. \section{Interpreting \LangCast{}}
  17346. \label{sec:interp-casts}
  17347. The runtime behavior of first-order casts is straightforward, that is,
  17348. casts involving simple types such as \code{Integer} and
  17349. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  17350. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  17351. puts the integer into a tagged value
  17352. (Figure~\ref{fig:interp-Lany}). Similarly, a cast from \code{Any} to
  17353. \code{Integer} is accomplished with the \code{Project} operator, that
  17354. is, by checking the value's tag and either retrieving the underlying
  17355. integer or signaling an error if it the tag is not the one for
  17356. integers (Figure~\ref{fig:interp-Lany-aux}).
  17357. %
  17358. Things get more interesting for higher-order casts, that is, casts
  17359. involving function or tuple types.
  17360. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  17361. Any)} to \code{(Integer -> Integer)}. When a function flows through
  17362. this cast at runtime, we can't know in general whether the function
  17363. will always return an integer.\footnote{Predicting the return value of
  17364. a function is equivalent to the halting problem, which is
  17365. undecidable.} The \LangCast{} interpreter therefore delays the checking
  17366. of the cast until the function is applied. This is accomplished by
  17367. wrapping \code{maybe-inc} in a new function that casts its parameter
  17368. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  17369. casts the return value from \code{Any} to \code{Integer}.
  17370. Turning our attention to casts involving tuple types, we consider the
  17371. example in Figure~\ref{fig:map-bang} that defines a
  17372. partially-typed version of \code{map} whose parameter \code{v} has
  17373. type \code{(Vector Any Any)} and that updates \code{v} in place
  17374. instead of returning a new tuple. So we name this function
  17375. \code{map!}. We apply \code{map!} to a tuple of integers, so
  17376. the type checker inserts a cast from \code{(Vector Integer Integer)}
  17377. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  17378. cast between tuple types would be a build a new tuple whose elements
  17379. are the result of casting each of the original elements to the
  17380. appropriate target type. However, this approach is only valid for
  17381. immutable tuples; and our tuples are mutable. In the example of
  17382. Figure~\ref{fig:map-bang}, if the cast created a new tuple, then
  17383. the updates inside of \code{map!} would happen to the new tuple
  17384. and not the original one.
  17385. \begin{figure}[tbp]
  17386. % gradual_test_11.rkt
  17387. \begin{lstlisting}
  17388. (define (map! [f : (Any -> Any)]
  17389. [v : (Vector Any Any)]) : Void
  17390. (begin
  17391. (vector-set! v 0 (f (vector-ref v 0)))
  17392. (vector-set! v 1 (f (vector-ref v 1)))))
  17393. (define (inc x) (+ x 1))
  17394. (let ([v (vector 0 41)])
  17395. (begin (map! inc v) (vector-ref v 1)))
  17396. \end{lstlisting}
  17397. \caption{An example involving casts on vectors.}
  17398. \label{fig:map-bang}
  17399. \end{figure}
  17400. Instead the interpreter needs to create a new kind of value, a
  17401. \emph{tuple proxy}, that intercepts every tuple operation. On a
  17402. read, the proxy reads from the underlying tuple and then applies a
  17403. cast to the resulting value. On a write, the proxy casts the argument
  17404. value and then performs the write to the underlying tuple. For the
  17405. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  17406. \code{0} from \code{Integer} to \code{Any}. For the first
  17407. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  17408. to \code{Integer}.
  17409. The final category of cast that we need to consider are casts between
  17410. the \code{Any} type and either a function or a tuple
  17411. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  17412. in which parameter \code{v} does not have a type annotation, so it is
  17413. given type \code{Any}. In the call to \code{map!}, the tuple has
  17414. type \code{(Vector Integer Integer)} so the type checker inserts a
  17415. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  17416. thought is to use \code{Inject}, but that doesn't work because
  17417. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  17418. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  17419. to \code{Any}.
  17420. \begin{figure}[tbp]
  17421. \begin{lstlisting}
  17422. (define (map! [f : (Any -> Any)] v) : Void
  17423. (begin
  17424. (vector-set! v 0 (f (vector-ref v 0)))
  17425. (vector-set! v 1 (f (vector-ref v 1)))))
  17426. (define (inc x) (+ x 1))
  17427. (let ([v (vector 0 41)])
  17428. (begin (map! inc v) (vector-ref v 1)))
  17429. \end{lstlisting}
  17430. \caption{Casting a tuple to \code{Any}.}
  17431. \label{fig:map-any}
  17432. \end{figure}
  17433. The \LangCast{} interpreter uses an auxiliary function named
  17434. \code{apply-cast} to cast a value from a source type to a target type,
  17435. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  17436. of the kinds of casts that we've discussed in this section.
  17437. \begin{figure}[tbp]
  17438. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17439. (define/public (apply-cast v s t)
  17440. (match* (s t)
  17441. [(t1 t2) #:when (equal? t1 t2) v]
  17442. [('Any t2)
  17443. (match t2
  17444. [`(,ts ... -> ,rt)
  17445. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17446. (define v^ (apply-project v any->any))
  17447. (apply-cast v^ any->any `(,@ts -> ,rt))]
  17448. [`(Vector ,ts ...)
  17449. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17450. (define v^ (apply-project v vec-any))
  17451. (apply-cast v^ vec-any `(Vector ,@ts))]
  17452. [else (apply-project v t2)])]
  17453. [(t1 'Any)
  17454. (match t1
  17455. [`(,ts ... -> ,rt)
  17456. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17457. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  17458. (apply-inject v^ (any-tag any->any))]
  17459. [`(Vector ,ts ...)
  17460. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17461. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  17462. (apply-inject v^ (any-tag vec-any))]
  17463. [else (apply-inject v (any-tag t1))])]
  17464. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17465. (define x (gensym 'x))
  17466. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  17467. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  17468. (define cast-writes
  17469. (for/list ([t1 ts1] [t2 ts2])
  17470. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  17471. `(vector-proxy ,(vector v (apply vector cast-reads)
  17472. (apply vector cast-writes)))]
  17473. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17474. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  17475. `(function ,xs ,(Cast
  17476. (Apply (Value v)
  17477. (for/list ([x xs][t1 ts1][t2 ts2])
  17478. (Cast (Var x) t2 t1)))
  17479. rt1 rt2) ())]
  17480. ))
  17481. \end{lstlisting}
  17482. \caption{The \code{apply-cast} auxiliary method.}
  17483. \label{fig:apply-cast}
  17484. \end{figure}
  17485. The interpreter for \LangCast{} is defined in
  17486. Figure~\ref{fig:interp-Lcast}, with the case for \code{Cast}
  17487. dispatching to \code{apply-cast}. To handle the addition of tuple
  17488. proxies, we update the tuple primitives in \code{interp-op} using the
  17489. functions in Figure~\ref{fig:guarded-tuple}.
  17490. \begin{figure}[tbp]
  17491. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17492. (define interp-Lcast-class
  17493. (class interp-Llambda-class
  17494. (super-new)
  17495. (inherit apply-fun apply-inject apply-project)
  17496. (define/override (interp-op op)
  17497. (match op
  17498. ['vector-length guarded-vector-length]
  17499. ['vector-ref guarded-vector-ref]
  17500. ['vector-set! guarded-vector-set!]
  17501. ['any-vector-ref (lambda (v i)
  17502. (match v [`(tagged ,v^ ,tg)
  17503. (guarded-vector-ref v^ i)]))]
  17504. ['any-vector-set! (lambda (v i a)
  17505. (match v [`(tagged ,v^ ,tg)
  17506. (guarded-vector-set! v^ i a)]))]
  17507. ['any-vector-length (lambda (v)
  17508. (match v [`(tagged ,v^ ,tg)
  17509. (guarded-vector-length v^)]))]
  17510. [else (super interp-op op)]
  17511. ))
  17512. (define/override ((interp-exp env) e)
  17513. (define (recur e) ((interp-exp env) e))
  17514. (match e
  17515. [(Value v) v]
  17516. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  17517. [else ((super interp-exp env) e)]))
  17518. ))
  17519. (define (interp-Lcast p)
  17520. (send (new interp-Lcast-class) interp-program p))
  17521. \end{lstlisting}
  17522. \caption{The interpreter for \LangCast{}.}
  17523. \label{fig:interp-Lcast}
  17524. \end{figure}
  17525. \begin{figure}[tbp]
  17526. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17527. (define (guarded-vector-ref vec i)
  17528. (match vec
  17529. [`(vector-proxy ,proxy)
  17530. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  17531. (define rd (vector-ref (vector-ref proxy 1) i))
  17532. (apply-fun rd (list val) 'guarded-vector-ref)]
  17533. [else (vector-ref vec i)]))
  17534. (define (guarded-vector-set! vec i arg)
  17535. (match vec
  17536. [`(vector-proxy ,proxy)
  17537. (define wr (vector-ref (vector-ref proxy 2) i))
  17538. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  17539. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  17540. [else (vector-set! vec i arg)]))
  17541. (define (guarded-vector-length vec)
  17542. (match vec
  17543. [`(vector-proxy ,proxy)
  17544. (guarded-vector-length (vector-ref proxy 0))]
  17545. [else (vector-length vec)]))
  17546. \end{lstlisting}
  17547. \caption{The \code{guarded-vector} auxiliary functions.}
  17548. \label{fig:guarded-tuple}
  17549. \end{figure}
  17550. \section{Lower Casts}
  17551. \label{sec:lower-casts}
  17552. The next step in the journey towards x86 is the \code{lower-casts}
  17553. pass that translates the casts in \LangCast{} to the lower-level
  17554. \code{Inject} and \code{Project} operators and a new operator for
  17555. creating tuple proxies, extending the \LangLam{} language to create
  17556. \LangProxy{}. We recommend creating an auxiliary function named
  17557. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  17558. and a target type, and translates it to expression in \LangProxy{} that has
  17559. the same behavior as casting the expression from the source to the
  17560. target type in the interpreter.
  17561. The \code{lower-cast} function can follow a code structure similar to
  17562. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  17563. the interpreter for \LangCast{} because it must handle the same cases as
  17564. \code{apply-cast} and it needs to mimic the behavior of
  17565. \code{apply-cast}. The most interesting cases are those concerning the
  17566. casts between two tuple types and between two function types.
  17567. As mentioned in Section~\ref{sec:interp-casts}, a cast from one tuple
  17568. type to another tuple type is accomplished by creating a proxy that
  17569. intercepts the operations on the underlying tuple. Here we make the
  17570. creation of the proxy explicit with the \code{vector-proxy} primitive
  17571. operation. It takes three arguments, the first is an expression for
  17572. the tuple, the second is a tuple of functions for casting an element
  17573. that is being read from the tuple, and the third is a tuple of
  17574. functions for casting an element that is being written to the tuple.
  17575. You can create the functions using \code{Lambda}. Also, as we shall
  17576. see in the next section, we need to differentiate these tuples from
  17577. the user-created ones, so we recommend using a new primitive operator
  17578. named \code{raw-vector} instead of \code{vector} to create these
  17579. tuples of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  17580. the output of \code{lower-casts} on the example in
  17581. Figure~\ref{fig:map-bang} that involved casting a tuple of
  17582. integers to a tuple of \code{Any}.
  17583. \begin{figure}[tbp]
  17584. \begin{lstlisting}
  17585. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  17586. (begin
  17587. (vector-set! v 0 (f (vector-ref v 0)))
  17588. (vector-set! v 1 (f (vector-ref v 1)))))
  17589. (define (inc [x : Any]) : Any
  17590. (inject (+ (project x Integer) 1) Integer))
  17591. (let ([v (vector 0 41)])
  17592. (begin
  17593. (map! inc (vector-proxy v
  17594. (raw-vector (lambda: ([x9 : Integer]) : Any
  17595. (inject x9 Integer))
  17596. (lambda: ([x9 : Integer]) : Any
  17597. (inject x9 Integer)))
  17598. (raw-vector (lambda: ([x9 : Any]) : Integer
  17599. (project x9 Integer))
  17600. (lambda: ([x9 : Any]) : Integer
  17601. (project x9 Integer)))))
  17602. (vector-ref v 1)))
  17603. \end{lstlisting}
  17604. \caption{Output of \code{lower-casts} on the example in
  17605. Figure~\ref{fig:map-bang}.}
  17606. \label{fig:map-bang-lower-cast}
  17607. \end{figure}
  17608. A cast from one function type to another function type is accomplished
  17609. by generating a \code{Lambda} whose parameter and return types match
  17610. the target function type. The body of the \code{Lambda} should cast
  17611. the parameters from the target type to the source type. (Yes,
  17612. backwards! Functions are contravariant\index{subject}{contravariant}
  17613. in the parameters.). Afterwards, call the underlying function and then
  17614. cast the result from the source return type to the target return type.
  17615. Figure~\ref{fig:map-lower-cast} shows the output of the
  17616. \code{lower-casts} pass on the \code{map} example in
  17617. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument in the
  17618. call to \code{map} is wrapped in a \code{lambda}.
  17619. \begin{figure}[tbp]
  17620. \begin{lstlisting}
  17621. (define (map [f : (Integer -> Integer)]
  17622. [v : (Vector Integer Integer)])
  17623. : (Vector Integer Integer)
  17624. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17625. (define (inc [x : Any]) : Any
  17626. (inject (+ (project x Integer) 1) Integer))
  17627. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  17628. (project (inc (inject x9 Integer)) Integer))
  17629. (vector 0 41)) 1)
  17630. \end{lstlisting}
  17631. \caption{Output of \code{lower-casts} on the example in
  17632. Figure~\ref{fig:gradual-map}.}
  17633. \label{fig:map-lower-cast}
  17634. \end{figure}
  17635. \section{Differentiate Proxies}
  17636. \label{sec:differentiate-proxies}
  17637. So far the job of differentiating tuples and tuple proxies has been
  17638. the job of the interpreter. For example, the interpreter for \LangCast{}
  17639. implements \code{vector-ref} using the \code{guarded-vector-ref}
  17640. function in Figure~\ref{fig:guarded-tuple}. In the
  17641. \code{differentiate-proxies} pass we shift this responsibility to the
  17642. generated code.
  17643. We begin by designing the output language \LangPVec. In
  17644. \LangGrad{} we used the type \code{Vector} for both real tuples and tuple
  17645. proxies. In \LangPVec we return the \code{Vector} type to
  17646. its original meaning, as the type of real tuples, and we introduce a
  17647. new type, \code{PVector}, whose values can be either real tuples or
  17648. tuple proxies. This new type comes with a suite of new primitive
  17649. operations for creating and using values of type \code{PVector}.
  17650. %We don't need to introduce a new type to represent tuple proxies.
  17651. A proxy is represented by a tuple containing three things: 1) the
  17652. underlying tuple, 2) a tuple of functions for casting elements that
  17653. are read from the tuple, and 3) a tuple of functions for casting
  17654. values to be written to the tuple. So we define the following
  17655. abbreviation for the type of a tuple proxy:
  17656. \[
  17657. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  17658. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  17659. \to (\key{PVector}~ T' \ldots)
  17660. \]
  17661. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  17662. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  17663. %
  17664. Next we describe each of the new primitive operations.
  17665. \begin{description}
  17666. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  17667. (\key{PVector} $T \ldots$)]\ \\
  17668. %
  17669. This operation brands a vector as a value of the \code{PVector} type.
  17670. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  17671. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  17672. %
  17673. This operation brands a vector proxy as value of the \code{PVector} type.
  17674. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  17675. \code{Boolean}] \ \\
  17676. %
  17677. This returns true if the value is a tuple proxy and false if it is a
  17678. real tuple.
  17679. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  17680. (\key{Vector} $T \ldots$)]\ \\
  17681. %
  17682. Assuming that the input is a tuple, this operation returns the
  17683. tuple.
  17684. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  17685. $\to$ \code{Boolean}]\ \\
  17686. %
  17687. Given a tuple proxy, this operation returns the length of the tuple.
  17688. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  17689. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  17690. %
  17691. Given a tuple proxy, this operation returns the $i$th element of the
  17692. tuple.
  17693. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  17694. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\
  17695. Given a tuple proxy, this operation writes a value to the $i$th element
  17696. of the tuple.
  17697. \end{description}
  17698. Now to discuss the translation that differentiates tuples from
  17699. proxies. First, every type annotation in the program is translated
  17700. (recursively) to replace \code{Vector} with \code{PVector}. Next, we
  17701. insert uses of \code{PVector} operations in the appropriate
  17702. places. For example, we wrap every tuple creation with an
  17703. \code{inject-vector}.
  17704. \begin{lstlisting}
  17705. (vector |$e_1 \ldots e_n$|)
  17706. |$\Rightarrow$|
  17707. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  17708. \end{lstlisting}
  17709. The \code{raw-vector} operator that we introduced in the previous
  17710. section does not get injected.
  17711. \begin{lstlisting}
  17712. (raw-vector |$e_1 \ldots e_n$|)
  17713. |$\Rightarrow$|
  17714. (vector |$e'_1 \ldots e'_n$|)
  17715. \end{lstlisting}
  17716. The \code{vector-proxy} primitive translates as follows.
  17717. \begin{lstlisting}
  17718. (vector-proxy |$e_1~e_2~e_3$|)
  17719. |$\Rightarrow$|
  17720. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  17721. \end{lstlisting}
  17722. We translate the tuple operations into conditional expressions that
  17723. check whether the value is a proxy and then dispatch to either the
  17724. appropriate proxy tuple operation or the regular tuple operation.
  17725. For example, the following is the translation for \code{vector-ref}.
  17726. \begin{lstlisting}
  17727. (vector-ref |$e_1$| |$i$|)
  17728. |$\Rightarrow$|
  17729. (let ([|$v~e_1$|])
  17730. (if (proxy? |$v$|)
  17731. (proxy-vector-ref |$v$| |$i$|)
  17732. (vector-ref (project-vector |$v$|) |$i$|)
  17733. \end{lstlisting}
  17734. Note in the case of a real tuple, we must apply \code{project-vector}
  17735. before the \code{vector-ref}.
  17736. \section{Reveal Casts}
  17737. \label{sec:reveal-casts-gradual}
  17738. Recall that the \code{reveal-casts} pass
  17739. (Section~\ref{sec:reveal-casts-Lany}) is responsible for lowering
  17740. \code{Inject} and \code{Project} into lower-level operations. In
  17741. particular, \code{Project} turns into a conditional expression that
  17742. inspects the tag and retrieves the underlying value. Here we need to
  17743. augment the translation of \code{Project} to handle the situation when
  17744. the target type is \code{PVector}. Instead of using
  17745. \code{vector-length} we need to use \code{proxy-vector-length}.
  17746. \begin{lstlisting}
  17747. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  17748. |$\Rightarrow$|
  17749. (let |$\itm{tmp}$| |$e'$|
  17750. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  17751. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  17752. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  17753. (exit)))
  17754. \end{lstlisting}
  17755. \section{Closure Conversion}
  17756. \label{sec:closure-conversion-gradual}
  17757. The closure conversion pass only requires one minor adjustment. The
  17758. auxiliary function that translates type annotations needs to be
  17759. updated to handle the \code{PVector} type.
  17760. \section{Explicate Control}
  17761. \label{sec:explicate-control-gradual}
  17762. Update the \code{explicate\_control} pass to handle the new primitive
  17763. operations on the \code{PVector} type.
  17764. \section{Select Instructions}
  17765. \label{sec:select-instructions-gradual}
  17766. Recall that the \code{select\_instructions} pass is responsible for
  17767. lowering the primitive operations into x86 instructions. So we need
  17768. to translate the new \code{PVector} operations to x86. To do so, the
  17769. first question we need to answer is how to differentiate the two
  17770. kinds of values (tuples and proxies) that can inhabit \code{PVector}.
  17771. We need just one bit to accomplish this, and use the bit in position
  17772. $57$ of the 64-bit tag at the front of every tuple (see
  17773. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  17774. for \code{inject-vector} we leave it that way.
  17775. \begin{lstlisting}
  17776. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  17777. |$\Rightarrow$|
  17778. movq |$e'_1$|, |$\itm{lhs'}$|
  17779. \end{lstlisting}
  17780. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  17781. \begin{lstlisting}
  17782. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  17783. |$\Rightarrow$|
  17784. movq |$e'_1$|, %r11
  17785. movq |$(1 << 57)$|, %rax
  17786. orq 0(%r11), %rax
  17787. movq %rax, 0(%r11)
  17788. movq %r11, |$\itm{lhs'}$|
  17789. \end{lstlisting}
  17790. The \code{proxy?} operation consumes the information so carefully
  17791. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  17792. isolates the $57$th bit to tell whether the value is a real tuple or
  17793. a proxy.
  17794. \begin{lstlisting}
  17795. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  17796. |$\Rightarrow$|
  17797. movq |$e_1'$|, %r11
  17798. movq 0(%r11), %rax
  17799. sarq $57, %rax
  17800. andq $1, %rax
  17801. movq %rax, |$\itm{lhs'}$|
  17802. \end{lstlisting}
  17803. The \code{project-vector} operation is straightforward to translate,
  17804. so we leave it up to the reader.
  17805. Regarding the \code{proxy-vector} operations, the runtime provides
  17806. procedures that implement them (they are recursive functions!) so
  17807. here we simply need to translate these tuple operations into the
  17808. appropriate function call. For example, here is the translation for
  17809. \code{proxy-vector-ref}.
  17810. \begin{lstlisting}
  17811. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  17812. |$\Rightarrow$|
  17813. movq |$e_1'$|, %rdi
  17814. movq |$e_2'$|, %rsi
  17815. callq proxy_vector_ref
  17816. movq %rax, |$\itm{lhs'}$|
  17817. \end{lstlisting}
  17818. We have another batch of tuple operations to deal with, those for the
  17819. \code{Any} type. Recall that the type checker for \LangGrad{}
  17820. generates an \code{any-vector-ref} when there is a \code{vector-ref}
  17821. on something of type \code{Any}, and similarly for
  17822. \code{any-vector-set!} and \code{any-vector-length}
  17823. (Figure~\ref{fig:type-check-Lgradual-1}). In
  17824. Section~\ref{sec:select-Lany} we selected instructions for these
  17825. operations based on the idea that the underlying value was a real
  17826. tuple. But in the current setting, the underlying value is of type
  17827. \code{PVector}. So \code{any-vector-ref} can be translated follows. We
  17828. begin by projecting the underlying value out of the tagged value and
  17829. then call the \code{proxy\_vector\_ref} procedure in the runtime.
  17830. \begin{lstlisting}
  17831. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17832. movq |$\neg 111$|, %rdi
  17833. andq |$e_1'$|, %rdi
  17834. movq |$e_2'$|, %rsi
  17835. callq proxy_vector_ref
  17836. movq %rax, |$\itm{lhs'}$|
  17837. \end{lstlisting}
  17838. The \code{any-vector-set!} and \code{any-vector-length} operators can
  17839. be translated in a similar way.
  17840. \begin{exercise}\normalfont\normalsize
  17841. Implement a compiler for the gradually-typed \LangGrad{} language by
  17842. extending and adapting your compiler for \LangLam{}. Create 10 new
  17843. partially-typed test programs. In addition to testing with these
  17844. new programs, also test your compiler on all the tests for \LangLam{}
  17845. and tests for \LangDyn{}. Sometimes you may get a type checking error
  17846. on the \LangDyn{} programs but you can adapt them by inserting
  17847. a cast to the \code{Any} type around each subexpression
  17848. causing a type error. While \LangDyn{} does not have explicit casts,
  17849. you can induce one by wrapping the subexpression \code{e}
  17850. with a call to an un-annotated identity function, like this:
  17851. \code{((lambda (x) x) e)}.
  17852. \end{exercise}
  17853. \begin{figure}[p]
  17854. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17855. \node (Lgradual) at (9,4) {\large \LangGrad{}};
  17856. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  17857. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  17858. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  17859. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  17860. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  17861. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  17862. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  17863. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  17864. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  17865. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  17866. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  17867. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  17868. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  17869. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17870. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17871. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17872. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17873. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17874. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17875. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17876. \path[->,bend right=15] (Lgradual) edge [above] node
  17877. {\ttfamily\footnotesize type\_check} (Lgradualp);
  17878. \path[->,bend right=15] (Lgradualp) edge [above] node
  17879. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  17880. \path[->,bend right=15] (Llambdapp) edge [above] node
  17881. {\ttfamily\footnotesize differentiate.} (Llambdaproxy);
  17882. \path[->,bend left=15] (Llambdaproxy) edge [right] node
  17883. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  17884. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  17885. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  17886. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  17887. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  17888. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  17889. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  17890. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  17891. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17892. \path[->,bend left=15] (F1-1) edge [left] node
  17893. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17894. \path[->,bend left=15] (F1-2) edge [below] node
  17895. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17896. \path[->,bend right=15] (F1-3) edge [above] node
  17897. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17898. \path[->,bend right=15] (F1-4) edge [above] node
  17899. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  17900. \path[->,bend right=15] (F1-5) edge [above] node
  17901. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  17902. \path[->,bend right=15] (F1-6) edge [right] node
  17903. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17904. \path[->,bend left=15] (C3-2) edge [left] node
  17905. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17906. \path[->,bend right=15] (x86-2) edge [left] node
  17907. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17908. \path[->,bend right=15] (x86-2-1) edge [below] node
  17909. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17910. \path[->,bend right=15] (x86-2-2) edge [left] node
  17911. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17912. \path[->,bend left=15] (x86-3) edge [above] node
  17913. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17914. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  17915. \end{tikzpicture}
  17916. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  17917. \label{fig:Lgradual-passes}
  17918. \end{figure}
  17919. Figure~\ref{fig:Lgradual-passes} provides an overview of the passes
  17920. needed for the compilation of \LangGrad{}.
  17921. \section{Further Reading}
  17922. This chapter just scratches the surface of gradual typing. The basic
  17923. approach described here is missing two key ingredients that one would
  17924. want in a implementation of gradual typing: blame
  17925. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  17926. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  17927. problem addressed by blame tracking is that when a cast on a
  17928. higher-order value fails, it often does so at a point in the program
  17929. that is far removed from the original cast. Blame tracking is a
  17930. technique for propagating extra information through casts and proxies
  17931. so that when a cast fails, the error message can point back to the
  17932. original location of the cast in the source program.
  17933. The problem addressed by space-efficient casts also relates to
  17934. higher-order casts. It turns out that in partially typed programs, a
  17935. function or tuple can flow through very-many casts at runtime. With
  17936. the approach described in this chapter, each cast adds another
  17937. \code{lambda} wrapper or a tuple proxy. Not only does this take up
  17938. considerable space, but it also makes the function calls and tuple
  17939. operations slow. For example, a partially-typed version of quicksort
  17940. could, in the worst case, build a chain of proxies of length $O(n)$
  17941. around the tuple, changing the overall time complexity of the
  17942. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  17943. solution to this problem by representing casts using the coercion
  17944. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  17945. long chains of proxies by compressing them into a concise normal
  17946. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  17947. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  17948. the Grift compiler.
  17949. \begin{center}
  17950. \url{https://github.com/Gradual-Typing/Grift}
  17951. \end{center}
  17952. There are also interesting interactions between gradual typing and
  17953. other language features, such as parametetric polymorphism,
  17954. information-flow types, and type inference, to name a few. We
  17955. recommend the reader to the online gradual typing bibliography:
  17956. \begin{center}
  17957. \url{http://samth.github.io/gradual-typing-bib/}
  17958. \end{center}
  17959. % TODO: challenge problem:
  17960. % type analysis and type specialization?
  17961. % coercions?
  17962. \fi
  17963. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17964. \chapter{Parametric Polymorphism}
  17965. \label{ch:Lpoly}
  17966. \index{subject}{parametric polymorphism}
  17967. \index{subject}{generics}
  17968. \if\edition\pythonEd
  17969. UNDER CONSTRUCTION
  17970. \fi
  17971. \if\edition\racketEd
  17972. This chapter studies the compilation of parametric
  17973. polymorphism\index{subject}{parametric polymorphism}
  17974. (aka. generics\index{subject}{generics}), compiling the \LangPoly{}
  17975. subset of Typed Racket. Parametric polymorphism enables programmers to
  17976. make code more reusable by parameterizing functions and data
  17977. structures with respect to the types that they operate on. For
  17978. example, Figure~\ref{fig:map-poly} revisits the \code{map} example but
  17979. this time gives it a more fitting type. This \code{map} function is
  17980. parameterized with respect to the element type of the tuple. The type
  17981. of \code{map} is the following polymorphic type as specified by the
  17982. \code{All} and the type parameter \code{a}.
  17983. \begin{lstlisting}
  17984. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17985. \end{lstlisting}
  17986. The idea is that \code{map} can be used at \emph{all} choices of a
  17987. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  17988. \code{map} to a tuple of integers, a choice of \code{Integer} for
  17989. \code{a}, but we could have just as well applied \code{map} to a tuple
  17990. of Booleans.
  17991. \begin{figure}[tbp]
  17992. % poly_test_2.rkt
  17993. \begin{lstlisting}
  17994. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  17995. (define (map f v)
  17996. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17997. (define (inc [x : Integer]) : Integer (+ x 1))
  17998. (vector-ref (map inc (vector 0 41)) 1)
  17999. \end{lstlisting}
  18000. \caption{The \code{map} example using parametric polymorphism.}
  18001. \label{fig:map-poly}
  18002. \end{figure}
  18003. Figure~\ref{fig:Lpoly-concrete-syntax} defines the concrete syntax of
  18004. \LangPoly{} and Figure~\ref{fig:Lpoly-syntax} defines the abstract
  18005. syntax. We add a second form for function definitions in which a type
  18006. declaration comes before the \code{define}. In the abstract syntax,
  18007. the return type in the \code{Def} is \code{Any}, but that should be
  18008. ignored in favor of the return type in the type declaration. (The
  18009. \code{Any} comes from using the same parser as in
  18010. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  18011. enables the use of an \code{All} type for a function, thereby making
  18012. it polymorphic. The grammar for types is extended to include
  18013. polymorphic types and type variables.
  18014. \newcommand{\LpolyGrammarRacket}{
  18015. \begin{array}{lcl}
  18016. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18017. \Def &::=& \LP\key{:}~\Var~\Type\RP \\
  18018. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP
  18019. \end{array}
  18020. }
  18021. \newcommand{\LpolyASTRacket}{
  18022. \begin{array}{lcl}
  18023. \Type &::=& \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18024. \Def &::=& \DECL{\Var}{\Type} \\
  18025. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp}
  18026. \end{array}
  18027. }
  18028. \begin{figure}[tp]
  18029. \centering
  18030. \fbox{
  18031. \begin{minipage}{0.96\textwidth}
  18032. \footnotesize
  18033. \[
  18034. \begin{array}{l}
  18035. \gray{\LintGrammarRacket{}} \\ \hline
  18036. \gray{\LvarGrammarRacket{}} \\ \hline
  18037. \gray{\LifGrammarRacket{}} \\ \hline
  18038. \gray{\LwhileGrammarRacket} \\ \hline
  18039. \gray{\LtupGrammarRacket} \\ \hline
  18040. \gray{\LfunGrammarRacket} \\ \hline
  18041. \gray{\LlambdaGrammarRacket} \\ \hline
  18042. \LpolyGrammarRacket \\
  18043. \begin{array}{lcl}
  18044. \LangPoly{} &::=& \Def \ldots ~ \Exp
  18045. \end{array}
  18046. \end{array}
  18047. \]
  18048. \end{minipage}
  18049. }
  18050. \caption{The concrete syntax of \LangPoly{}, extending \LangLam{}
  18051. (Figure~\ref{fig:Llam-concrete-syntax}).}
  18052. \label{fig:Lpoly-concrete-syntax}
  18053. \end{figure}
  18054. \begin{figure}[tp]
  18055. \centering
  18056. \fbox{
  18057. \begin{minipage}{0.96\textwidth}
  18058. \footnotesize
  18059. \[
  18060. \begin{array}{l}
  18061. \gray{\LintOpAST} \\ \hline
  18062. \gray{\LvarASTRacket{}} \\ \hline
  18063. \gray{\LifASTRacket{}} \\ \hline
  18064. \gray{\LwhileASTRacket{}} \\ \hline
  18065. \gray{\LtupASTRacket{}} \\ \hline
  18066. \gray{\LfunASTRacket} \\ \hline
  18067. \gray{\LlambdaASTRacket} \\ \hline
  18068. \LpolyASTRacket \\
  18069. \begin{array}{lcl}
  18070. \LangPoly{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18071. \end{array}
  18072. \end{array}
  18073. \]
  18074. \end{minipage}
  18075. }
  18076. \caption{The abstract syntax of \LangPoly{}, extending \LangLam{}
  18077. (Figure~\ref{fig:Llam-syntax}).}
  18078. \label{fig:Lpoly-syntax}
  18079. \end{figure}
  18080. By including polymorphic types in the $\Type$ non-terminal we choose
  18081. to make them first-class which has interesting repercussions on the
  18082. compiler. Many languages with polymorphism, such as
  18083. C++~\citep{stroustrup88:_param_types} and Standard
  18084. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  18085. it may be helpful to see an example of first-class polymorphism in
  18086. action. In Figure~\ref{fig:apply-twice} we define a function
  18087. \code{apply-twice} whose parameter is a polymorphic function. The
  18088. occurrence of a polymorphic type underneath a function type is enabled
  18089. by the normal recursive structure of the grammar for $\Type$ and the
  18090. categorization of the \code{All} type as a $\Type$. The body of
  18091. \code{apply-twice} applies the polymorphic function to a Boolean and
  18092. to an integer.
  18093. \begin{figure}[tbp]
  18094. \begin{lstlisting}
  18095. (: apply-twice ((All (b) (b -> b)) -> Integer))
  18096. (define (apply-twice f)
  18097. (if (f #t) (f 42) (f 777)))
  18098. (: id (All (a) (a -> a)))
  18099. (define (id x) x)
  18100. (apply-twice id)
  18101. \end{lstlisting}
  18102. \caption{An example illustrating first-class polymorphism.}
  18103. \label{fig:apply-twice}
  18104. \end{figure}
  18105. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  18106. three new responsibilities (compared to \LangLam{}). The type checking of
  18107. function application is extended to handle the case where the operator
  18108. expression is a polymorphic function. In that case the type arguments
  18109. are deduced by matching the type of the parameters with the types of
  18110. the arguments.
  18111. %
  18112. The \code{match-types} auxiliary function carries out this deduction
  18113. by recursively descending through a parameter type \code{pt} and the
  18114. corresponding argument type \code{at}, making sure that they are equal
  18115. except when there is a type parameter on the left (in the parameter
  18116. type). If it is the first time that the type parameter has been
  18117. encountered, then the algorithm deduces an association of the type
  18118. parameter to the corresponding type on the right (in the argument
  18119. type). If it is not the first time that the type parameter has been
  18120. encountered, the algorithm looks up its deduced type and makes sure
  18121. that it is equal to the type on the right.
  18122. %
  18123. Once the type arguments are deduced, the operator expression is
  18124. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18125. type of the operator, but more importantly, records the deduced type
  18126. arguments. The return type of the application is the return type of
  18127. the polymorphic function, but with the type parameters replaced by the
  18128. deduced type arguments, using the \code{subst-type} function.
  18129. The second responsibility of the type checker to extend the
  18130. \code{type-equal?} function to handle the \code{All} type. This is
  18131. not quite as simple as for other types, such as function and tuple
  18132. types, because two polymorphic types can be syntactically different
  18133. even though they are equivalent types. For example, \code{(All (a) (a
  18134. -> a))} is equivalent to \code{(All (b) (b -> b))}. Two polymorphic
  18135. types should be considered equal if they differ only in the choice of
  18136. the names of the type parameters. The \code{type-equal?} function in
  18137. Figure~\ref{fig:type-check-Lvar0-aux} renames the type parameters of
  18138. the first type to match the type parameters of the second type.
  18139. The third responsibility of the type checker is to make sure that only
  18140. defined type variables appear in type annotations. The
  18141. \code{check-well-formed} function defined in
  18142. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18143. sure that each type variable has been defined.
  18144. The output language of the type checker is \LangInst{}, defined in
  18145. Figure~\ref{fig:Lpoly-prime-syntax}. The type checker combines the type
  18146. declaration and polymorphic function into a single definition, using
  18147. the \code{Poly} form, to make polymorphic functions more convenient to
  18148. process in next pass of the compiler.
  18149. \begin{figure}[tp]
  18150. \centering
  18151. \fbox{
  18152. \begin{minipage}{0.96\textwidth}
  18153. \small
  18154. \[
  18155. \begin{array}{lcl}
  18156. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18157. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18158. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18159. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18160. \LangInst{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  18161. \end{array}
  18162. \]
  18163. \end{minipage}
  18164. }
  18165. \caption{The abstract syntax of \LangInst{}, extending \LangLam{}
  18166. (Figure~\ref{fig:Llam-syntax}).}
  18167. \label{fig:Lpoly-prime-syntax}
  18168. \end{figure}
  18169. The output of the type checker on the polymorphic \code{map}
  18170. example is listed in Figure~\ref{fig:map-type-check}.
  18171. \begin{figure}[tbp]
  18172. % poly_test_2.rkt
  18173. \begin{lstlisting}
  18174. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18175. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18176. (define (inc [x : Integer]) : Integer (+ x 1))
  18177. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18178. (Integer))
  18179. inc (vector 0 41)) 1)
  18180. \end{lstlisting}
  18181. \caption{Output of the type checker on the \code{map} example.}
  18182. \label{fig:map-type-check}
  18183. \end{figure}
  18184. \begin{figure}[tbp]
  18185. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18186. (define type-check-poly-class
  18187. (class type-check-Llambda-class
  18188. (super-new)
  18189. (inherit check-type-equal?)
  18190. (define/override (type-check-apply env e1 es)
  18191. (define-values (e^ ty) ((type-check-exp env) e1))
  18192. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18193. ((type-check-exp env) e)))
  18194. (match ty
  18195. [`(,ty^* ... -> ,rt)
  18196. (for ([arg-ty ty*] [param-ty ty^*])
  18197. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18198. (values e^ es^ rt)]
  18199. [`(All ,xs (,tys ... -> ,rt))
  18200. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18201. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18202. (match-types env^^ param-ty arg-ty)))
  18203. (define targs
  18204. (for/list ([x xs])
  18205. (match (dict-ref env^^ x (lambda () #f))
  18206. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18207. x (Apply e1 es))]
  18208. [ty ty])))
  18209. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18210. [else (error 'type-check "expected a function, not ~a" ty)]))
  18211. (define/override ((type-check-exp env) e)
  18212. (match e
  18213. [(Lambda `([,xs : ,Ts] ...) rT body)
  18214. (for ([T Ts]) ((check-well-formed env) T))
  18215. ((check-well-formed env) rT)
  18216. ((super type-check-exp env) e)]
  18217. [(HasType e1 ty)
  18218. ((check-well-formed env) ty)
  18219. ((super type-check-exp env) e)]
  18220. [else ((super type-check-exp env) e)]))
  18221. (define/override ((type-check-def env) d)
  18222. (verbose 'type-check "poly/def" d)
  18223. (match d
  18224. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18225. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18226. (for ([p ps]) ((check-well-formed ts-env) p))
  18227. ((check-well-formed ts-env) rt)
  18228. (define new-env (append ts-env (map cons xs ps) env))
  18229. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18230. (check-type-equal? ty^ rt body)
  18231. (Generic ts (Def f p:t* rt info body^))]
  18232. [else ((super type-check-def env) d)]))
  18233. (define/override (type-check-program p)
  18234. (match p
  18235. [(Program info body)
  18236. (type-check-program (ProgramDefsExp info '() body))]
  18237. [(ProgramDefsExp info ds body)
  18238. (define ds^ (combine-decls-defs ds))
  18239. (define new-env (for/list ([d ds^])
  18240. (cons (def-name d) (fun-def-type d))))
  18241. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18242. (define-values (body^ ty) ((type-check-exp new-env) body))
  18243. (check-type-equal? ty 'Integer body)
  18244. (ProgramDefsExp info ds^^ body^)]))
  18245. ))
  18246. \end{lstlisting}
  18247. \caption{Type checker for the \LangPoly{} language.}
  18248. \label{fig:type-check-Lvar0}
  18249. \end{figure}
  18250. \begin{figure}[tbp]
  18251. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18252. (define/override (type-equal? t1 t2)
  18253. (match* (t1 t2)
  18254. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18255. (define env (map cons xs ys))
  18256. (type-equal? (subst-type env T1) T2)]
  18257. [(other wise)
  18258. (super type-equal? t1 t2)]))
  18259. (define/public (match-types env pt at)
  18260. (match* (pt at)
  18261. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18262. [('Void 'Void) env] [('Any 'Any) env]
  18263. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18264. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18265. (match-types env^ pt1 at1))]
  18266. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18267. (define env^ (match-types env prt art))
  18268. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18269. (match-types env^^ pt1 at1))]
  18270. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18271. (define env^ (append (map cons pxs axs) env))
  18272. (match-types env^ pt1 at1)]
  18273. [((? symbol? x) at)
  18274. (match (dict-ref env x (lambda () #f))
  18275. [#f (error 'type-check "undefined type variable ~a" x)]
  18276. ['Type (cons (cons x at) env)]
  18277. [t^ (check-type-equal? at t^ 'matching) env])]
  18278. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18279. (define/public (subst-type env pt)
  18280. (match pt
  18281. ['Integer 'Integer] ['Boolean 'Boolean]
  18282. ['Void 'Void] ['Any 'Any]
  18283. [`(Vector ,ts ...)
  18284. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18285. [`(,ts ... -> ,rt)
  18286. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18287. [`(All ,xs ,t)
  18288. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18289. [(? symbol? x) (dict-ref env x)]
  18290. [else (error 'type-check "expected a type not ~a" pt)]))
  18291. (define/public (combine-decls-defs ds)
  18292. (match ds
  18293. ['() '()]
  18294. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  18295. (unless (equal? name f)
  18296. (error 'type-check "name mismatch, ~a != ~a" name f))
  18297. (match type
  18298. [`(All ,xs (,ps ... -> ,rt))
  18299. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18300. (cons (Generic xs (Def name params^ rt info body))
  18301. (combine-decls-defs ds^))]
  18302. [`(,ps ... -> ,rt)
  18303. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18304. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  18305. [else (error 'type-check "expected a function type, not ~a" type) ])]
  18306. [`(,(Def f params rt info body) . ,ds^)
  18307. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  18308. \end{lstlisting}
  18309. \caption{Auxiliary functions for type checking \LangPoly{}.}
  18310. \label{fig:type-check-Lvar0-aux}
  18311. \end{figure}
  18312. \begin{figure}[tbp]
  18313. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  18314. (define/public ((check-well-formed env) ty)
  18315. (match ty
  18316. ['Integer (void)]
  18317. ['Boolean (void)]
  18318. ['Void (void)]
  18319. [(? symbol? a)
  18320. (match (dict-ref env a (lambda () #f))
  18321. ['Type (void)]
  18322. [else (error 'type-check "undefined type variable ~a" a)])]
  18323. [`(Vector ,ts ...)
  18324. (for ([t ts]) ((check-well-formed env) t))]
  18325. [`(,ts ... -> ,t)
  18326. (for ([t ts]) ((check-well-formed env) t))
  18327. ((check-well-formed env) t)]
  18328. [`(All ,xs ,t)
  18329. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18330. ((check-well-formed env^) t)]
  18331. [else (error 'type-check "unrecognized type ~a" ty)]))
  18332. \end{lstlisting}
  18333. \caption{Well-formed types.}
  18334. \label{fig:well-formed-types}
  18335. \end{figure}
  18336. % TODO: interpreter for R'_10
  18337. \clearpage
  18338. \section{Compiling Polymorphism}
  18339. \label{sec:compiling-poly}
  18340. Broadly speaking, there are four approaches to compiling parametric
  18341. polymorphism, which we describe below.
  18342. \begin{description}
  18343. \item[Monomorphization] generates a different version of a polymorphic
  18344. function for each set of type arguments that it is used with,
  18345. producing type-specialized code. This approach results in the most
  18346. efficient code but requires whole-program compilation (no separate
  18347. compilation) and increases code size. For our current purposes
  18348. monomorphization is a non-starter because, with first-class
  18349. polymorphism, it is sometimes not possible to determine which
  18350. generic functions are used with which type arguments during
  18351. compilation. (It can be done at runtime, with just-in-time
  18352. compilation.) Monomorphization is used to compile C++
  18353. templates~\citep{stroustrup88:_param_types} and polymorphic
  18354. functions in NESL~\citep{Blelloch:1993aa} and
  18355. ML~\citep{Weeks:2006aa}.
  18356. \item[Uniform representation] generates one version of each
  18357. polymorphic function but requires all values to have a common
  18358. ``boxed'' format, such as the tagged values of type \code{Any} in
  18359. \LangAny{}. Both polymorphic and non-polymorphic (i.e. monomorphic)
  18360. code is compiled similarly to code in a dynamically typed language
  18361. (like \LangDyn{}), in which primitive operators require their
  18362. arguments to be projected from \code{Any} and their results are
  18363. injected into \code{Any}. (In object-oriented languages, the
  18364. projection is accomplished via virtual method dispatch.) The uniform
  18365. representation approach is compatible with separate compilation and
  18366. with first-class polymorphism. However, it produces the
  18367. least-efficient code because it introduces overhead in the entire
  18368. program. This approach is used in implementations of
  18369. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  18370. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  18371. Java~\citep{Bracha:1998fk}.
  18372. \item[Mixed representation] generates one version of each polymorphic
  18373. function, using a boxed representation for type
  18374. variables. Monomorphic code is compiled as usual (as in \LangLam{})
  18375. and conversions are performed at the boundaries between monomorphic
  18376. and polymorphic (e.g. when a polymorphic function is instantiated
  18377. and called). This approach is compatible with separate compilation
  18378. and first-class polymorphism and maintains efficiency in monomorphic
  18379. code. The trade off is increased overhead at the boundary between
  18380. monomorphic and polymorphic code. This approach is used in
  18381. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  18382. Java 5 with the addition of autoboxing.
  18383. \item[Type passing] uses the unboxed representation in both
  18384. monomorphic and polymorphic code. Each polymorphic function is
  18385. compiled to a single function with extra parameters that describe
  18386. the type arguments. The type information is used by the generated
  18387. code to know how to access the unboxed values at runtime. This
  18388. approach is used in implementation of the Napier88
  18389. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  18390. passing is compatible with separate compilation and first-class
  18391. polymorphism and maintains the efficiency for monomorphic
  18392. code. There is runtime overhead in polymorphic code from dispatching
  18393. on type information.
  18394. \end{description}
  18395. In this chapter we use the mixed representation approach, partly
  18396. because of its favorable attributes, and partly because it is
  18397. straightforward to implement using the tools that we have already
  18398. built to support gradual typing. To compile polymorphic functions, we
  18399. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  18400. \LangCast{}.
  18401. \section{Erase Types}
  18402. \label{sec:erase-types}
  18403. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  18404. represent type variables. For example, Figure~\ref{fig:map-erase}
  18405. shows the output of the \code{erase-types} pass on the polymorphic
  18406. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  18407. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  18408. \code{All} types are removed from the type of \code{map}.
  18409. \begin{figure}[tbp]
  18410. \begin{lstlisting}
  18411. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  18412. : (Vector Any Any)
  18413. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18414. (define (inc [x : Integer]) : Integer (+ x 1))
  18415. (vector-ref ((cast map
  18416. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18417. ((Integer -> Integer) (Vector Integer Integer)
  18418. -> (Vector Integer Integer)))
  18419. inc (vector 0 41)) 1)
  18420. \end{lstlisting}
  18421. \caption{The polymorphic \code{map} example after type erasure.}
  18422. \label{fig:map-erase}
  18423. \end{figure}
  18424. This process of type erasure creates a challenge at points of
  18425. instantiation. For example, consider the instantiation of
  18426. \code{map} in Figure~\ref{fig:map-type-check}.
  18427. The type of \code{map} is
  18428. \begin{lstlisting}
  18429. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18430. \end{lstlisting}
  18431. and it is instantiated to
  18432. \begin{lstlisting}
  18433. ((Integer -> Integer) (Vector Integer Integer)
  18434. -> (Vector Integer Integer))
  18435. \end{lstlisting}
  18436. After erasure, the type of \code{map} is
  18437. \begin{lstlisting}
  18438. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18439. \end{lstlisting}
  18440. but we need to convert it to the instantiated type. This is easy to
  18441. do in the language \LangCast{} with a single \code{cast}. In
  18442. Figure~\ref{fig:map-erase}, the instantiation of \code{map} has been
  18443. compiled to a \code{cast} from the type of \code{map} to the
  18444. instantiated type. The source and target type of a cast must be
  18445. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  18446. because both the source and target are obtained from the same
  18447. polymorphic type of \code{map}, replacing the type parameters with
  18448. \code{Any} in the former and with the deduced type arguments in the
  18449. later. (Recall that the \code{Any} type is consistent with any type.)
  18450. To implement the \code{erase-types} pass, we recommend defining a
  18451. recursive auxiliary function named \code{erase-type} that applies the
  18452. following two transformations. It replaces type variables with
  18453. \code{Any}
  18454. \begin{lstlisting}
  18455. |$x$|
  18456. |$\Rightarrow$|
  18457. Any
  18458. \end{lstlisting}
  18459. and it removes the polymorphic \code{All} types.
  18460. \begin{lstlisting}
  18461. (All |$xs$| |$T_1$|)
  18462. |$\Rightarrow$|
  18463. |$T'_1$|
  18464. \end{lstlisting}
  18465. Apply the \code{erase-type} function to all of the type annotations in
  18466. the program.
  18467. Regarding the translation of expressions, the case for \code{Inst} is
  18468. the interesting one. We translate it into a \code{Cast}, as shown
  18469. below. The type of the subexpression $e$ is the polymorphic type
  18470. $\LP\key{All}~\itm{xs}~T\RP$. The source type of the cast is the erasure of
  18471. $T$, the type $T'$. The target type $T''$ is the result of
  18472. substituting the argument types $ts$ for the type parameters $xs$ in
  18473. $T$ followed by doing type erasure.
  18474. \begin{lstlisting}
  18475. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  18476. |$\Rightarrow$|
  18477. (Cast |$e'$| |$T'$| |$T''$|)
  18478. \end{lstlisting}
  18479. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  18480. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  18481. Finally, each polymorphic function is translated to a regular
  18482. function in which type erasure has been applied to all the type
  18483. annotations and the body.
  18484. \begin{lstlisting}
  18485. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  18486. |$\Rightarrow$|
  18487. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  18488. \end{lstlisting}
  18489. \begin{exercise}\normalfont\normalsize
  18490. Implement a compiler for the polymorphic language \LangPoly{} by
  18491. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  18492. programs that use polymorphic functions. Some of them should make
  18493. use of first-class polymorphism.
  18494. \end{exercise}
  18495. \begin{figure}[p]
  18496. \begin{tikzpicture}[baseline=(current bounding box.center)]
  18497. \node (Lpoly) at (12,4) {\large \LangPoly{}};
  18498. \node (Lpolyp) at (9,4) {\large \LangInst{}};
  18499. \node (Lgradualp) at (6,4) {\large \LangCast{}};
  18500. \node (Llambdapp) at (3,4) {\large \LangProxy{}};
  18501. \node (Llambdaproxy) at (0,4) {\large \LangPVec{}};
  18502. \node (Llambdaproxy-2) at (0,2) {\large \LangPVec{}};
  18503. \node (Llambdaproxy-3) at (3,2) {\large \LangPVec{}};
  18504. \node (Llambdaproxy-4) at (6,2) {\large \LangPVecFunRef{}};
  18505. \node (Llambdaproxy-5) at (9,2) {\large \LangPVecFunRef{}};
  18506. \node (F1-1) at (12,2) {\large \LangPVecFunRef{}};
  18507. \node (F1-2) at (12,0) {\large \LangPVecFunRef{}};
  18508. \node (F1-3) at (9,0) {\large \LangPVecFunRef{}};
  18509. \node (F1-4) at (6,0) {\large \LangPVecAlloc{}};
  18510. \node (F1-5) at (3,0) {\large \LangPVecAlloc{}};
  18511. \node (F1-6) at (0,0) {\large \LangPVecAlloc{}};
  18512. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18513. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18514. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18515. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18516. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18517. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18518. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18519. \path[->,bend right=15] (Lpoly) edge [above] node
  18520. {\ttfamily\footnotesize type\_check} (Lpolyp);
  18521. \path[->,bend right=15] (Lpolyp) edge [above] node
  18522. {\ttfamily\footnotesize erase\_types} (Lgradualp);
  18523. \path[->,bend right=15] (Lgradualp) edge [above] node
  18524. {\ttfamily\footnotesize lower\_casts} (Llambdapp);
  18525. \path[->,bend right=15] (Llambdapp) edge [above] node
  18526. {\ttfamily\footnotesize differentiate\_proxies} (Llambdaproxy);
  18527. \path[->,bend right=15] (Llambdaproxy) edge [right] node
  18528. {\ttfamily\footnotesize shrink} (Llambdaproxy-2);
  18529. \path[->,bend left=15] (Llambdaproxy-2) edge [above] node
  18530. {\ttfamily\footnotesize uniquify} (Llambdaproxy-3);
  18531. \path[->,bend left=15] (Llambdaproxy-3) edge [above] node
  18532. {\ttfamily\footnotesize reveal\_functions} (Llambdaproxy-4);
  18533. \path[->,bend left=15] (Llambdaproxy-4) edge [above] node
  18534. {\ttfamily\footnotesize reveal\_casts} (Llambdaproxy-5);
  18535. \path[->,bend left=15] (Llambdaproxy-5) edge [above] node
  18536. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18537. \path[->,bend left=15] (F1-1) edge [left] node
  18538. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18539. \path[->,bend left=15] (F1-2) edge [below] node
  18540. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18541. \path[->,bend right=15] (F1-3) edge [above] node
  18542. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18543. \path[->,bend right=15] (F1-4) edge [above] node
  18544. {\ttfamily\footnotesize uncover\_get!} (F1-5);
  18545. \path[->,bend right=15] (F1-5) edge [above] node
  18546. {\ttfamily\footnotesize remove\_complex.} (F1-6);
  18547. \path[->,bend right=15] (F1-6) edge [right] node
  18548. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18549. \path[->,bend left=15] (C3-2) edge [left] node
  18550. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18551. \path[->,bend right=15] (x86-2) edge [left] node
  18552. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18553. \path[->,bend right=15] (x86-2-1) edge [below] node
  18554. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18555. \path[->,bend right=15] (x86-2-2) edge [left] node
  18556. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18557. \path[->,bend left=15] (x86-3) edge [above] node
  18558. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18559. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_conc.} (x86-5);
  18560. \end{tikzpicture}
  18561. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  18562. \label{fig:Lpoly-passes}
  18563. \end{figure}
  18564. Figure~\ref{fig:Lpoly-passes} provides an overview of the passes
  18565. needed to compile \LangPoly{}.
  18566. % TODO: challenge problem: specialization of instantiations
  18567. % Further Reading
  18568. \fi
  18569. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18570. \clearpage
  18571. \appendix
  18572. \chapter{Appendix}
  18573. \if\edition\racketEd
  18574. \section{Interpreters}
  18575. \label{appendix:interp}
  18576. \index{subject}{interpreter}
  18577. We provide interpreters for each of the source languages \LangInt{},
  18578. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  18579. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  18580. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  18581. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  18582. and x86 are in the \key{interp.rkt} file.
  18583. \section{Utility Functions}
  18584. \label{appendix:utilities}
  18585. The utility functions described in this section are in the
  18586. \key{utilities.rkt} file of the support code.
  18587. \paragraph{\code{interp-tests}}
  18588. The \key{interp-tests} function runs the compiler passes and the
  18589. interpreters on each of the specified tests to check whether each pass
  18590. is correct. The \key{interp-tests} function has the following
  18591. parameters:
  18592. \begin{description}
  18593. \item[name (a string)] a name to identify the compiler,
  18594. \item[typechecker] a function of exactly one argument that either
  18595. raises an error using the \code{error} function when it encounters a
  18596. type error, or returns \code{\#f} when it encounters a type
  18597. error. If there is no type error, the type checker returns the
  18598. program.
  18599. \item[passes] a list with one entry per pass. An entry is a list with
  18600. four things:
  18601. \begin{enumerate}
  18602. \item a string giving the name of the pass,
  18603. \item the function that implements the pass (a translator from AST
  18604. to AST),
  18605. \item a function that implements the interpreter (a function from
  18606. AST to result value) for the output language,
  18607. \item and a type checker for the output language. Type checkers for
  18608. the $R$ and $C$ languages are provided in the support code. For
  18609. example, the type checkers for \LangVar{} and \LangCVar{} are in
  18610. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  18611. type checker entry is optional. The support code does not provide
  18612. type checkers for the x86 languages.
  18613. \end{enumerate}
  18614. \item[source-interp] an interpreter for the source language. The
  18615. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  18616. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  18617. \item[tests] a list of test numbers that specifies which tests to
  18618. run. (see below)
  18619. \end{description}
  18620. %
  18621. The \key{interp-tests} function assumes that the subdirectory
  18622. \key{tests} has a collection of Racket programs whose names all start
  18623. with the family name, followed by an underscore and then the test
  18624. number, ending with the file extension \key{.rkt}. Also, for each test
  18625. program that calls \code{read} one or more times, there is a file with
  18626. the same name except that the file extension is \key{.in} that
  18627. provides the input for the Racket program. If the test program is
  18628. expected to fail type checking, then there should be an empty file of
  18629. the same name but with extension \key{.tyerr}.
  18630. \paragraph{\code{compiler-tests}}
  18631. runs the compiler passes to generate x86 (a \key{.s} file) and then
  18632. runs the GNU C compiler (gcc) to generate machine code. It runs the
  18633. machine code and checks that the output is $42$. The parameters to the
  18634. \code{compiler-tests} function are similar to those of the
  18635. \code{interp-tests} function, and consist of
  18636. \begin{itemize}
  18637. \item a compiler name (a string),
  18638. \item a type checker,
  18639. \item description of the passes,
  18640. \item name of a test-family, and
  18641. \item a list of test numbers.
  18642. \end{itemize}
  18643. \paragraph{\code{compile-file}}
  18644. takes a description of the compiler passes (see the comment for
  18645. \key{interp-tests}) and returns a function that, given a program file
  18646. name (a string ending in \key{.rkt}), applies all of the passes and
  18647. writes the output to a file whose name is the same as the program file
  18648. name but with \key{.rkt} replaced with \key{.s}.
  18649. \paragraph{\code{read-program}}
  18650. takes a file path and parses that file (it must be a Racket program)
  18651. into an abstract syntax tree.
  18652. \paragraph{\code{parse-program}}
  18653. takes an S-expression representation of an abstract syntax tree and converts it into
  18654. the struct-based representation.
  18655. \paragraph{\code{assert}}
  18656. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  18657. and displays the message \key{msg} if the Boolean \key{bool} is false.
  18658. \paragraph{\code{lookup}}
  18659. % remove discussion of lookup? -Jeremy
  18660. takes a key and an alist, and returns the first value that is
  18661. associated with the given key, if there is one. If not, an error is
  18662. triggered. The alist may contain both immutable pairs (built with
  18663. \key{cons}) and mutable pairs (built with \key{mcons}).
  18664. %The \key{map2} function ...
  18665. \fi %\racketEd
  18666. \section{x86 Instruction Set Quick-Reference}
  18667. \label{sec:x86-quick-reference}
  18668. \index{subject}{x86}
  18669. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  18670. do. We write $A \to B$ to mean that the value of $A$ is written into
  18671. location $B$. Address offsets are given in bytes. The instruction
  18672. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  18673. registers (such as \code{\%rax}), or memory references (such as
  18674. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  18675. reference per instruction. Other operands must be immediates or
  18676. registers.
  18677. \begin{table}[tbp]
  18678. \centering
  18679. \begin{tabular}{l|l}
  18680. \textbf{Instruction} & \textbf{Operation} \\ \hline
  18681. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  18682. \texttt{negq} $A$ & $- A \to A$ \\
  18683. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  18684. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  18685. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  18686. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  18687. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  18688. \texttt{retq} & Pops the return address and jumps to it \\
  18689. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  18690. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  18691. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  18692. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  18693. be an immediate) \\
  18694. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  18695. matches the condition code of the instruction, otherwise go to the
  18696. next instructions. The condition codes are \key{e} for ``equal'',
  18697. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  18698. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  18699. \texttt{jl} $L$ & \\
  18700. \texttt{jle} $L$ & \\
  18701. \texttt{jg} $L$ & \\
  18702. \texttt{jge} $L$ & \\
  18703. \texttt{jmp} $L$ & Jump to label $L$ \\
  18704. \texttt{movq} $A$, $B$ & $A \to B$ \\
  18705. \texttt{movzbq} $A$, $B$ &
  18706. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  18707. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  18708. and the extra bytes of $B$ are set to zero.} \\
  18709. & \\
  18710. & \\
  18711. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  18712. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  18713. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  18714. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  18715. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  18716. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  18717. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  18718. description of the condition codes. $A$ must be a single byte register
  18719. (e.g., \texttt{al} or \texttt{cl}).} \\
  18720. \texttt{setl} $A$ & \\
  18721. \texttt{setle} $A$ & \\
  18722. \texttt{setg} $A$ & \\
  18723. \texttt{setge} $A$ &
  18724. \end{tabular}
  18725. \vspace{5pt}
  18726. \caption{Quick-reference for the x86 instructions used in this book.}
  18727. \label{tab:x86-instr}
  18728. \end{table}
  18729. %% \if\edition\racketEd
  18730. %% \cleardoublepage
  18731. %% \section{Concrete Syntax for Intermediate Languages}
  18732. %% The concrete syntax of \LangAny{} is defined in
  18733. %% Figure~\ref{fig:Lany-concrete-syntax}.
  18734. %% \begin{figure}[tp]
  18735. %% \centering
  18736. %% \fbox{
  18737. %% \begin{minipage}{0.97\textwidth}\small
  18738. %% \[
  18739. %% \begin{array}{lcl}
  18740. %% \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  18741. %% \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  18742. %% &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  18743. %% \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  18744. %% \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  18745. %% &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  18746. %% \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  18747. %% &\MID& \LP\key{any-vector-length}\;\Exp\RP
  18748. %% \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  18749. %% &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  18750. %% &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  18751. %% \MID \LP\key{void?}\;\Exp\RP \\
  18752. %% &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  18753. %% \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  18754. %% \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  18755. %% \end{array}
  18756. %% \]
  18757. %% \end{minipage}
  18758. %% }
  18759. %% \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  18760. %% (Figure~\ref{fig:Llam-syntax}).}
  18761. %% \label{fig:Lany-concrete-syntax}
  18762. %% \end{figure}
  18763. %% The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  18764. %% \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  18765. %% \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  18766. %% \ref{fig:c3-concrete-syntax}, respectively.
  18767. %% \begin{figure}[tbp]
  18768. %% \fbox{
  18769. %% \begin{minipage}{0.96\textwidth}
  18770. %% \small
  18771. %% \[
  18772. %% \begin{array}{lcl}
  18773. %% \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  18774. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18775. %% \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  18776. %% &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  18777. %% &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  18778. %% &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  18779. %% &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  18780. %% \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  18781. %% \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  18782. %% \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  18783. %% &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  18784. %% \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  18785. %% \end{array}
  18786. %% \]
  18787. %% \end{minipage}
  18788. %% }
  18789. %% \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  18790. %% \label{fig:c2-concrete-syntax}
  18791. %% \end{figure}
  18792. %% \begin{figure}[tp]
  18793. %% \fbox{
  18794. %% \begin{minipage}{0.96\textwidth}
  18795. %% \small
  18796. %% \[
  18797. %% \begin{array}{lcl}
  18798. %% \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  18799. %% \\
  18800. %% \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18801. %% \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  18802. %% \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  18803. %% &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  18804. %% \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  18805. %% &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  18806. %% &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  18807. %% \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  18808. %% \MID \LP\key{collect} \,\itm{int}\RP }\\
  18809. %% \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  18810. %% &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  18811. %% \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  18812. %% &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  18813. %% \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  18814. %% \LangCFunM{} & ::= & \Def\ldots
  18815. %% \end{array}
  18816. %% \]
  18817. %% \end{minipage}
  18818. %% }
  18819. %% \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  18820. %% \label{fig:c3-concrete-syntax}
  18821. %% \end{figure}
  18822. %% \fi % racketEd
  18823. \backmatter
  18824. \addtocontents{toc}{\vspace{11pt}}
  18825. %% \addtocontents{toc}{\vspace{11pt}}
  18826. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  18827. \nocite{*}\let\bibname\refname
  18828. \addcontentsline{toc}{fmbm}{\refname}
  18829. \printbibliography
  18830. \printindex{authors}{Author Index}
  18831. \printindex{subject}{Subject Index}
  18832. \end{document}
  18833. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  18834. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  18835. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  18836. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  18837. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  18838. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  18839. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  18840. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  18841. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  18842. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  18843. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  18844. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  18845. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  18846. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  18847. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  18848. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  18849. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  18850. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  18851. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS wb
  18852. % LocalWords: morekeywords fullflexible goto allocator tuples Wailes
  18853. % LocalWords: Kernighan runtime Freiburg Thiemann Bloomington unary
  18854. % LocalWords: eq prog rcl binaryop unaryop definitional Evaluator os
  18855. % LocalWords: subexpression evaluator InterpLint lcl quadwords concl
  18856. % LocalWords: nanopass subexpressions decompositions Lawall Hatcliff
  18857. % LocalWords: subdirectory monadic Moggi mon utils macosx unix repr
  18858. % LocalWords: Uncomment undirected vertices callee Liveness liveness
  18859. % LocalWords: frozenset unordered Appel Rosen pqueue cmp Fortran vl
  18860. % LocalWords: Horwitz Kempe colorable subgraph kx iteratively Matula
  18861. % LocalWords: ys ly Palsberg si JoeQ cardinality Poletto Booleans hj
  18862. % LocalWords: subscriptable MyPy Lehtosalo Listof Pairof indexable
  18863. % LocalWords: bool boolop NotEq LtE GtE refactor els orelse BoolOp
  18864. % LocalWords: boolean initializer param exprs TypeCheckLvar msg Tt
  18865. % LocalWords: isinstance TypeCheckLif tyerr xorq bytereg al dh dl ne
  18866. % LocalWords: le ge cmpq movzbq EFLAGS jle inlined setl je jl Cif
  18867. % LocalWords: lll pred IfStmt sete CFG tsort multigraph FunctionType
  18868. % LocalWords: Wijngaarden Plotkin Logothetis PeytonJones SetBang Ph
  18869. % LocalWords: WhileLoop unboxes Lwhile unbox InterpLwhile rhsT varT
  18870. % LocalWords: Tbody TypeCheckLwhile acyclic mainstart mainconclusion
  18871. % LocalWords: versa Kildall Kleene worklist enqueue dequeue deque tb
  18872. % LocalWords: GetBang effectful SPERBER Lfun tuple implementer's tup
  18873. % LocalWords: indices HasType Lvec InterpLtup tuple's vec ty Ungar
  18874. % LocalWords: TypeCheckLtup Detlefs Tene FromSpace ToSpace Diwan ptr
  18875. % LocalWords: Siebert TupleType endian salq sarq fromspace rootstack
  18876. % LocalWords: uint th vecinit alloc GlobalValue andq bitwise ior elt
  18877. % LocalWords: dereferencing StructDef Vectorof vectorof Lvecof Jacek
  18878. % LocalWords: AllocateArray cheney tospace Dieckmann Shahriyar di xs
  18879. % LocalWords: Shidal Osterlund Gamari lexically FunctionDef IntType
  18880. % LocalWords: BoolType VoidType ProgramDefsExp vals params ps ds num
  18881. % LocalWords: InterpLfun FunRef TypeCheckLfun leaq callee's mainDef
  18882. % LocalWords: ProgramDefs TailCall tailjmp IndirectCallq TailJmp rT
  18883. % LocalWords: prepending addstart addconclusion Cardelli Llambda typ
  18884. % LocalWords: Llambda InterpLlambda AnnAssign Dunfield bodyT str fvs
  18885. % LocalWords: TypeCheckLlambda annot dereference clos fvts closTy tg
  18886. % LocalWords: Minamide AllocateClosure Gilray Milner morphos subtype
  18887. % LocalWords: polymorphism untyped AnyType dataclass untag Ldyn conc
  18888. % LocalWords: lookup InterpLdyn elif tagof Lany TypeCheckLany tv orq
  18889. % LocalWords: AnnLambda InterpLany ClosureTuple ValueOf TagOf imulq
  18890. % LocalWords: untagged multi Tobin Hochstadt zr mn Gronski kd ret Tp
  18891. % LocalWords: Tif src tgt Lcast wr contravariant PVector un Lgradual
  18892. % LocalWords: Lgradualp Llambdapp Llambdaproxy Wadler qv quicksort
  18893. % LocalWords: Henglein nz coercions Grift parametetric parameterized
  18894. % LocalWords: parameterizing stroustrup subst tys targs decls defs
  18895. % LocalWords: pts ats prt pxs axs Decl Monomorphization NESL CLU qb
  18896. % LocalWords: monomorphization Blelloch monomorphic Bracha unboxed
  18897. % LocalWords: instantiation Lpoly Lpolyp typechecker mcons ebp jge
  18898. % LocalWords: notq setle setg setge