book.tex 711 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397
  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. \definecolor{lightgray}{gray}{1}
  18. \newcommand{\black}[1]{{\color{black} #1}}
  19. %\newcommand{\gray}[1]{{\color{lightgray} #1}}
  20. \newcommand{\gray}[1]{{\color{gray} #1}}
  21. \def\racketEd{0}
  22. \def\pythonEd{1}
  23. \def\edition{0}
  24. % material that is specific to the Racket edition of the book
  25. \newcommand{\racket}[1]{{\if\edition\racketEd{#1}\fi}}
  26. % would like a command for: \if\edition\racketEd\color{olive}
  27. % and : \fi\color{black}
  28. % material that is specific to the Python edition of the book
  29. \newcommand{\python}[1]{{\if\edition\pythonEd #1\fi}}
  30. %% For multiple indices:
  31. \usepackage{multind}
  32. \makeindex{subject}
  33. \makeindex{authors}
  34. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  35. \if\edition\racketEd
  36. \lstset{%
  37. language=Lisp,
  38. basicstyle=\ttfamily\small,
  39. morekeywords={seq,assign,program,block,define,lambda,match,goto,if,else,then,struct,Integer,Boolean,Vector,Void,Any,while,begin,define,public,override,class},
  40. deletekeywords={read,mapping,vector},
  41. escapechar=|,
  42. columns=flexible,
  43. moredelim=[is][\color{red}]{~}{~},
  44. showstringspaces=false
  45. }
  46. \fi
  47. \if\edition\pythonEd
  48. \lstset{%
  49. language=Python,
  50. basicstyle=\ttfamily\small,
  51. morekeywords={match,case,bool,int,let},
  52. deletekeywords={},
  53. escapechar=|,
  54. columns=flexible,
  55. moredelim=[is][\color{red}]{~}{~},
  56. showstringspaces=false
  57. }
  58. \fi
  59. %%% Any shortcut own defined macros place here
  60. %% sample of author macro:
  61. \input{defs}
  62. \newtheorem{exercise}[theorem]{Exercise}
  63. % Adjusted settings
  64. \setlength{\columnsep}{4pt}
  65. %% \begingroup
  66. %% \setlength{\intextsep}{0pt}%
  67. %% \setlength{\columnsep}{0pt}%
  68. %% \begin{wrapfigure}{r}{0.5\textwidth}
  69. %% \centering\includegraphics[width=\linewidth]{example-image-a}
  70. %% \caption{Basic layout}
  71. %% \end{wrapfigure}
  72. %% \lipsum[1]
  73. %% \endgroup
  74. \newbox\oiintbox
  75. \setbox\oiintbox=\hbox{$\lower2pt\hbox{\huge$\displaystyle\circ$}
  76. \hskip-13pt\displaystyle\int\hskip-7pt\int_{S}\ $}
  77. \def\oiint{\copy\oiintbox}
  78. \def\boldnabla{\hbox{\boldmath$\displaystyle\nabla$}}
  79. %\usepackage{showframe}
  80. \def\ShowFrameLinethickness{0.125pt}
  81. \addbibresource{book.bib}
  82. \begin{document}
  83. \frontmatter
  84. \HalfTitle{Essentials of Compilation \\ An Incremental Approach in \python{Python}\racket{Racket}}
  85. \halftitlepage
  86. \Title{Essentials of Compilation}
  87. \Booksubtitle{An Incremental Approach in \python{Python}\racket{Racket}}
  88. %\edition{First Edition}
  89. \BookAuthor{Jeremy G. Siek}
  90. \imprint{The MIT Press\\
  91. Cambridge, Massachusetts\\
  92. London, England}
  93. \begin{copyrightpage}
  94. \textcopyright\ 2021 Jeremy G. Siek. Available for free viewing
  95. or personal downloading under the
  96. \href{https://creativecommons.org/licenses/by-nc-nd/2.0/uk/}{CC-BY-NC-ND}
  97. license.
  98. Copyright in this monograph has been licensed exclusively to The MIT
  99. Press, \url{http://mitpress.mit.edu}, which will be releasing the final
  100. version to the public in 2022. All inquiries regarding rights should
  101. be addressed to The MIT Press, Rights and Permissions Department.
  102. %% \textcopyright\ [YEAR] Massachusetts Institute of Technology
  103. %% All rights reserved. No part of this book may be reproduced in any
  104. %% form by any electronic or mechanical means (including photocopying,
  105. %% recording, or information storage and retrieval) without permission in
  106. %% writing from the publisher.
  107. %% This book was set in LaTeX by Jeremy G. Siek. Printed and bound in the
  108. %% United States of America.
  109. %% Library of Congress Cataloging-in-Publication Data is available.
  110. %% ISBN:
  111. %% 10\quad9\quad8\quad7\quad6\quad5\quad4\quad3\quad2\quad1
  112. \end{copyrightpage}
  113. \dedication{This book is dedicated to the programming language wonks
  114. at Indiana University.}
  115. %% \begin{epigraphpage}
  116. %% \epigraph{First Epigraph line goes here}{Mention author name if any,
  117. %% \textit{Book Name if any}}
  118. %% \epigraph{Second Epigraph line goes here}{Mention author name if any}
  119. %% \end{epigraphpage}
  120. \tableofcontents
  121. %\listoffigures
  122. %\listoftables
  123. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  124. \chapter*{Preface}
  125. \addcontentsline{toc}{fmbm}{Preface}
  126. There is a magical moment when a programmer presses the ``run'' button
  127. and the software begins to execute. Somehow a program written in a
  128. high-level language is running on a computer that is only capable of
  129. shuffling bits. Here we reveal the wizardry that makes that moment
  130. possible. Beginning with the groundbreaking work of Backus and
  131. colleagues in the 1950s, computer scientists discovered techniques for
  132. constructing programs, called \emph{compilers}, that automatically
  133. translate high-level programs into machine code.
  134. We take you on a journey of constructing your own compiler for a small
  135. but powerful language. Along the way we explain the essential
  136. concepts, algorithms, and data structures that underlie compilers. We
  137. develop your understanding of how programs are mapped onto computer
  138. hardware, which is helpful when reasoning about properties at the
  139. junction between hardware and software such as execution time,
  140. software errors, and security vulnerabilities. For those interested
  141. in pursuing compiler construction as a career, our goal is to provide a
  142. stepping-stone to advanced topics such as just-in-time compilation,
  143. program analysis, and program optimization. For those interested in
  144. designing and implementing programming languages, we connect
  145. language design choices to their impact on the compiler and the generated
  146. code.
  147. A compiler is typically organized as a sequence of stages that
  148. progressively translate a program to the code that runs on
  149. hardware. We take this approach to the extreme by partitioning our
  150. compiler into a large number of \emph{nanopasses}, each of which
  151. performs a single task. This enables the testing of each pass in
  152. isolation and focuses our attention, making the compiler far easier to
  153. understand.
  154. The most familiar approach to describing compilers is with each
  155. chapter dedicated to one pass. The problem with that approach is it
  156. obfuscates how language features motivate design choices in a
  157. compiler. We instead take an \emph{incremental} approach in which we
  158. build a complete compiler in each chapter, starting with a small input
  159. language that includes only arithmetic and variables. We add new
  160. language features in subsequent chapters, extending the compiler as
  161. necessary.
  162. Our choice of language features is designed to elicit fundamental
  163. concepts and algorithms used in compilers.
  164. \begin{itemize}
  165. \item We begin with integer arithmetic and local variables in
  166. Chapters~\ref{ch:trees-recur} and \ref{ch:Lvar}, where we introduce
  167. the fundamental tools of compiler construction: \emph{abstract
  168. syntax trees} and \emph{recursive functions}.
  169. \item In Chapter~\ref{ch:register-allocation-Lvar} we apply
  170. \emph{graph coloring} to assign variables to machine registers.
  171. \item Chapter~\ref{ch:Lif} adds conditional expressions, which
  172. motivates an elegant recursive algorithm for translating them into
  173. conditional \code{goto}'s.
  174. \item Chapter~\ref{ch:Lwhile} adds loops\racket{ and mutable
  175. variables}. This elicits the need for \emph{dataflow
  176. analysis} in the register allocator.
  177. \item Chapter~\ref{ch:Lvec} adds heap-allocated tuples, motivating
  178. \emph{garbage collection}.
  179. \item Chapter~\ref{ch:Lfun} adds functions as first-class values but
  180. without lexical scoping, similar to functions in the C programming
  181. language~\citep{Kernighan:1988nx}. The reader learns about the
  182. procedure call stack and \emph{calling conventions} and how they interact
  183. with register allocation and garbage collection. The chapter also
  184. describes how to generate efficient tail calls.
  185. \item Chapter~\ref{ch:Llambda} adds anonymous functions with lexical
  186. scoping, i.e., \emph{lambda} expressions. The reader learns about
  187. \emph{closure conversion}, in which lambdas are translated into a
  188. combination of functions and tuples.
  189. % Chapter about classes and objects?
  190. \item Chapter~\ref{ch:Ldyn} adds \emph{dynamic typing}. Prior to this
  191. point the input languages are statically typed. The reader extends
  192. the statically typed language with an \code{Any} type which serves
  193. as a target for compiling the dynamically typed language.
  194. {\if\edition\pythonEd
  195. \item Chapter~\ref{ch:Lobject} adds support for \emph{objects} and
  196. \emph{classes}.
  197. \fi}
  198. \item Chapter~\ref{ch:Lgrad} uses the \code{Any} type of
  199. Chapter~\ref{ch:Ldyn} to implement a \emph{gradually typed language}
  200. in which different regions of a program may be static or dynamically
  201. typed. The reader implements runtime support for \emph{proxies} that
  202. allow values to safely move between regions.
  203. \item Chapter~\ref{ch:Lpoly} adds \emph{generics} with autoboxing,
  204. leveraging the \code{Any} type and type casts developed in Chapters
  205. \ref{ch:Ldyn} and \ref{ch:Lgrad}.
  206. \end{itemize}
  207. There are many language features that we do not include. Our choices
  208. balance the incidental complexity of a feature versus the fundamental
  209. concepts that it exposes. For example, we include tuples and not
  210. records because they both elicit the study of heap allocation and
  211. garbage collection but records come with more incidental complexity.
  212. Since 2009 drafts of this book have served as the textbook for 16-week
  213. compiler courses for upper-level undergraduates and first-year
  214. graduate students at the University of Colorado and Indiana
  215. University.
  216. %
  217. Students come into the course having learned the basics of
  218. programming, data structures and algorithms, and discrete
  219. mathematics.
  220. %
  221. At the beginning of the course, students form groups of 2-4 people.
  222. The groups complete one chapter every two weeks, starting with
  223. Chapter~\ref{ch:Lvar} and finishing with
  224. Chapter~\ref{ch:Llambda}. Many chapters include a challenge problem
  225. that we assign to the graduate students. The last two weeks of the
  226. course involve a final project in which students design and implement
  227. a compiler extension of their choosing. The later chapters can be
  228. used in support of these projects. For compiler courses at
  229. universities on the quarter system (about 10 weeks in length), we
  230. recommend completing up through Chapter~\ref{ch:Lvec} or
  231. Chapter~\ref{ch:Lfun} and providing some scafolding code to the
  232. students for each compiler pass.
  233. %
  234. The course can be adapted to emphasize functional languages by
  235. skipping Chapter~\ref{ch:Lwhile} (loops) and including
  236. Chapter~\ref{ch:Llambda} (lambda). The course can be adapted to
  237. dynamically typed languages by including Chapter~\ref{ch:Ldyn}.
  238. %
  239. \python{A course that emphasizes object-oriented languages would
  240. include Chapter~\ref{ch:Lobject}.}
  241. %
  242. Figure~\ref{fig:chapter-dependences} depicts the dependencies between
  243. chapters. Chapter~\ref{ch:Lfun} (functions) depends on
  244. Chapter~\ref{ch:Lvec} (tuples) only in the implementation of efficient
  245. tail calls.
  246. This book has been used in compiler courses at California Polytechnic
  247. State University, Portland State University, Rose–Hulman Institute of
  248. Technology, University of Freiburg, University of Massachusetts
  249. Lowell, and the University of Vermont.
  250. \begin{figure}[tp]
  251. {\if\edition\racketEd
  252. \begin{tikzpicture}[baseline=(current bounding box.center)]
  253. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  254. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  255. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  256. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  257. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  258. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  259. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  260. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  261. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  262. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  263. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  264. \path[->] (C1) edge [above] node {} (C2);
  265. \path[->] (C2) edge [above] node {} (C3);
  266. \path[->] (C3) edge [above] node {} (C4);
  267. \path[->] (C4) edge [above] node {} (C5);
  268. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  269. \path[->] (C5) edge [above] node {} (C7);
  270. \path[->] (C6) edge [above] node {} (C7);
  271. \path[->] (C4) edge [above] node {} (C8);
  272. \path[->] (C4) edge [above] node {} (C9);
  273. \path[->] (C7) edge [above] node {} (C10);
  274. \path[->] (C8) edge [above] node {} (C10);
  275. \path[->] (C10) edge [above] node {} (C11);
  276. \end{tikzpicture}
  277. \fi}
  278. {\if\edition\pythonEd
  279. \begin{tikzpicture}[baseline=(current bounding box.center)]
  280. \node (C1) at (0,1.5) {\small Ch.~\ref{ch:trees-recur} Preliminaries};
  281. \node (C2) at (4,1.5) {\small Ch.~\ref{ch:Lvar} Variables};
  282. \node (C3) at (8,1.5) {\small Ch.~\ref{ch:register-allocation-Lvar} Registers};
  283. \node (C4) at (0,0) {\small Ch.~\ref{ch:Lif} Conditionals};
  284. \node (C5) at (4,0) {\small Ch.~\ref{ch:Lvec} Tuples};
  285. \node (C6) at (8,0) {\small Ch.~\ref{ch:Lfun} Functions};
  286. \node (C9) at (0,-1.5) {\small Ch.~\ref{ch:Lwhile} Loops};
  287. \node (C8) at (4,-1.5) {\small Ch.~\ref{ch:Ldyn} Dynamic};
  288. \node (CO) at (0,-3) {\small Ch.~\ref{ch:Lobject} Objects};
  289. \node (C7) at (8,-1.5) {\small Ch.~\ref{ch:Llambda} Lambda};
  290. \node (C10) at (4,-3) {\small Ch.~\ref{ch:Lgrad} Gradual Typing};
  291. \node (C11) at (8,-3) {\small Ch.~\ref{ch:Lpoly} Generics};
  292. \path[->] (C1) edge [above] node {} (C2);
  293. \path[->] (C2) edge [above] node {} (C3);
  294. \path[->] (C3) edge [above] node {} (C4);
  295. \path[->] (C4) edge [above] node {} (C5);
  296. \path[->,style=dotted] (C5) edge [above] node {} (C6);
  297. \path[->] (C5) edge [above] node {} (C7);
  298. \path[->] (C6) edge [above] node {} (C7);
  299. \path[->] (C4) edge [above] node {} (C8);
  300. \path[->] (C4) edge [above] node {} (C9);
  301. \path[->] (C7) edge [above] node {} (C10);
  302. \path[->] (C8) edge [above] node {} (C10);
  303. \path[->] (C8) edge [above] node {} (CO);
  304. \path[->] (C10) edge [above] node {} (C11);
  305. \end{tikzpicture}
  306. \fi}
  307. \caption{Diagram of chapter dependencies.}
  308. \label{fig:chapter-dependences}
  309. \end{figure}
  310. \racket{
  311. We use the \href{https://racket-lang.org/}{Racket} language both for
  312. the implementation of the compiler and for the input language, so the
  313. reader should be proficient with Racket or Scheme. There are many
  314. excellent resources for learning Scheme and
  315. Racket~\citep{Dybvig:1987aa,Abelson:1996uq,Friedman:1996aa,Felleisen:2001aa,Felleisen:2013aa,Flatt:2014aa}.
  316. }
  317. \python{
  318. This edition of the book uses \href{https://www.python.org/}{Python}
  319. both for the implementation of the compiler and for the input language, so the
  320. reader should be proficient with Python. There are many
  321. excellent resources for learning Python~\citep{Lutz:2013vp,Barry:2016vj,Sweigart:2019vn,Matthes:2019vs}.
  322. }
  323. The support code for this book is in the github repository at
  324. the following location:
  325. \if\edition\racketEd
  326. \begin{center}\small
  327. \url{https://github.com/IUCompilerCourse/public-student-support-code}
  328. \end{center}
  329. \fi
  330. \if\edition\pythonEd
  331. \begin{center}\small
  332. \url{https://github.com/IUCompilerCourse/}
  333. \end{center}
  334. \fi
  335. The compiler targets x86 assembly language~\citep{Intel:2015aa}, so it
  336. is helpful but not necessary for the reader to have taken a computer
  337. systems course~\citep{Bryant:2010aa}. We introduce the parts of x86-64
  338. assembly language that are needed in the compiler.
  339. %
  340. We follow the System V calling
  341. conventions~\citep{Bryant:2005aa,Matz:2013aa}, so the assembly code
  342. that we generate works with the runtime system (written in C) when it
  343. is compiled using the GNU C compiler (\code{gcc}) on Linux and MacOS
  344. operating systems on Intel hardware.
  345. %
  346. On the Windows operating system, \code{gcc} uses the Microsoft x64
  347. calling convention~\citep{Microsoft:2018aa,Microsoft:2020aa}. So the
  348. assembly code that we generate does \emph{not} work with the runtime
  349. system on Windows. One workaround is to use a virtual machine with
  350. Linux as the guest operating system.
  351. \section*{Acknowledgments}
  352. The tradition of compiler construction at Indiana University goes back
  353. to research and courses on programming languages by Daniel Friedman in
  354. the 1970's and 1980's. One of his students, Kent Dybvig, implemented
  355. Chez Scheme~\citep{Dybvig:2006aa}, an efficient, production-quality
  356. compiler for Scheme. Throughout the 1990's and 2000's, Dybvig taught
  357. the compiler course and continued the development of Chez Scheme.
  358. %
  359. The compiler course evolved to incorporate novel pedagogical ideas
  360. while also including elements of real-world compilers. One of
  361. Friedman's ideas was to split the compiler into many small
  362. passes. Another idea, called ``the game'', was to test the code
  363. generated by each pass using interpreters.
  364. Dybvig, with help from his students Dipanwita Sarkar and Andrew Keep,
  365. developed infrastructure to support this approach and evolved the
  366. course to use even smaller
  367. nanopasses~\citep{Sarkar:2004fk,Keep:2012aa}. Many of the compiler
  368. design decisions in this book are inspired by the assignment
  369. descriptions of \citet{Dybvig:2010aa}. In the mid 2000's a student of
  370. Dybvig's named Abdulaziz Ghuloum observed that the front-to-back
  371. organization of the course made it difficult for students to
  372. understand the rationale for the compiler design. Ghuloum proposed the
  373. incremental approach~\citep{Ghuloum:2006bh} that this book is based
  374. on.
  375. We thank the many students who served as teaching assistants for the
  376. compiler course at IU including Carl Factora, Ryan Scott, Cameron
  377. Swords, and Chris Wailes. We thank Andre Kuhlenschmidt for work on the
  378. garbage collector and x86 interpreter, Michael Vollmer for work on
  379. efficient tail calls, and Michael Vitousek for help with the first
  380. offering of the incremental compiler course at IU.
  381. We thank professors Bor-Yuh Chang, John Clements, Jay McCarthy, Joseph
  382. Near, Ryan Newton, Nate Nystrom, Peter Thiemann, Andrew Tolmach, and
  383. Michael Wollowski for teaching courses based on drafts of this book
  384. and for their feedback.
  385. We thank Ronald Garcia for helping Jeremy survive Dybvig's compiler
  386. course in the early 2000's and especially for finding the bug that
  387. sent our garbage collector on a wild goose chase!
  388. \mbox{}\\
  389. \noindent Jeremy G. Siek \\
  390. Bloomington, Indiana
  391. \mainmatter
  392. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  393. \chapter{Preliminaries}
  394. \label{ch:trees-recur}
  395. In this chapter we review the basic tools that are needed to implement
  396. a compiler. Programs are typically input by a programmer as text,
  397. i.e., a sequence of characters. The program-as-text representation is
  398. called \emph{concrete syntax}. We use concrete syntax to concisely
  399. write down and talk about programs. Inside the compiler, we use
  400. \emph{abstract syntax trees} (ASTs) to represent programs in a way
  401. that efficiently supports the operations that the compiler needs to
  402. perform.\index{subject}{concrete syntax}\index{subject}{abstract syntax}\index{subject}{abstract
  403. syntax tree}\index{subject}{AST}\index{subject}{program}\index{subject}{parse} The translation
  404. from concrete syntax to abstract syntax is a process called
  405. \emph{parsing}~\citep{Aho:2006wb}. We do not cover the theory and
  406. implementation of parsing in this book.
  407. %
  408. \racket{A parser is provided in the support code for translating from
  409. concrete to abstract syntax.}
  410. %
  411. \python{We use Python's \code{ast} module to translate from concrete
  412. to abstract syntax.}
  413. ASTs can be represented in many different ways inside the compiler,
  414. depending on the programming language used to write the compiler.
  415. %
  416. \racket{We use Racket's
  417. \href{https://docs.racket-lang.org/guide/define-struct.html}{\code{struct}}
  418. feature to represent ASTs (Section~\ref{sec:ast}).}
  419. %
  420. \python{We use Python classes and objects to represent ASTs, especially the
  421. classes defined in the standard \code{ast} module for the Python
  422. source language.}
  423. %
  424. We use grammars to define the abstract syntax of programming languages
  425. (Section~\ref{sec:grammar}) and pattern matching to inspect individual
  426. nodes in an AST (Section~\ref{sec:pattern-matching}). We use
  427. recursive functions to construct and deconstruct ASTs
  428. (Section~\ref{sec:recursion}). This chapter provides an brief
  429. introduction to these ideas.
  430. \racket{\index{subject}{struct}}
  431. \python{\index{subject}{class}\index{subject}{object}}
  432. \section{Abstract Syntax Trees}
  433. \label{sec:ast}
  434. Compilers use abstract syntax trees to represent programs because they
  435. often need to ask questions like: for a given part of a program, what
  436. kind of language feature is it? What are its sub-parts? Consider the
  437. program on the left and its AST on the right. This program is an
  438. addition operation and it has two sub-parts, a
  439. \racket{read}\python{input} operation and a negation. The negation has
  440. another sub-part, the integer constant \code{8}. By using a tree to
  441. represent the program, we can easily follow the links to go from one
  442. part of a program to its sub-parts.
  443. \begin{center}
  444. \begin{minipage}{0.4\textwidth}
  445. \if\edition\racketEd
  446. \begin{lstlisting}
  447. (+ (read) (- 8))
  448. \end{lstlisting}
  449. \fi
  450. \if\edition\pythonEd
  451. \begin{lstlisting}
  452. input_int() + -8
  453. \end{lstlisting}
  454. \fi
  455. \end{minipage}
  456. \begin{minipage}{0.4\textwidth}
  457. \begin{equation}
  458. \begin{tikzpicture}
  459. \node[draw] (plus) at (0 , 0) {\key{+}};
  460. \node[draw] (read) at (-1, -1.5) {{\if\edition\racketEd\footnotesize\key{read}\fi\if\edition\pythonEd\key{input\_int()}\fi}};
  461. \node[draw] (minus) at (1 , -1.5) {$\key{-}$};
  462. \node[draw] (8) at (1 , -3) {\key{8}};
  463. \draw[->] (plus) to (read);
  464. \draw[->] (plus) to (minus);
  465. \draw[->] (minus) to (8);
  466. \end{tikzpicture}
  467. \label{eq:arith-prog}
  468. \end{equation}
  469. \end{minipage}
  470. \end{center}
  471. We use the standard terminology for trees to describe ASTs: each
  472. rectangle above is called a \emph{node}. The arrows connect a node to its
  473. \emph{children} (which are also nodes). The top-most node is the
  474. \emph{root}. Every node except for the root has a \emph{parent} (the
  475. node it is the child of). If a node has no children, it is a
  476. \emph{leaf} node. Otherwise it is an \emph{internal} node.
  477. \index{subject}{node}
  478. \index{subject}{children}
  479. \index{subject}{root}
  480. \index{subject}{parent}
  481. \index{subject}{leaf}
  482. \index{subject}{internal node}
  483. %% Recall that an \emph{symbolic expression} (S-expression) is either
  484. %% \begin{enumerate}
  485. %% \item an atom, or
  486. %% \item a pair of two S-expressions, written $(e_1 \key{.} e_2)$,
  487. %% where $e_1$ and $e_2$ are each an S-expression.
  488. %% \end{enumerate}
  489. %% An \emph{atom} can be a symbol, such as \code{`hello}, a number, the
  490. %% null value \code{'()}, etc. We can create an S-expression in Racket
  491. %% simply by writing a backquote (called a quasi-quote in Racket)
  492. %% followed by the textual representation of the S-expression. It is
  493. %% quite common to use S-expressions to represent a list, such as $a, b
  494. %% ,c$ in the following way:
  495. %% \begin{lstlisting}
  496. %% `(a . (b . (c . ())))
  497. %% \end{lstlisting}
  498. %% Each element of the list is in the first slot of a pair, and the
  499. %% second slot is either the rest of the list or the null value, to mark
  500. %% the end of the list. Such lists are so common that Racket provides
  501. %% special notation for them that removes the need for the periods
  502. %% and so many parenthesis:
  503. %% \begin{lstlisting}
  504. %% `(a b c)
  505. %% \end{lstlisting}
  506. %% The following expression creates an S-expression that represents AST
  507. %% \eqref{eq:arith-prog}.
  508. %% \begin{lstlisting}
  509. %% `(+ (read) (- 8))
  510. %% \end{lstlisting}
  511. %% When using S-expressions to represent ASTs, the convention is to
  512. %% represent each AST node as a list and to put the operation symbol at
  513. %% the front of the list. The rest of the list contains the children. So
  514. %% in the above case, the root AST node has operation \code{`+} and its
  515. %% two children are \code{`(read)} and \code{`(- 8)}, just as in the
  516. %% diagram \eqref{eq:arith-prog}.
  517. %% To build larger S-expressions one often needs to splice together
  518. %% several smaller S-expressions. Racket provides the comma operator to
  519. %% splice an S-expression into a larger one. For example, instead of
  520. %% creating the S-expression for AST \eqref{eq:arith-prog} all at once,
  521. %% we could have first created an S-expression for AST
  522. %% \eqref{eq:arith-neg8} and then spliced that into the addition
  523. %% S-expression.
  524. %% \begin{lstlisting}
  525. %% (define ast1.4 `(- 8))
  526. %% (define ast1_1 `(+ (read) ,ast1.4))
  527. %% \end{lstlisting}
  528. %% In general, the Racket expression that follows the comma (splice)
  529. %% can be any expression that produces an S-expression.
  530. {\if\edition\racketEd
  531. We define a Racket \code{struct} for each kind of node. For this
  532. chapter we require just two kinds of nodes: one for integer constants
  533. and one for primitive operations. The following is the \code{struct}
  534. definition for integer constants.\footnote{All of the AST structures are
  535. defined in the file \code{utilities.rkt} in the support code.}
  536. \begin{lstlisting}
  537. (struct Int (value))
  538. \end{lstlisting}
  539. An integer node includes just one thing: the integer value.
  540. To create an AST node for the integer $8$, we write \INT{8}.
  541. \begin{lstlisting}
  542. (define eight (Int 8))
  543. \end{lstlisting}
  544. We say that the value created by \INT{8} is an
  545. \emph{instance} of the
  546. \code{Int} structure.
  547. The following is the \code{struct} definition for primitive operations.
  548. \begin{lstlisting}
  549. (struct Prim (op args))
  550. \end{lstlisting}
  551. A primitive operation node includes an operator symbol \code{op} and a
  552. list of child \code{args}. For example, to create an AST that negates
  553. the number $8$, we write the following.
  554. \begin{lstlisting}
  555. (define neg-eight (Prim '- (list eight)))
  556. \end{lstlisting}
  557. Primitive operations may have zero or more children. The \code{read}
  558. operator has zero:
  559. \begin{lstlisting}
  560. (define rd (Prim 'read '()))
  561. \end{lstlisting}
  562. The addition operator has two children:
  563. \begin{lstlisting}
  564. (define ast1_1 (Prim '+ (list rd neg-eight)))
  565. \end{lstlisting}
  566. We have made a design choice regarding the \code{Prim} structure.
  567. Instead of using one structure for many different operations
  568. (\code{read}, \code{+}, and \code{-}), we could have instead defined a
  569. structure for each operation, as follows.
  570. \begin{lstlisting}
  571. (struct Read ())
  572. (struct Add (left right))
  573. (struct Neg (value))
  574. \end{lstlisting}
  575. The reason we choose to use just one structure is that in many parts
  576. of the compiler the code for the different primitive operators is the
  577. same, so we might as well just write that code once, which is enabled
  578. by using a single structure.
  579. \fi}
  580. {\if\edition\pythonEd
  581. We use a Python \code{class} for each kind of node.
  582. The following is the class definition for constants.
  583. \begin{lstlisting}
  584. class Constant:
  585. def __init__(self, value):
  586. self.value = value
  587. \end{lstlisting}
  588. An integer constant node includes just one thing: the integer value.
  589. To create an AST node for the integer $8$, we write \INT{8}.
  590. \begin{lstlisting}
  591. eight = Constant(8)
  592. \end{lstlisting}
  593. We say that the value created by \INT{8} is an
  594. \emph{instance} of the \code{Constant} class.
  595. The following is the class definition for unary operators.
  596. \begin{lstlisting}
  597. class UnaryOp:
  598. def __init__(self, op, operand):
  599. self.op = op
  600. self.operand = operand
  601. \end{lstlisting}
  602. The specific operation is specified by the \code{op} parameter. For
  603. example, the class \code{USub} is for unary subtraction. (More unary
  604. operators are introduced in later chapters.) To create an AST that
  605. negates the number $8$, we write the following.
  606. \begin{lstlisting}
  607. neg_eight = UnaryOp(USub(), eight)
  608. \end{lstlisting}
  609. The call to the \code{input\_int} function is represented by the
  610. \code{Call} and \code{Name} classes.
  611. \begin{lstlisting}
  612. class Call:
  613. def __init__(self, func, args):
  614. self.func = func
  615. self.args = args
  616. class Name:
  617. def __init__(self, id):
  618. self.id = id
  619. \end{lstlisting}
  620. To create an AST node that calls \code{input\_int}, we write
  621. \begin{lstlisting}
  622. read = Call(Name('input_int'), [])
  623. \end{lstlisting}
  624. Finally, to represent the addition in \eqref{eq:arith-prog}, we use
  625. the \code{BinOp} class for binary operators.
  626. \begin{lstlisting}
  627. class BinOp:
  628. def __init__(self, left, op, right):
  629. self.op = op
  630. self.left = left
  631. self.right = right
  632. \end{lstlisting}
  633. Similar to \code{UnaryOp}, the specific operation is specified by the
  634. \code{op} parameter, which for now is just an instance of the
  635. \code{Add} class. So to create the AST node that adds negative eight
  636. to some user input, we write the following.
  637. \begin{lstlisting}
  638. ast1_1 = BinOp(read, Add(), neg_eight)
  639. \end{lstlisting}
  640. \fi}
  641. When compiling a program such as \eqref{eq:arith-prog}, we need to
  642. know that the operation associated with the root node is addition and
  643. we need to be able to access its two children. \racket{Racket}\python{Python}
  644. provides pattern matching to support these kinds of queries, as we see in
  645. Section~\ref{sec:pattern-matching}.
  646. We often write down the concrete syntax of a program even when we
  647. really have in mind the AST because the concrete syntax is more
  648. concise. We recommend that, in your mind, you always think of
  649. programs as abstract syntax trees.
  650. \section{Grammars}
  651. \label{sec:grammar}
  652. \index{subject}{integer}
  653. \index{subject}{literal}
  654. \index{subject}{constant}
  655. A programming language can be thought of as a \emph{set} of programs.
  656. The set is typically infinite (one can always create larger and larger
  657. programs) so one cannot simply describe a language by listing all of
  658. the programs in the language. Instead we write down a set of rules, a
  659. \emph{grammar}, for building programs. Grammars are often used to
  660. define the concrete syntax of a language but they can also be used to
  661. describe the abstract syntax. We write our rules in a variant of
  662. Backus-Naur Form (BNF)~\citep{Backus:1960aa,Knuth:1964aa}.
  663. \index{subject}{Backus-Naur Form}\index{subject}{BNF}
  664. As an example, we describe a small language, named \LangInt{}, that consists of
  665. integers and arithmetic operations.
  666. \index{subject}{grammar}
  667. The first grammar rule for the abstract syntax of \LangInt{} says that an
  668. instance of the \racket{\code{Int} structure}\python{\code{Constant} class} is an expression:
  669. \begin{equation}
  670. \Exp ::= \INT{\Int} \label{eq:arith-int}
  671. \end{equation}
  672. %
  673. Each rule has a left-hand-side and a right-hand-side.
  674. If you have an AST node that matches the
  675. right-hand-side, then you can categorize it according to the
  676. left-hand-side.
  677. %
  678. Symbols in typewriter font are \emph{terminal} symbols and must
  679. literally appear in the program for the rule to be applicable.
  680. \index{subject}{terminal}
  681. %
  682. Our grammars do not mention \emph{white-space}, that is, separating characters
  683. like spaces, tabulators, and newlines. White-space may be inserted
  684. between symbols for disambiguation and to improve readability.
  685. \index{subject}{white-space}
  686. %
  687. A name such as $\Exp$ that is defined by the grammar rules is a
  688. \emph{non-terminal}. \index{subject}{non-terminal}
  689. %
  690. The name $\Int$ is also a non-terminal, but instead of defining it
  691. with a grammar rule, we define it with the following explanation. An
  692. $\Int$ is a sequence of decimals ($0$ to $9$), possibly starting with
  693. $-$ (for negative integers), such that the sequence of decimals
  694. represent an integer in range $-2^{62}$ to $2^{62}-1$. This enables
  695. the representation of integers using 63 bits, which simplifies several
  696. aspects of compilation. \racket{Thus, these integers correspond to
  697. the Racket \texttt{fixnum} datatype on a 64-bit machine.}
  698. \python{In contrast, integers in Python have unlimited precision, but
  699. the techniques needed to handle unlimited precision fall outside the
  700. scope of this book.}
  701. The second grammar rule is the \READOP{} operation that receives an
  702. input integer from the user of the program.
  703. \begin{equation}
  704. \Exp ::= \READ{} \label{eq:arith-read}
  705. \end{equation}
  706. The third rule categorizes the negation of an $\Exp$ node as an
  707. $\Exp$.
  708. \begin{equation}
  709. \Exp ::= \NEG{\Exp} \label{eq:arith-neg}
  710. \end{equation}
  711. We can apply these rules to categorize the ASTs that are in the
  712. \LangInt{} language. For example, by rule \eqref{eq:arith-int}
  713. \INT{8} is an $\Exp$, then by rule \eqref{eq:arith-neg} the
  714. following AST is an $\Exp$.
  715. \begin{center}
  716. \begin{minipage}{0.5\textwidth}
  717. \NEG{\INT{\code{8}}}
  718. \end{minipage}
  719. \begin{minipage}{0.25\textwidth}
  720. \begin{equation}
  721. \begin{tikzpicture}
  722. \node[draw, circle] (minus) at (0, 0) {$\text{--}$};
  723. \node[draw, circle] (8) at (0, -1.2) {$8$};
  724. \draw[->] (minus) to (8);
  725. \end{tikzpicture}
  726. \label{eq:arith-neg8}
  727. \end{equation}
  728. \end{minipage}
  729. \end{center}
  730. The next grammar rules are for addition and subtraction expressions:
  731. \begin{align}
  732. \Exp &::= \ADD{\Exp}{\Exp} \label{eq:arith-add}\\
  733. \Exp &::= \SUB{\Exp}{\Exp} \label{eq:arith-sub}
  734. \end{align}
  735. We can now justify that the AST \eqref{eq:arith-prog} is an $\Exp$ in
  736. \LangInt{}. We know that \READ{} is an $\Exp$ by rule
  737. \eqref{eq:arith-read} and we have already categorized
  738. \NEG{\INT{\code{8}}} as an $\Exp$, so we apply rule \eqref{eq:arith-add}
  739. to show that
  740. \[
  741. \ADD{\READ{}}{\NEG{\INT{\code{8}}}}
  742. \]
  743. is an $\Exp$ in the \LangInt{} language.
  744. If you have an AST for which the above rules do not apply, then the
  745. AST is not in \LangInt{}. For example, the program \racket{\code{(*
  746. (read) 8)}} \python{\code{input\_int() * 8}} is not in \LangInt{}
  747. because there is no rule for the \key{*} operator. Whenever we
  748. define a language with a grammar, the language only includes those
  749. programs that are justified by the grammar rules.
  750. {\if\edition\pythonEd
  751. The language \LangInt{} includes a second non-terminal $\Stmt$ for statements.
  752. There is a statement for printing the value of an expression
  753. \[
  754. \Stmt{} ::= \PRINT{\Exp}
  755. \]
  756. and a statement that evaluates an expression but ignores the result.
  757. \[
  758. \Stmt{} ::= \EXPR{\Exp}
  759. \]
  760. \fi}
  761. {\if\edition\racketEd
  762. The last grammar rule for \LangInt{} states that there is a
  763. \code{Program} node to mark the top of the whole program:
  764. \[
  765. \LangInt{} ::= \PROGRAM{\code{'()}}{\Exp}
  766. \]
  767. The \code{Program} structure is defined as follows
  768. \begin{lstlisting}
  769. (struct Program (info body))
  770. \end{lstlisting}
  771. where \code{body} is an expression. In later chapters, the \code{info}
  772. part will be used to store auxiliary information but for now it is
  773. just the empty list.
  774. \fi}
  775. {\if\edition\pythonEd
  776. The last grammar rule for \LangInt{} states that there is a
  777. \code{Module} node to mark the top of the whole program:
  778. \[
  779. \LangInt{} ::= \PROGRAM{}{\Stmt^{*}}
  780. \]
  781. The asterisk symbol $*$ indicates a list of the preceding grammar item, in
  782. this case, a list of statements.
  783. %
  784. The \code{Module} class is defined as follows
  785. \begin{lstlisting}
  786. class Module:
  787. def __init__(self, body):
  788. self.body = body
  789. \end{lstlisting}
  790. where \code{body} is a list of statements.
  791. \fi}
  792. It is common to have many grammar rules with the same left-hand side
  793. but different right-hand sides, such as the rules for $\Exp$ in the
  794. grammar of \LangInt{}. As a short-hand, a vertical bar can be used to
  795. combine several right-hand-sides into a single rule.
  796. We collect all of the grammar rules for the abstract syntax of \LangInt{}
  797. in Figure~\ref{fig:r0-syntax}. The concrete syntax for \LangInt{} is
  798. defined in Figure~\ref{fig:r0-concrete-syntax}.
  799. \racket{The \code{read-program} function provided in
  800. \code{utilities.rkt} of the support code reads a program in from a
  801. file (the sequence of characters in the concrete syntax of Racket)
  802. and parses it into an abstract syntax tree. See the description of
  803. \code{read-program} in Appendix~\ref{appendix:utilities} for more
  804. details.}
  805. \python{The \code{parse} function in Python's \code{ast} module
  806. converts the concrete syntax (represented as a string) into an
  807. abstract syntax tree.}
  808. \newcommand{\LintGrammarRacket}{
  809. \begin{array}{rcl}
  810. \Type &::=& \key{Integer} \\
  811. \Exp{} &::=& \Int{} \MID \CREAD \RP \MID \CNEG{\Exp} \MID \CADD{\Exp}{\Exp}
  812. \MID \CSUB{\Exp}{\Exp}
  813. \end{array}
  814. }
  815. \newcommand{\LintASTRacket}{
  816. \begin{array}{rcl}
  817. \Type &::=& \key{Integer} \\
  818. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  819. &\MID& \NEG{\Exp} \MID \ADD{\Exp}{\Exp} \MID \SUB{\Exp}{\Exp}
  820. \end{array}
  821. }
  822. \newcommand{\LintGrammarPython}{
  823. \begin{array}{rcl}
  824. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  825. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  826. \end{array}
  827. }
  828. \newcommand{\LintASTPython}{
  829. \begin{array}{rcl}
  830. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  831. \itm{unaryop} &::= & \code{USub()} \\
  832. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  833. &\MID& \UNIOP{\itm{unaryop}}{\Exp} \MID \BINOP{\itm{binaryop}}{\Exp}{\Exp} \\
  834. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp}
  835. \end{array}
  836. }
  837. \begin{figure}[tp]
  838. \fbox{
  839. \begin{minipage}{0.96\textwidth}
  840. {\if\edition\racketEd
  841. \[
  842. \begin{array}{l}
  843. \LintGrammarRacket \\
  844. \begin{array}{rcl}
  845. \LangInt{} &::=& \Exp
  846. \end{array}
  847. \end{array}
  848. \]
  849. \fi}
  850. {\if\edition\pythonEd
  851. \[
  852. \begin{array}{l}
  853. \LintGrammarPython \\
  854. \begin{array}{rcl}
  855. \LangInt{} &::=& \Stmt^{*}
  856. \end{array}
  857. \end{array}
  858. \]
  859. \fi}
  860. \end{minipage}
  861. }
  862. \caption{The concrete syntax of \LangInt{}.}
  863. \label{fig:r0-concrete-syntax}
  864. \end{figure}
  865. \begin{figure}[tp]
  866. \fbox{
  867. \begin{minipage}{0.96\textwidth}
  868. {\if\edition\racketEd
  869. \[
  870. \begin{array}{l}
  871. \LintASTRacket{} \\
  872. \begin{array}{rcl}
  873. \LangInt{} &::=& \PROGRAM{\code{'()}}{\Exp}
  874. \end{array}
  875. \end{array}
  876. \]
  877. \fi}
  878. {\if\edition\pythonEd
  879. \[
  880. \begin{array}{l}
  881. \LintASTPython\\
  882. \begin{array}{rcl}
  883. \LangInt{} &::=& \PROGRAM{}{\Stmt^{*}}
  884. \end{array}
  885. \end{array}
  886. \]
  887. \fi}
  888. \end{minipage}
  889. }
  890. \caption{The abstract syntax of \LangInt{}.}
  891. \label{fig:r0-syntax}
  892. \end{figure}
  893. \section{Pattern Matching}
  894. \label{sec:pattern-matching}
  895. As mentioned in Section~\ref{sec:ast}, compilers often need to access
  896. the parts of an AST node. \racket{Racket}\python{As of version 3.10, Python} provides the
  897. \texttt{match} feature to access the parts of a value.
  898. Consider the following example. \index{subject}{match} \index{subject}{pattern matching}
  899. \begin{center}
  900. \begin{minipage}{0.5\textwidth}
  901. {\if\edition\racketEd
  902. \begin{lstlisting}
  903. (match ast1_1
  904. [(Prim op (list child1 child2))
  905. (print op)])
  906. \end{lstlisting}
  907. \fi}
  908. {\if\edition\pythonEd
  909. \begin{lstlisting}
  910. match ast1_1:
  911. case BinOp(child1, op, child2):
  912. print(op)
  913. \end{lstlisting}
  914. \fi}
  915. \end{minipage}
  916. \end{center}
  917. {\if\edition\racketEd
  918. %
  919. In the above example, the \texttt{match} form checks whether the AST
  920. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  921. three pattern variables \texttt{op}, \texttt{child1}, and
  922. \texttt{child2}. In general, a match clause consists of a
  923. \emph{pattern} and a \emph{body}.\index{subject}{pattern} Patterns are
  924. recursively defined to be either a pattern variable, a structure name
  925. followed by a pattern for each of the structure's arguments, or an
  926. S-expression (symbols, lists, etc.). (See Chapter 12 of The Racket
  927. Guide\footnote{\url{https://docs.racket-lang.org/guide/match.html}}
  928. and Chapter 9 of The Racket
  929. Reference\footnote{\url{https://docs.racket-lang.org/reference/match.html}}
  930. for complete descriptions of \code{match}.)
  931. %
  932. The body of a match clause may contain arbitrary Racket code. The
  933. pattern variables can be used in the scope of the body, such as
  934. \code{op} in \code{(print op)}.
  935. %
  936. \fi}
  937. %
  938. %
  939. {\if\edition\pythonEd
  940. %
  941. In the above example, the \texttt{match} form checks whether the AST
  942. \eqref{eq:arith-prog} is a binary operator and binds its parts to the
  943. three pattern variables \texttt{child1}, \texttt{op}, and
  944. \texttt{child2}, and then prints out the operator. In general, each
  945. \code{case} consists of a \emph{pattern} and a
  946. \emph{body}.\index{subject}{pattern} Patterns are recursively defined
  947. to be either a pattern variable, a class name followed by a pattern
  948. for each of its constructor's arguments, or other literals such as
  949. strings, lists, etc.
  950. %
  951. The body of each \code{case} may contain arbitrary Python code. The
  952. pattern variables can be used in the body, such as \code{op} in
  953. \code{print(op)}.
  954. %
  955. \fi}
  956. A \code{match} form may contain several clauses, as in the following
  957. function \code{leaf} that recognizes when an \LangInt{} node is a leaf in
  958. the AST. The \code{match} proceeds through the clauses in order,
  959. checking whether the pattern can match the input AST. The body of the
  960. first clause that matches is executed. The output of \code{leaf} for
  961. several ASTs is shown on the right.
  962. \begin{center}
  963. \begin{minipage}{0.6\textwidth}
  964. {\if\edition\racketEd
  965. \begin{lstlisting}
  966. (define (leaf arith)
  967. (match arith
  968. [(Int n) #t]
  969. [(Prim 'read '()) #t]
  970. [(Prim '- (list e1)) #f]
  971. [(Prim '+ (list e1 e2)) #f]
  972. [(Prim '- (list e1 e2)) #f]))
  973. (leaf (Prim 'read '()))
  974. (leaf (Prim '- (list (Int 8))))
  975. (leaf (Int 8))
  976. \end{lstlisting}
  977. \fi}
  978. {\if\edition\pythonEd
  979. \begin{lstlisting}
  980. def leaf(arith):
  981. match arith:
  982. case Constant(n):
  983. return True
  984. case Call(Name('input_int'), []):
  985. return True
  986. case UnaryOp(USub(), e1):
  987. return False
  988. case BinOp(e1, Add(), e2):
  989. return False
  990. case BinOp(e1, Sub(), e2):
  991. return False
  992. print(leaf(Call(Name('input_int'), [])))
  993. print(leaf(UnaryOp(USub(), eight)))
  994. print(leaf(Constant(8)))
  995. \end{lstlisting}
  996. \fi}
  997. \end{minipage}
  998. \vrule
  999. \begin{minipage}{0.25\textwidth}
  1000. {\if\edition\racketEd
  1001. \begin{lstlisting}
  1002. #t
  1003. #f
  1004. #t
  1005. \end{lstlisting}
  1006. \fi}
  1007. {\if\edition\pythonEd
  1008. \begin{lstlisting}
  1009. True
  1010. False
  1011. True
  1012. \end{lstlisting}
  1013. \fi}
  1014. \end{minipage}
  1015. \end{center}
  1016. When constructing a \code{match} expression, we refer to the grammar
  1017. definition to identify which non-terminal we are expecting to match
  1018. against, then we make sure that 1) we have one
  1019. \racket{clause}\python{case} for each alternative of that non-terminal
  1020. and 2) that the pattern in each \racket{clause}\python{case}
  1021. corresponds to the corresponding right-hand side of a grammar
  1022. rule. For the \code{match} in the \code{leaf} function, we refer to
  1023. the grammar for \LangInt{} in Figure~\ref{fig:r0-syntax}. The $\Exp$
  1024. non-terminal has 4 alternatives, so the \code{match} has 4
  1025. \racket{clauses}\python{cases}. The pattern in each
  1026. \racket{clause}\python{case} corresponds to the right-hand side of a
  1027. grammar rule. For example, the pattern \ADDP{\code{e1}}{\code{e2}}
  1028. corresponds to the right-hand side $\ADD{\Exp}{\Exp}$. When
  1029. translating from grammars to patterns, replace non-terminals such as
  1030. $\Exp$ with pattern variables of your choice (e.g. \code{e1} and
  1031. \code{e2}).
  1032. \section{Recursive Functions}
  1033. \label{sec:recursion}
  1034. \index{subject}{recursive function}
  1035. Programs are inherently recursive. For example, an expression is often
  1036. made of smaller expressions. Thus, the natural way to process an
  1037. entire program is with a recursive function. As a first example of
  1038. such a recursive function, we define the function \code{is\_exp} in
  1039. Figure~\ref{fig:exp-predicate}, which takes an arbitrary value and
  1040. determines whether or not it is an expression in \LangInt{}.
  1041. %
  1042. We say that a function is defined by \emph{structural recursion} when
  1043. it is defined using a sequence of match \racket{clauses}\python{cases}
  1044. that correspond to a grammar, and the body of each
  1045. \racket{clause}\python{case} makes a recursive call on each child
  1046. node.\footnote{This principle of structuring code according to the
  1047. data definition is advocated in the book \emph{How to Design
  1048. Programs} by \citet{Felleisen:2001aa}.} \python{We define a
  1049. second function, named \code{stmt}, that recognizes whether a value
  1050. is a \LangInt{} statement.} \python{Finally, }
  1051. Figure~\ref{fig:exp-predicate} \racket{also} defines \code{is\_Lint},
  1052. which determines whether an AST is a program in \LangInt{}. In
  1053. general we can write one recursive function to handle each
  1054. non-terminal in a grammar.\index{subject}{structural recursion} Of the
  1055. two examples at the bottom of the figure, the first is in
  1056. \LangInt{} and the second is not.
  1057. \begin{figure}[tp]
  1058. {\if\edition\racketEd
  1059. \begin{lstlisting}
  1060. (define (is_exp ast)
  1061. (match ast
  1062. [(Int n) #t]
  1063. [(Prim 'read '()) #t]
  1064. [(Prim '- (list e)) (is_exp e)]
  1065. [(Prim '+ (list e1 e2))
  1066. (and (is_exp e1) (is_exp e2))]
  1067. [(Prim '- (list e1 e2))
  1068. (and (is_exp e1) (is_exp e2))]
  1069. [else #f]))
  1070. (define (is_Lint ast)
  1071. (match ast
  1072. [(Program '() e) (is_exp e)]
  1073. [else #f]))
  1074. (is_Lint (Program '() ast1_1)
  1075. (is_Lint (Program '()
  1076. (Prim '* (list (Prim 'read '())
  1077. (Prim '+ (list (Int 8)))))))
  1078. \end{lstlisting}
  1079. \fi}
  1080. {\if\edition\pythonEd
  1081. \begin{lstlisting}
  1082. def is_exp(e):
  1083. match e:
  1084. case Constant(n):
  1085. return True
  1086. case Call(Name('input_int'), []):
  1087. return True
  1088. case UnaryOp(USub(), e1):
  1089. return is_exp(e1)
  1090. case BinOp(e1, Add(), e2):
  1091. return is_exp(e1) and is_exp(e2)
  1092. case BinOp(e1, Sub(), e2):
  1093. return is_exp(e1) and is_exp(e2)
  1094. case _:
  1095. return False
  1096. def stmt(s):
  1097. match s:
  1098. case Expr(Call(Name('print'), [e])):
  1099. return is_exp(e)
  1100. case Expr(e):
  1101. return is_exp(e)
  1102. case _:
  1103. return False
  1104. def is_Lint(p):
  1105. match p:
  1106. case Module(body):
  1107. return all([stmt(s) for s in body])
  1108. case _:
  1109. return False
  1110. print(is_Lint(Module([Expr(ast1_1)])))
  1111. print(is_Lint(Module([Expr(BinOp(read, Sub(),
  1112. UnaryOp(Add(), Constant(8))))])))
  1113. \end{lstlisting}
  1114. \fi}
  1115. \caption{Example of recursive functions for \LangInt{}. These functions
  1116. recognize whether an AST is in \LangInt{}.}
  1117. \label{fig:exp-predicate}
  1118. \end{figure}
  1119. %% You may be tempted to merge the two functions into one, like this:
  1120. %% \begin{center}
  1121. %% \begin{minipage}{0.5\textwidth}
  1122. %% \begin{lstlisting}
  1123. %% (define (Lint ast)
  1124. %% (match ast
  1125. %% [(Int n) #t]
  1126. %% [(Prim 'read '()) #t]
  1127. %% [(Prim '- (list e)) (Lint e)]
  1128. %% [(Prim '+ (list e1 e2)) (and (Lint e1) (Lint e2))]
  1129. %% [(Program '() e) (Lint e)]
  1130. %% [else #f]))
  1131. %% \end{lstlisting}
  1132. %% \end{minipage}
  1133. %% \end{center}
  1134. %% %
  1135. %% Sometimes such a trick will save a few lines of code, especially when
  1136. %% it comes to the \code{Program} wrapper. Yet this style is generally
  1137. %% \emph{not} recommended because it can get you into trouble.
  1138. %% %
  1139. %% For example, the above function is subtly wrong:
  1140. %% \lstinline{(Lint (Program '() (Program '() (Int 3))))}
  1141. %% returns true when it should return false.
  1142. \section{Interpreters}
  1143. \label{sec:interp_Lint}
  1144. \index{subject}{interpreter}
  1145. The behavior of a program is defined by the specification of the
  1146. programming language.
  1147. %
  1148. \racket{For example, the Scheme language is defined in the report by
  1149. \cite{SPERBER:2009aa}. The Racket language is defined in its
  1150. reference manual~\citep{plt-tr}.}
  1151. %
  1152. \python{For example, the Python language is defined in the Python
  1153. Language Reference~\citep{PSF21:python_ref} and the CPython interpreter~\citep{PSF21:cpython}.}
  1154. %
  1155. In this book we use interpreters to specify each language that we
  1156. consider. An interpreter that is designated as the definition of a
  1157. language is called a \emph{definitional
  1158. interpreter}~\citep{reynolds72:_def_interp}.
  1159. \index{subject}{definitional interpreter} We warm up by creating a
  1160. definitional interpreter for the \LangInt{} language. This interpreter
  1161. serves as a second example of structural recursion. The
  1162. \code{interp\_Lint} function is defined in
  1163. Figure~\ref{fig:interp_Lint}.
  1164. %
  1165. \racket{The body of the function is a match on the input program
  1166. followed by a call to the \lstinline{interp_exp} helper function,
  1167. which in turn has one match clause per grammar rule for \LangInt{}
  1168. expressions.}
  1169. %
  1170. \python{The body of the function matches on the \code{Module} AST node
  1171. and then invokes \code{interp\_stmt} on each statement in the
  1172. module. The \code{interp\_stmt} function includes a case for each
  1173. grammar rule of the \Stmt{} non-terminal and it calls
  1174. \code{interp\_exp} on each subexpression. The \code{interp\_exp}
  1175. function includes a case for each grammar rule of the \Exp{}
  1176. non-terminal.}
  1177. \begin{figure}[tp]
  1178. {\if\edition\racketEd
  1179. \begin{lstlisting}
  1180. (define (interp_exp e)
  1181. (match e
  1182. [(Int n) n]
  1183. [(Prim 'read '())
  1184. (define r (read))
  1185. (cond [(fixnum? r) r]
  1186. [else (error 'interp_exp "read expected an integer" r)])]
  1187. [(Prim '- (list e))
  1188. (define v (interp_exp e))
  1189. (fx- 0 v)]
  1190. [(Prim '+ (list e1 e2))
  1191. (define v1 (interp_exp e1))
  1192. (define v2 (interp_exp e2))
  1193. (fx+ v1 v2)]
  1194. [(Prim '- (list e1 e2))
  1195. (define v1 ((interp-exp env) e1))
  1196. (define v2 ((interp-exp env) e2))
  1197. (fx- v1 v2)]))
  1198. (define (interp_Lint p)
  1199. (match p
  1200. [(Program '() e) (interp_exp e)]))
  1201. \end{lstlisting}
  1202. \fi}
  1203. {\if\edition\pythonEd
  1204. \begin{lstlisting}
  1205. def interp_exp(e):
  1206. match e:
  1207. case BinOp(left, Add(), right):
  1208. l = interp_exp(left); r = interp_exp(right)
  1209. return l + r
  1210. case BinOp(left, Sub(), right):
  1211. l = interp_exp(left); r = interp_exp(right)
  1212. return l - r
  1213. case UnaryOp(USub(), v):
  1214. return - interp_exp(v)
  1215. case Constant(value):
  1216. return value
  1217. case Call(Name('input_int'), []):
  1218. return int(input())
  1219. def interp_stmt(s):
  1220. match s:
  1221. case Expr(Call(Name('print'), [arg])):
  1222. print(interp_exp(arg))
  1223. case Expr(value):
  1224. interp_exp(value)
  1225. def interp_Lint(p):
  1226. match p:
  1227. case Module(body):
  1228. for s in body:
  1229. interp_stmt(s)
  1230. \end{lstlisting}
  1231. \fi}
  1232. \caption{Interpreter for the \LangInt{} language.}
  1233. \label{fig:interp_Lint}
  1234. \end{figure}
  1235. Let us consider the result of interpreting a few \LangInt{} programs. The
  1236. following program adds two integers.
  1237. {\if\edition\racketEd
  1238. \begin{lstlisting}
  1239. (+ 10 32)
  1240. \end{lstlisting}
  1241. \fi}
  1242. {\if\edition\pythonEd
  1243. \begin{lstlisting}
  1244. print(10 + 32)
  1245. \end{lstlisting}
  1246. \fi}
  1247. %
  1248. \noindent The result is \key{42}, the answer to life, the universe,
  1249. and everything: \code{42}!\footnote{\emph{The Hitchhiker's Guide to
  1250. the Galaxy} by Douglas Adams.}
  1251. %
  1252. We wrote the above program in concrete syntax whereas the parsed
  1253. abstract syntax is:
  1254. {\if\edition\racketEd
  1255. \begin{lstlisting}
  1256. (Program '() (Prim '+ (list (Int 10) (Int 32))))
  1257. \end{lstlisting}
  1258. \fi}
  1259. {\if\edition\pythonEd
  1260. \begin{lstlisting}
  1261. Module([Expr(Call(Name('print'), [BinOp(Constant(10), Add(), Constant(32))]))])
  1262. \end{lstlisting}
  1263. \fi}
  1264. The next example demonstrates that expressions may be nested within
  1265. each other, in this case nesting several additions and negations.
  1266. {\if\edition\racketEd
  1267. \begin{lstlisting}
  1268. (+ 10 (- (+ 12 20)))
  1269. \end{lstlisting}
  1270. \fi}
  1271. {\if\edition\pythonEd
  1272. \begin{lstlisting}
  1273. print(10 + -(12 + 20))
  1274. \end{lstlisting}
  1275. \fi}
  1276. %
  1277. \noindent What is the result of the above program?
  1278. {\if\edition\racketEd
  1279. As mentioned previously, the \LangInt{} language does not support
  1280. arbitrarily-large integers, but only $63$-bit integers, so we
  1281. interpret the arithmetic operations of \LangInt{} using fixnum arithmetic
  1282. in Racket.
  1283. Suppose
  1284. \[
  1285. n = 999999999999999999
  1286. \]
  1287. which indeed fits in $63$-bits. What happens when we run the
  1288. following program in our interpreter?
  1289. \begin{lstlisting}
  1290. (+ (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)) (+ (+ |$n$| |$n$|) (+ |$n$| |$n$|)))))
  1291. \end{lstlisting}
  1292. It produces an error:
  1293. \begin{lstlisting}
  1294. fx+: result is not a fixnum
  1295. \end{lstlisting}
  1296. We establish the convention that if running the definitional
  1297. interpreter on a program produces an error then the meaning of that
  1298. program is \emph{unspecified}\index{subject}{unspecified behavior}, unless the
  1299. error is a \code{trapped-error}. A compiler for the language is under
  1300. no obligations regarding programs with unspecified behavior; it does
  1301. not have to produce an executable, and if it does, that executable can
  1302. do anything. On the other hand, if the error is a
  1303. \code{trapped-error}, then the compiler must produce an executable and
  1304. it is required to report that an error occurred. To signal an error,
  1305. exit with a return code of \code{255}. The interpreters in chapters
  1306. \ref{ch:Ldyn} and \ref{ch:Lgrad} use
  1307. \code{trapped-error}.
  1308. \fi}
  1309. % TODO: how to deal with too-large integers in the Python interpreter?
  1310. %% This convention applies to the languages defined in this
  1311. %% book, as a way to simplify the student's task of implementing them,
  1312. %% but this convention is not applicable to all programming languages.
  1313. %%
  1314. Moving on to the last feature of the \LangInt{} language, the
  1315. \READOP{} operation prompts the user of the program for an integer.
  1316. Recall that program \eqref{eq:arith-prog} requests an integer input
  1317. and then subtracts \code{8}. So if we run
  1318. {\if\edition\racketEd
  1319. \begin{lstlisting}
  1320. (interp_Lint (Program '() ast1_1))
  1321. \end{lstlisting}
  1322. \fi}
  1323. {\if\edition\pythonEd
  1324. \begin{lstlisting}
  1325. interp_Lint(Module([Expr(Call(Name('print'), [ast1_1]))]))
  1326. \end{lstlisting}
  1327. \fi}
  1328. \noindent and if the input is \code{50}, the result is \code{42}.
  1329. We include the \READOP{} operation in \LangInt{} so a clever student
  1330. cannot implement a compiler for \LangInt{} that simply runs the interpreter
  1331. during compilation to obtain the output and then generates the trivial
  1332. code to produce the output.\footnote{Yes, a clever student did this in the
  1333. first instance of this course!}
  1334. The job of a compiler is to translate a program in one language into a
  1335. program in another language so that the output program behaves the
  1336. same way as the input program. This idea is depicted in the
  1337. following diagram. Suppose we have two languages, $\mathcal{L}_1$ and
  1338. $\mathcal{L}_2$, and a definitional interpreter for each language.
  1339. Given a compiler that translates from language $\mathcal{L}_1$ to
  1340. $\mathcal{L}_2$ and given any program $P_1$ in $\mathcal{L}_1$, the
  1341. compiler must translate it into some program $P_2$ such that
  1342. interpreting $P_1$ and $P_2$ on their respective interpreters with
  1343. same input $i$ yields the same output $o$.
  1344. \begin{equation} \label{eq:compile-correct}
  1345. \begin{tikzpicture}[baseline=(current bounding box.center)]
  1346. \node (p1) at (0, 0) {$P_1$};
  1347. \node (p2) at (3, 0) {$P_2$};
  1348. \node (o) at (3, -2.5) {$o$};
  1349. \path[->] (p1) edge [above] node {compile} (p2);
  1350. \path[->] (p2) edge [right] node {interp\_$\mathcal{L}_2$($i$)} (o);
  1351. \path[->] (p1) edge [left] node {interp\_$\mathcal{L}_1$($i$)} (o);
  1352. \end{tikzpicture}
  1353. \end{equation}
  1354. In the next section we see our first example of a compiler.
  1355. \section{Example Compiler: a Partial Evaluator}
  1356. \label{sec:partial-evaluation}
  1357. In this section we consider a compiler that translates \LangInt{}
  1358. programs into \LangInt{} programs that may be more efficient. The
  1359. compiler eagerly computes the parts of the program that do not depend
  1360. on any inputs, a process known as \emph{partial
  1361. evaluation}~\citep{Jones:1993uq}. \index{subject}{partial evaluation}
  1362. For example, given the following program
  1363. {\if\edition\racketEd
  1364. \begin{lstlisting}
  1365. (+ (read) (- (+ 5 3)))
  1366. \end{lstlisting}
  1367. \fi}
  1368. {\if\edition\pythonEd
  1369. \begin{lstlisting}
  1370. print(input_int() + -(5 + 3) )
  1371. \end{lstlisting}
  1372. \fi}
  1373. \noindent our compiler translates it into the program
  1374. {\if\edition\racketEd
  1375. \begin{lstlisting}
  1376. (+ (read) -8)
  1377. \end{lstlisting}
  1378. \fi}
  1379. {\if\edition\pythonEd
  1380. \begin{lstlisting}
  1381. print(input_int() + -8)
  1382. \end{lstlisting}
  1383. \fi}
  1384. Figure~\ref{fig:pe-arith} gives the code for a simple partial
  1385. evaluator for the \LangInt{} language. The output of the partial evaluator
  1386. is a program in \LangInt{}. In Figure~\ref{fig:pe-arith}, the structural
  1387. recursion over $\Exp$ is captured in the \code{pe\_exp} function
  1388. whereas the code for partially evaluating the negation and addition
  1389. operations is factored into three auxiliary functions:
  1390. \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub}. The input to these
  1391. functions is the output of partially evaluating the children.
  1392. The \code{pe\_neg}, \code{pe\_add} and \code{pe\_sub} functions check whether their
  1393. arguments are integers and if they are, perform the appropriate
  1394. arithmetic. Otherwise, they create an AST node for the arithmetic
  1395. operation.
  1396. \begin{figure}[tp]
  1397. {\if\edition\racketEd
  1398. \begin{lstlisting}
  1399. (define (pe_neg r)
  1400. (match r
  1401. [(Int n) (Int (fx- 0 n))]
  1402. [else (Prim '- (list r))]))
  1403. (define (pe_add r1 r2)
  1404. (match* (r1 r2)
  1405. [((Int n1) (Int n2)) (Int (fx+ n1 n2))]
  1406. [(_ _) (Prim '+ (list r1 r2))]))
  1407. (define (pe_sub r1 r2)
  1408. (match* (r1 r2)
  1409. [((Int n1) (Int n2)) (Int (fx- n1 n2))]
  1410. [(_ _) (Prim '- (list r1 r2))]))
  1411. (define (pe_exp e)
  1412. (match e
  1413. [(Int n) (Int n)]
  1414. [(Prim 'read '()) (Prim 'read '())]
  1415. [(Prim '- (list e1)) (pe_neg (pe_exp e1))]
  1416. [(Prim '+ (list e1 e2)) (pe_add (pe_exp e1) (pe_exp e2))]
  1417. [(Prim '- (list e1 e2)) (pe_sub (pe_exp e1) (pe_exp e2))]))
  1418. (define (pe_Lint p)
  1419. (match p
  1420. [(Program '() e) (Program '() (pe_exp e))]))
  1421. \end{lstlisting}
  1422. \fi}
  1423. {\if\edition\pythonEd
  1424. \begin{lstlisting}
  1425. def pe_neg(r):
  1426. match r:
  1427. case Constant(n):
  1428. return Constant(-n)
  1429. case _:
  1430. return UnaryOp(USub(), r)
  1431. def pe_add(r1, r2):
  1432. match (r1, r2):
  1433. case (Constant(n1), Constant(n2)):
  1434. return Constant(n1 + n2)
  1435. case _:
  1436. return BinOp(r1, Add(), r2)
  1437. def pe_sub(r1, r2):
  1438. match (r1, r2):
  1439. case (Constant(n1), Constant(n2)):
  1440. return Constant(n1 - n2)
  1441. case _:
  1442. return BinOp(r1, Sub(), r2)
  1443. def pe_exp(e):
  1444. match e:
  1445. case BinOp(left, Add(), right):
  1446. return pe_add(pe_exp(left), pe_exp(right))
  1447. case BinOp(left, Sub(), right):
  1448. return pe_sub(pe_exp(left), pe_exp(right))
  1449. case UnaryOp(USub(), v):
  1450. return pe_neg(pe_exp(v))
  1451. case Constant(value):
  1452. return e
  1453. case Call(Name('input_int'), []):
  1454. return e
  1455. def pe_stmt(s):
  1456. match s:
  1457. case Expr(Call(Name('print'), [arg])):
  1458. return Expr(Call(Name('print'), [pe_exp(arg)]))
  1459. case Expr(value):
  1460. return Expr(pe_exp(value))
  1461. def pe_P_int(p):
  1462. match p:
  1463. case Module(body):
  1464. new_body = [pe_stmt(s) for s in body]
  1465. return Module(new_body)
  1466. \end{lstlisting}
  1467. \fi}
  1468. \caption{A partial evaluator for \LangInt{}.}
  1469. \label{fig:pe-arith}
  1470. \end{figure}
  1471. To gain some confidence that the partial evaluator is correct, we can
  1472. test whether it produces programs that produce the same result as the
  1473. input programs. That is, we can test whether it satisfies Diagram
  1474. \ref{eq:compile-correct}.
  1475. %
  1476. {\if\edition\racketEd
  1477. The following code runs the partial evaluator on several examples and
  1478. tests the output program. The \texttt{parse-program} and
  1479. \texttt{assert} functions are defined in
  1480. Appendix~\ref{appendix:utilities}.\\
  1481. \begin{minipage}{1.0\textwidth}
  1482. \begin{lstlisting}
  1483. (define (test_pe p)
  1484. (assert "testing pe_Lint"
  1485. (equal? (interp_Lint p) (interp_Lint (pe_Lint p)))))
  1486. (test_pe (parse-program `(program () (+ 10 (- (+ 5 3))))))
  1487. (test_pe (parse-program `(program () (+ 1 (+ 3 1)))))
  1488. (test_pe (parse-program `(program () (- (+ 3 (- 5))))))
  1489. \end{lstlisting}
  1490. \end{minipage}
  1491. \fi}
  1492. % TODO: python version of testing the PE
  1493. \begin{exercise}\normalfont\normalsize
  1494. Create three programs in the \LangInt{} language and test whether
  1495. partially evaluating them with \code{pe\_Lint} and then
  1496. interpreting them with \code{interp\_Lint} gives the same result
  1497. as directly interpreting them with \code{interp\_Lint}.
  1498. \end{exercise}
  1499. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1500. \chapter{Integers and Variables}
  1501. \label{ch:Lvar}
  1502. This chapter is about compiling a subset of
  1503. \racket{Racket}\python{Python} to x86-64 assembly
  1504. code~\citep{Intel:2015aa}. The subset, named \LangVar{}, includes
  1505. integer arithmetic and local variables. We often refer to x86-64
  1506. simply as x86. The chapter begins with a description of the
  1507. \LangVar{} language (Section~\ref{sec:s0}) followed by an introduction
  1508. to x86 assembly (Section~\ref{sec:x86}). The x86 assembly language is
  1509. large so we discuss only the instructions needed for compiling
  1510. \LangVar{}. We introduce more x86 instructions in later chapters.
  1511. After introducing \LangVar{} and x86, we reflect on their differences
  1512. and come up with a plan to break down the translation from \LangVar{}
  1513. to x86 into a handful of steps (Section~\ref{sec:plan-s0-x86}). The
  1514. rest of the sections in this chapter give detailed hints regarding
  1515. each step. We hope to give enough hints that the well-prepared
  1516. reader, together with a few friends, can implement a compiler from
  1517. \LangVar{} to x86 in a short time. To give the reader a feeling for
  1518. the scale of this first compiler, the instructor solution for the
  1519. \LangVar{} compiler is approximately \racket{500}\python{300} lines of
  1520. code.
  1521. \section{The \LangVar{} Language}
  1522. \label{sec:s0}
  1523. \index{subject}{variable}
  1524. The \LangVar{} language extends the \LangInt{} language with
  1525. variables. The concrete syntax of the \LangVar{} language is defined
  1526. by the grammar in Figure~\ref{fig:Lvar-concrete-syntax} and the
  1527. abstract syntax is defined in Figure~\ref{fig:Lvar-syntax}. The
  1528. non-terminal \Var{} may be any \racket{Racket}\python{Python} identifier.
  1529. As in \LangInt{}, \READOP{} is a nullary operator, \key{-} is a unary operator, and
  1530. \key{+} is a binary operator. Similar to \LangInt{}, the abstract
  1531. syntax of \LangVar{} includes the \racket{\key{Program}
  1532. struct}\python{\key{Module} instance} to mark the top of the
  1533. program.
  1534. %% The $\itm{info}$
  1535. %% field of the \key{Program} structure contains an \emph{association
  1536. %% list} (a list of key-value pairs) that is used to communicate
  1537. %% auxiliary data from one compiler pass the next.
  1538. Despite the simplicity of the \LangVar{} language, it is rich enough to
  1539. exhibit several compilation techniques.
  1540. \newcommand{\LvarGrammarRacket}{
  1541. \begin{array}{rcl}
  1542. \Exp &::=& \Var \MID \CLET{\Var}{\Exp}{\Exp}
  1543. \end{array}
  1544. }
  1545. \newcommand{\LvarASTRacket}{
  1546. \begin{array}{rcl}
  1547. \Exp &::=& \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp}
  1548. \end{array}
  1549. }
  1550. \newcommand{\LvarGrammarPython}{
  1551. \begin{array}{rcl}
  1552. \Exp &::=& \Var{} \\
  1553. \Stmt &::=& \Var\mathop{\key{=}}\Exp
  1554. \end{array}
  1555. }
  1556. \newcommand{\LvarASTPython}{
  1557. \begin{array}{rcl}
  1558. \Exp{} &::=& \VAR{\Var{}} \\
  1559. \Stmt{} &::=& \ASSIGN{\VAR{\Var}}{\Exp}
  1560. \end{array}
  1561. }
  1562. \begin{figure}[tp]
  1563. \centering
  1564. \fbox{
  1565. \begin{minipage}{0.96\textwidth}
  1566. {\if\edition\racketEd
  1567. \[
  1568. \begin{array}{l}
  1569. \gray{\LintGrammarRacket{}} \\ \hline
  1570. \LvarGrammarRacket{} \\
  1571. \begin{array}{rcl}
  1572. \LangVarM{} &::=& \Exp
  1573. \end{array}
  1574. \end{array}
  1575. \]
  1576. \fi}
  1577. {\if\edition\pythonEd
  1578. \[
  1579. \begin{array}{l}
  1580. \gray{\LintGrammarPython} \\ \hline
  1581. \LvarGrammarPython \\
  1582. \begin{array}{rcl}
  1583. \LangVarM{} &::=& \Stmt^{*}
  1584. \end{array}
  1585. \end{array}
  1586. \]
  1587. \fi}
  1588. \end{minipage}
  1589. }
  1590. \caption{The concrete syntax of \LangVar{}.}
  1591. \label{fig:Lvar-concrete-syntax}
  1592. \end{figure}
  1593. \begin{figure}[tp]
  1594. \centering
  1595. \fbox{
  1596. \begin{minipage}{0.96\textwidth}
  1597. {\if\edition\racketEd
  1598. \[
  1599. \begin{array}{l}
  1600. \gray{\LintASTRacket{}} \\ \hline
  1601. \LvarASTRacket \\
  1602. \begin{array}{rcl}
  1603. \LangVarM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  1604. \end{array}
  1605. \end{array}
  1606. \]
  1607. \fi}
  1608. {\if\edition\pythonEd
  1609. \[
  1610. \begin{array}{l}
  1611. \gray{\LintASTPython}\\ \hline
  1612. \LvarASTPython \\
  1613. \begin{array}{rcl}
  1614. \LangVarM{} &::=& \PROGRAM{}{\Stmt^{*}}
  1615. \end{array}
  1616. \end{array}
  1617. \]
  1618. \fi}
  1619. \end{minipage}
  1620. }
  1621. \caption{The abstract syntax of \LangVar{}.}
  1622. \label{fig:Lvar-syntax}
  1623. \end{figure}
  1624. {\if\edition\racketEd
  1625. Let us dive further into the syntax and semantics of the \LangVar{}
  1626. language. The \key{let} feature defines a variable for use within its
  1627. body and initializes the variable with the value of an expression.
  1628. The abstract syntax for \key{let} is defined in
  1629. Figure~\ref{fig:Lvar-syntax}. The concrete syntax for \key{let} is
  1630. \begin{lstlisting}
  1631. (let ([|$\itm{var}$| |$\itm{exp}$|]) |$\itm{exp}$|)
  1632. \end{lstlisting}
  1633. For example, the following program initializes \code{x} to $32$ and then
  1634. evaluates the body \code{(+ 10 x)}, producing $42$.
  1635. \begin{lstlisting}
  1636. (let ([x (+ 12 20)]) (+ 10 x))
  1637. \end{lstlisting}
  1638. \fi}
  1639. %
  1640. {\if\edition\pythonEd
  1641. %
  1642. The \LangVar{} language includes assignment statements, which define a
  1643. variable for use in later statements and initializes the variable with
  1644. the value of an expression. The abstract syntax for assignment is
  1645. defined in Figure~\ref{fig:Lvar-syntax}. The concrete syntax for
  1646. assignment is
  1647. \begin{lstlisting}
  1648. |$\itm{var}$| = |$\itm{exp}$|
  1649. \end{lstlisting}
  1650. For example, the following program initializes the variable \code{x}
  1651. to $32$ and then prints the result of \code{10 + x}, producing $42$.
  1652. \begin{lstlisting}
  1653. x = 12 + 20
  1654. print(10 + x)
  1655. \end{lstlisting}
  1656. \fi}
  1657. {\if\edition\racketEd
  1658. %
  1659. When there are multiple \key{let}'s for the same variable, the closest
  1660. enclosing \key{let} is used. That is, variable definitions overshadow
  1661. prior definitions. Consider the following program with two \key{let}'s
  1662. that define two variables named \code{x}. Can you figure out the
  1663. result?
  1664. \begin{lstlisting}
  1665. (let ([x 32]) (+ (let ([x 10]) x) x))
  1666. \end{lstlisting}
  1667. For the purposes of depicting which variable occurences correspond to
  1668. which definitions, the following shows the \code{x}'s annotated with
  1669. subscripts to distinguish them. Double check that your answer for the
  1670. above is the same as your answer for this annotated version of the
  1671. program.
  1672. \begin{lstlisting}
  1673. (let ([x|$_1$| 32]) (+ (let ([x|$_2$| 10]) x|$_2$|) x|$_1$|))
  1674. \end{lstlisting}
  1675. The initializing expression is always evaluated before the body of the
  1676. \key{let}, so in the following, the \key{read} for \code{x} is
  1677. performed before the \key{read} for \code{y}. Given the input
  1678. $52$ then $10$, the following produces $42$ (not $-42$).
  1679. \begin{lstlisting}
  1680. (let ([x (read)]) (let ([y (read)]) (+ x (- y))))
  1681. \end{lstlisting}
  1682. \fi}
  1683. \subsection{Extensible Interpreters via Method Overriding}
  1684. \label{sec:extensible-interp}
  1685. To prepare for discussing the interpreter of \LangVar{}, we explain
  1686. why we implement it in an object-oriented style. Throughout this book
  1687. we define many interpreters, one for each of language that we
  1688. study. Because each language builds on the prior one, there is a lot
  1689. of commonality between these interpreters. We want to write down the
  1690. common parts just once instead of many times. A naive
  1691. interpreter for \LangVar{} would handle the
  1692. \racket{cases for variables and \code{let}}
  1693. \python{case for variables}
  1694. but dispatch to an interpreter for \LangInt{}
  1695. in the rest of the cases. The following code sketches this idea. (We
  1696. explain the \code{env} parameter soon, in
  1697. Section~\ref{sec:interp-Lvar}.)
  1698. \begin{center}
  1699. {\if\edition\racketEd
  1700. \begin{minipage}{0.45\textwidth}
  1701. \begin{lstlisting}
  1702. (define ((interp_Lint env) e)
  1703. (match e
  1704. [(Prim '- (list e1))
  1705. (fx- 0 ((interp_Lint env) e1))]
  1706. ...))
  1707. \end{lstlisting}
  1708. \end{minipage}
  1709. \begin{minipage}{0.45\textwidth}
  1710. \begin{lstlisting}
  1711. (define ((interp_Lvar env) e)
  1712. (match e
  1713. [(Var x)
  1714. (dict-ref env x)]
  1715. [(Let x e body)
  1716. (define v ((interp_exp env) e))
  1717. (define env^ (dict-set env x v))
  1718. ((interp_exp env^) body)]
  1719. [else ((interp_Lint env) e)]))
  1720. \end{lstlisting}
  1721. \end{minipage}
  1722. \fi}
  1723. {\if\edition\pythonEd
  1724. \begin{minipage}{0.45\textwidth}
  1725. \begin{lstlisting}
  1726. def interp_Lint(e, env):
  1727. match e:
  1728. case UnaryOp(USub(), e1):
  1729. return - interp_Lint(e1, env)
  1730. ...
  1731. \end{lstlisting}
  1732. \end{minipage}
  1733. \begin{minipage}{0.45\textwidth}
  1734. \begin{lstlisting}
  1735. def interp_Lvar(e, env):
  1736. match e:
  1737. case Name(id):
  1738. return env[id]
  1739. case _:
  1740. return interp_Lint(e, env)
  1741. \end{lstlisting}
  1742. \end{minipage}
  1743. \fi}
  1744. \end{center}
  1745. The problem with this naive approach is that it does not handle
  1746. situations in which an \LangVar{} feature, such as a variable, is
  1747. nested inside an \LangInt{} feature, like the \code{-} operator, as in
  1748. the following program.
  1749. %
  1750. {\if\edition\racketEd
  1751. \begin{lstlisting}
  1752. (Let 'y (Int 10) (Prim '- (list (Var 'y))))
  1753. \end{lstlisting}
  1754. \fi}
  1755. {\if\edition\pythonEd
  1756. \begin{lstlisting}
  1757. y = 10
  1758. print(-y)
  1759. \end{lstlisting}
  1760. \fi}
  1761. %
  1762. \noindent If we invoke \code{interp\_Lvar} on this program, it
  1763. dispatches to \code{interp\_Lint} to handle the \code{-} operator, but
  1764. then it recursively calls \code{interp\_Lint} again on its argument.
  1765. But there is no case for \code{Var} in \code{interp\_Lint} so we get
  1766. an error!
  1767. To make our interpreters extensible we need something called
  1768. \emph{open recursion}\index{subject}{open recursion}, where the tying of the
  1769. recursive knot is delayed to when the functions are
  1770. composed. Object-oriented languages provide open recursion via
  1771. method overriding\index{subject}{method overriding}. The
  1772. following code uses method overriding to interpret \LangInt{} and
  1773. \LangVar{} using
  1774. %
  1775. \racket{the
  1776. \href{https://docs.racket-lang.org/guide/classes.html}{\code{class}}
  1777. \index{subject}{class} feature of Racket.}
  1778. %
  1779. \python{a Python \code{class} definition.}
  1780. %
  1781. We define one class for each language and define a method for
  1782. interpreting expressions inside each class. The class for \LangVar{}
  1783. inherits from the class for \LangInt{} and the method
  1784. \code{interp\_exp} in \LangVar{} overrides the \code{interp\_exp} in
  1785. \LangInt{}. Note that the default case of \code{interp\_exp} in
  1786. \LangVar{} uses \code{super} to invoke \code{interp\_exp}, and because
  1787. \LangVar{} inherits from \LangInt{}, that dispatches to the
  1788. \code{interp\_exp} in \LangInt{}.
  1789. \begin{center}
  1790. \hspace{-20pt}
  1791. {\if\edition\racketEd
  1792. \begin{minipage}{0.45\textwidth}
  1793. \begin{lstlisting}
  1794. (define interp_Lint_class
  1795. (class object%
  1796. (define/public ((interp_exp env) e)
  1797. (match e
  1798. [(Prim '- (list e))
  1799. (fx- 0 ((interp_exp env) e))]
  1800. ...))
  1801. ...))
  1802. \end{lstlisting}
  1803. \end{minipage}
  1804. \begin{minipage}{0.45\textwidth}
  1805. \begin{lstlisting}
  1806. (define interp_Lvar_class
  1807. (class interp_Lint_class
  1808. (define/override ((interp_exp env) e)
  1809. (match e
  1810. [(Var x)
  1811. (dict-ref env x)]
  1812. [(Let x e body)
  1813. (define v ((interp_exp env) e))
  1814. (define env^ (dict-set env x v))
  1815. ((interp_exp env^) body)]
  1816. [else
  1817. (super (interp_exp env) e)]))
  1818. ...
  1819. ))
  1820. \end{lstlisting}
  1821. \end{minipage}
  1822. \fi}
  1823. {\if\edition\pythonEd
  1824. \begin{minipage}{0.45\textwidth}
  1825. \begin{lstlisting}
  1826. class InterpLint:
  1827. def interp_exp(e):
  1828. match e:
  1829. case UnaryOp(USub(), e1):
  1830. return -self.interp_exp(e1)
  1831. ...
  1832. ...
  1833. \end{lstlisting}
  1834. \end{minipage}
  1835. \begin{minipage}{0.45\textwidth}
  1836. \begin{lstlisting}
  1837. def InterpLvar(InterpLint):
  1838. def interp_exp(e):
  1839. match e:
  1840. case Name(id):
  1841. return env[id]
  1842. case _:
  1843. return super().interp_exp(e)
  1844. ...
  1845. \end{lstlisting}
  1846. \end{minipage}
  1847. \fi}
  1848. \end{center}
  1849. Getting back to the troublesome example, repeated here:
  1850. {\if\edition\racketEd
  1851. \begin{lstlisting}
  1852. (Let 'y (Int 10) (Prim '- (Var 'y)))
  1853. \end{lstlisting}
  1854. \fi}
  1855. {\if\edition\pythonEd
  1856. \begin{lstlisting}
  1857. y = 10
  1858. print(-y)
  1859. \end{lstlisting}
  1860. \fi}
  1861. \noindent We can invoke the \code{interp\_exp} method for \LangVar{}
  1862. \racket{on this expression,}
  1863. \python{on the \code{-y} expression,}
  1864. %
  1865. call it \code{e0}, by creating an object of the \LangVar{} class
  1866. and calling the \code{interp\_exp} method.
  1867. {\if\edition\racketEd
  1868. \begin{lstlisting}
  1869. ((send (new interp_Lvar_class) interp_exp '()) e0)
  1870. \end{lstlisting}
  1871. \fi}
  1872. {\if\edition\pythonEd
  1873. \begin{lstlisting}
  1874. InterpLvar().interp_exp(e0)
  1875. \end{lstlisting}
  1876. \fi}
  1877. \noindent To process the \code{-} operator, the default case of
  1878. \code{interp\_exp} in \LangVar{} dispatches to the \code{interp\_exp}
  1879. method in \LangInt{}. But then for the recursive method call, it
  1880. dispatches back to \code{interp\_exp} in \LangVar{}, where the
  1881. \code{Var} node is handled correctly. Thus, method overriding gives us
  1882. the open recursion that we need to implement our interpreters in an
  1883. extensible way.
  1884. \subsection{Definitional Interpreter for \LangVar{}}
  1885. \label{sec:interp-Lvar}
  1886. {\if\edition\racketEd
  1887. \begin{figure}[tp]
  1888. %\begin{wrapfigure}[26]{r}[0.75in]{0.55\textwidth}
  1889. \small
  1890. \begin{tcolorbox}[title=Association Lists as Dictionaries]
  1891. An \emph{association list} (alist) is a list of key-value pairs.
  1892. For example, we can map people to their ages with an alist.
  1893. \index{subject}{alist}\index{subject}{association list}
  1894. \begin{lstlisting}[basicstyle=\ttfamily]
  1895. (define ages '((jane . 25) (sam . 24) (kate . 45)))
  1896. \end{lstlisting}
  1897. The \emph{dictionary} interface is for mapping keys to values.
  1898. Every alist implements this interface. \index{subject}{dictionary} The package
  1899. \href{https://docs.racket-lang.org/reference/dicts.html}{\code{racket/dict}}
  1900. provides many functions for working with dictionaries. Here
  1901. are a few of them:
  1902. \begin{description}
  1903. \item[$\LP\key{dict-ref}\,\itm{dict}\,\itm{key}\RP$]
  1904. returns the value associated with the given $\itm{key}$.
  1905. \item[$\LP\key{dict-set}\,\itm{dict}\,\itm{key}\,\itm{val}\RP$]
  1906. returns a new dictionary that maps $\itm{key}$ to $\itm{val}$
  1907. but otherwise is the same as $\itm{dict}$.
  1908. \item[$\LP\code{in-dict}\,\itm{dict}\RP$] returns the
  1909. \href{https://docs.racket-lang.org/reference/sequences.html}{sequence}
  1910. of keys and values in $\itm{dict}$. For example, the following
  1911. creates a new alist in which the ages are incremented.
  1912. \end{description}
  1913. \vspace{-10pt}
  1914. \begin{lstlisting}[basicstyle=\ttfamily]
  1915. (for/list ([(k v) (in-dict ages)])
  1916. (cons k (add1 v)))
  1917. \end{lstlisting}
  1918. \end{tcolorbox}
  1919. %\end{wrapfigure}
  1920. \caption{Association lists implement the dictionary interface.}
  1921. \label{fig:alist}
  1922. \end{figure}
  1923. \fi}
  1924. Having justified the use of classes and methods to implement
  1925. interpreters, we revisit the definitional interpreter for \LangInt{}
  1926. in Figure~\ref{fig:interp-Lint-class} and then extend it to create an
  1927. interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}. The
  1928. interpreter for \LangVar{} adds two new \key{match} cases for
  1929. variables and \racket{\key{let}}\python{assignment}. For
  1930. \racket{\key{let}}\python{assignment} we need a way to communicate the
  1931. value bound to a variable to all the uses of the variable. To
  1932. accomplish this, we maintain a mapping from variables to values
  1933. called an \emph{environment}\index{subject}{environment}.
  1934. %
  1935. We use
  1936. %
  1937. \racket{an association list (alist) }%
  1938. %
  1939. \python{a Python \href{https://docs.python.org/3.10/library/stdtypes.html\#mapping-types-dict}{dictionary} }%
  1940. %
  1941. to represent the environment.
  1942. %
  1943. \racket{Figure~\ref{fig:alist} gives a brief introduction to alists
  1944. and the \code{racket/dict} package.}
  1945. %
  1946. The \code{interp\_exp} function takes the current environment,
  1947. \code{env}, as an extra parameter. When the interpreter encounters a
  1948. variable, it looks up the corresponding value in the dictionary.
  1949. %
  1950. \racket{When the interpreter encounters a \key{Let}, it evaluates the
  1951. initializing expression, extends the environment with the result
  1952. value bound to the variable, using \code{dict-set}, then evaluates
  1953. the body of the \key{Let}.}
  1954. %
  1955. \python{When the interpreter encounters an assignment, it evaluates
  1956. the initializing expression and then associates the resulting value
  1957. with the variable in the environment.}
  1958. \begin{figure}[tp]
  1959. {\if\edition\racketEd
  1960. \begin{lstlisting}
  1961. (define interp_Lint_class
  1962. (class object%
  1963. (super-new)
  1964. (define/public ((interp_exp env) e)
  1965. (match e
  1966. [(Int n) n]
  1967. [(Prim 'read '())
  1968. (define r (read))
  1969. (cond [(fixnum? r) r]
  1970. [else (error 'interp_exp "expected an integer" r)])]
  1971. [(Prim '- (list e)) (fx- 0 ((interp_exp env) e))]
  1972. [(Prim '+ (list e1 e2))
  1973. (fx+ ((interp_exp env) e1) ((interp_exp env) e2))]
  1974. [(Prim '- (list e1 e2))
  1975. (fx- ((interp_exp env) e1) ((interp_exp env) e2))]))
  1976. (define/public (interp_program p)
  1977. (match p
  1978. [(Program '() e) ((interp_exp '()) e)]))
  1979. ))
  1980. \end{lstlisting}
  1981. \fi}
  1982. {\if\edition\pythonEd
  1983. \begin{lstlisting}
  1984. class InterpLint:
  1985. def interp_exp(self, e, env):
  1986. match e:
  1987. case BinOp(left, Add(), right):
  1988. return self.interp_exp(left, env) + self.interp_exp(right, env)
  1989. case BinOp(left, Sub(), right):
  1990. return self.interp_exp(left, env) - self.interp_exp(right, env)
  1991. case UnaryOp(USub(), v):
  1992. return - self.interp_exp(v, env)
  1993. case Constant(value):
  1994. return value
  1995. case Call(Name('input_int'), []):
  1996. return int(input())
  1997. def interp_stmts(self, ss, env):
  1998. if len(ss) == 0:
  1999. return
  2000. match ss[0]:
  2001. case Expr(Call(Name('print'), [arg])):
  2002. print(self.interp_exp(arg, env), end='')
  2003. return self.interp_stmts(ss[1:], env)
  2004. case Expr(value):
  2005. self.interp_exp(value, env)
  2006. return self.interp_stmts(ss[1:], env)
  2007. def interp(self, p):
  2008. match p:
  2009. case Module(body):
  2010. self.interp_stmts(body, {})
  2011. def interp_Lint(p):
  2012. return InterpLint().interp(p)
  2013. \end{lstlisting}
  2014. \fi}
  2015. \caption{Interpreter for \LangInt{} as a class.}
  2016. \label{fig:interp-Lint-class}
  2017. \end{figure}
  2018. \begin{figure}[tp]
  2019. {\if\edition\racketEd
  2020. \begin{lstlisting}
  2021. (define interp_Lvar_class
  2022. (class interp_Lint_class
  2023. (super-new)
  2024. (define/override ((interp_exp env) e)
  2025. (match e
  2026. [(Var x) (dict-ref env x)]
  2027. [(Let x e body)
  2028. (define new-env (dict-set env x ((interp_exp env) e)))
  2029. ((interp_exp new-env) body)]
  2030. [else ((super interp-exp env) e)]))
  2031. ))
  2032. (define (interp_Lvar p)
  2033. (send (new interp_Lvar_class) interp_program p))
  2034. \end{lstlisting}
  2035. \fi}
  2036. {\if\edition\pythonEd
  2037. \begin{lstlisting}
  2038. class InterpLvar(InterpLint):
  2039. def interp_exp(self, e, env):
  2040. match e:
  2041. case Name(id):
  2042. return env[id]
  2043. case _:
  2044. return super().interp_exp(e, env)
  2045. def interp_stmts(self, ss, env):
  2046. if len(ss) == 0:
  2047. return
  2048. match ss[0]:
  2049. case Assign([lhs], value):
  2050. env[lhs.id] = self.interp_exp(value, env)
  2051. return self.interp_stmts(ss[1:], env)
  2052. case _:
  2053. return super().interp_stmts(ss, env)
  2054. def interp_Lvar(p):
  2055. return InterpLvar().interp(p)
  2056. \end{lstlisting}
  2057. \fi}
  2058. \caption{Interpreter for the \LangVar{} language.}
  2059. \label{fig:interp-Lvar}
  2060. \end{figure}
  2061. The goal for this chapter is to implement a compiler that translates
  2062. any program $P_1$ written in the \LangVar{} language into an x86 assembly
  2063. program $P_2$ such that $P_2$ exhibits the same behavior when run on a
  2064. computer as the $P_1$ program interpreted by \code{interp\_Lvar}.
  2065. That is, they output the same integer $n$. We depict this correctness
  2066. criteria in the following diagram.
  2067. \[
  2068. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2069. \node (p1) at (0, 0) {$P_1$};
  2070. \node (p2) at (4, 0) {$P_2$};
  2071. \node (o) at (4, -2) {$n$};
  2072. \path[->] (p1) edge [above] node {\footnotesize compile} (p2);
  2073. \path[->] (p1) edge [left] node {\footnotesize\code{interp\_Lvar}} (o);
  2074. \path[->] (p2) edge [right] node {\footnotesize\code{interp\_x86int}} (o);
  2075. \end{tikzpicture}
  2076. \]
  2077. Next we introduce the \LangXInt{} subset of x86 that suffices for
  2078. compiling \LangVar{}.
  2079. \section{The \LangXInt{} Assembly Language}
  2080. \label{sec:x86}
  2081. \index{subject}{x86}
  2082. Figure~\ref{fig:x86-int-concrete} defines the concrete syntax for
  2083. \LangXInt{}. We use the AT\&T syntax expected by the GNU
  2084. assembler.
  2085. %
  2086. A program begins with a \code{main} label followed by a sequence of
  2087. instructions. The \key{globl} directive says that the \key{main}
  2088. procedure is externally visible, which is necessary so that the
  2089. operating system can call it.
  2090. %
  2091. An x86 program is stored in the computer's memory. For our purposes,
  2092. the computer's memory is a mapping of 64-bit addresses to 64-bit
  2093. values. The computer has a \emph{program counter} (PC)\index{subject}{program
  2094. counter}\index{subject}{PC} stored in the \code{rip} register that points to
  2095. the address of the next instruction to be executed. For most
  2096. instructions, the program counter is incremented after the instruction
  2097. is executed, so it points to the next instruction in memory. Most x86
  2098. instructions take two operands, where each operand is either an
  2099. integer constant (called an \emph{immediate value}\index{subject}{immediate
  2100. value}), a \emph{register}\index{subject}{register}, or a memory location.
  2101. \newcommand{\allregisters}{\key{rsp} \MID \key{rbp} \MID \key{rax} \MID \key{rbx} \MID \key{rcx}
  2102. \MID \key{rdx} \MID \key{rsi} \MID \key{rdi} \MID \\
  2103. && \key{r8} \MID \key{r9} \MID \key{r10}
  2104. \MID \key{r11} \MID \key{r12} \MID \key{r13}
  2105. \MID \key{r14} \MID \key{r15}}
  2106. \begin{figure}[tp]
  2107. \fbox{
  2108. \begin{minipage}{0.96\textwidth}
  2109. {\if\edition\racketEd
  2110. \[
  2111. \begin{array}{lcl}
  2112. \Reg &::=& \allregisters{} \\
  2113. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2114. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2115. \key{subq} \; \Arg\key{,} \Arg \MID
  2116. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2117. && \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID
  2118. \key{callq} \; \mathit{label} \MID
  2119. \key{retq} \MID
  2120. \key{jmp}\,\itm{label} \MID \\
  2121. && \itm{label}\key{:}\; \Instr \\
  2122. \LangXIntM{} &::= & \key{.globl main}\\
  2123. & & \key{main:} \; \Instr\ldots
  2124. \end{array}
  2125. \]
  2126. \fi}
  2127. {\if\edition\pythonEd
  2128. \[
  2129. \begin{array}{lcl}
  2130. \Reg &::=& \allregisters{} \\
  2131. \Arg &::=& \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)}\\
  2132. \Instr &::=& \key{addq} \; \Arg\key{,} \Arg \MID
  2133. \key{subq} \; \Arg\key{,} \Arg \MID
  2134. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID \\
  2135. && \key{callq} \; \mathit{label} \MID
  2136. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \\
  2137. \LangXIntM{} &::= & \key{.globl main}\\
  2138. & & \key{main:} \; \Instr^{*}
  2139. \end{array}
  2140. \]
  2141. \fi}
  2142. \end{minipage}
  2143. }
  2144. \caption{The syntax of the \LangXInt{} assembly language (AT\&T syntax).}
  2145. \label{fig:x86-int-concrete}
  2146. \end{figure}
  2147. A register is a special kind of variable that holds a 64-bit
  2148. value. There are 16 general-purpose registers in the computer and
  2149. their names are given in Figure~\ref{fig:x86-int-concrete}. A register
  2150. is written with a \key{\%} followed by the register name, such as
  2151. \key{\%rax}.
  2152. An immediate value is written using the notation \key{\$}$n$ where $n$
  2153. is an integer.
  2154. %
  2155. %
  2156. An access to memory is specified using the syntax $n(\key{\%}r)$,
  2157. which obtains the address stored in register $r$ and then adds $n$
  2158. bytes to the address. The resulting address is used to load or store
  2159. to memory depending on whether it occurs as a source or destination
  2160. argument of an instruction.
  2161. An arithmetic instruction such as $\key{addq}\,s\key{,}\,d$ reads from the
  2162. source $s$ and destination $d$, applies the arithmetic operation, then
  2163. writes the result back to the destination $d$. \index{subject}{instruction}
  2164. %
  2165. The move instruction $\key{movq}\,s\key{,}\,d$ reads from $s$ and
  2166. stores the result in $d$.
  2167. %
  2168. The $\key{callq}\,\itm{label}$ instruction jumps to the procedure
  2169. specified by the label and $\key{retq}$ returns from a procedure to
  2170. its caller.
  2171. %
  2172. We discuss procedure calls in more detail later in this chapter and in
  2173. Chapter~\ref{ch:Lfun}.
  2174. %
  2175. The last letter \key{q} indicates that these instructions operate on
  2176. quadwords, i.e., 64-bit values.
  2177. %
  2178. \racket{The instruction $\key{jmp}\,\itm{label}$ updates the program
  2179. counter to the address of the instruction after the specified
  2180. label.}
  2181. Appendix~\ref{sec:x86-quick-reference} contains a quick-reference for
  2182. all of the x86 instructions used in this book.
  2183. Figure~\ref{fig:p0-x86} depicts an x86 program that computes
  2184. \racket{\code{(+ 10 32)}}\python{10 + 32}. The instruction
  2185. \lstinline{movq $10, %rax}
  2186. puts $10$ into register \key{rax} and then \lstinline{addq $32, %rax}
  2187. adds $32$ to the $10$ in \key{rax} and
  2188. puts the result, $42$, back into \key{rax}.
  2189. %
  2190. The last instruction \key{retq} finishes the \key{main} function by
  2191. returning the integer in \key{rax} to the operating system. The
  2192. operating system interprets this integer as the program's exit
  2193. code. By convention, an exit code of 0 indicates that a program
  2194. completed successfully, and all other exit codes indicate various
  2195. errors.
  2196. %
  2197. \racket{Nevertheless, in this book we return the result of the program
  2198. as the exit code.}
  2199. \begin{figure}[tbp]
  2200. \begin{lstlisting}
  2201. .globl main
  2202. main:
  2203. movq $10, %rax
  2204. addq $32, %rax
  2205. retq
  2206. \end{lstlisting}
  2207. \caption{An x86 program that computes
  2208. \racket{\code{(+ 10 32)}}\python{10 + 32}.}
  2209. \label{fig:p0-x86}
  2210. \end{figure}
  2211. We exhibit the use of memory for storing intermediate results in the
  2212. next example. Figure~\ref{fig:p1-x86} lists an x86 program that
  2213. computes \racket{\code{(+ 52 (- 10))}}\python{52 + -10}. This program
  2214. uses a region of memory called the \emph{procedure call stack} (or
  2215. \emph{stack} for
  2216. short). \index{subject}{stack}\index{subject}{procedure call stack}
  2217. The stack consists of a separate \emph{frame}\index{subject}{frame}
  2218. for each procedure call. The memory layout for an individual frame is
  2219. shown in Figure~\ref{fig:frame}. The register \key{rsp} is called the
  2220. \emph{stack pointer}\index{subject}{stack pointer} and it contains the
  2221. address of the item at the top of the stack. In general, we use the
  2222. term \emph{pointer}\index{subject}{pointer} for something that
  2223. contains an address. The stack grows downward in memory, so we
  2224. increase the size of the stack by subtracting from the stack pointer.
  2225. In the context of a procedure call, the \emph{return
  2226. address}\index{subject}{return address} is the instruction after the
  2227. call instruction on the caller side. The function call instruction,
  2228. \code{callq}, pushes the return address onto the stack prior to
  2229. jumping to the procedure. The register \key{rbp} is the \emph{base
  2230. pointer}\index{subject}{base pointer} and is used to access
  2231. variables that are stored in the frame of the current procedure call.
  2232. The base pointer of the caller is stored after the return address. In
  2233. Figure~\ref{fig:frame} we number the variables from $1$ to
  2234. $n$. Variable $1$ is stored at address $-8\key{(\%rbp)}$, variable $2$
  2235. at $-16\key{(\%rbp)}$, etc.
  2236. \begin{figure}[tbp]
  2237. {\if\edition\racketEd
  2238. \begin{lstlisting}
  2239. start:
  2240. movq $10, -8(%rbp)
  2241. negq -8(%rbp)
  2242. movq -8(%rbp), %rax
  2243. addq $52, %rax
  2244. jmp conclusion
  2245. .globl main
  2246. main:
  2247. pushq %rbp
  2248. movq %rsp, %rbp
  2249. subq $16, %rsp
  2250. jmp start
  2251. conclusion:
  2252. addq $16, %rsp
  2253. popq %rbp
  2254. retq
  2255. \end{lstlisting}
  2256. \fi}
  2257. {\if\edition\pythonEd
  2258. \begin{lstlisting}
  2259. .globl main
  2260. main:
  2261. pushq %rbp
  2262. movq %rsp, %rbp
  2263. subq $16, %rsp
  2264. movq $10, -8(%rbp)
  2265. negq -8(%rbp)
  2266. movq -8(%rbp), %rax
  2267. addq $52, %rax
  2268. addq $16, %rsp
  2269. popq %rbp
  2270. retq
  2271. \end{lstlisting}
  2272. \fi}
  2273. \caption{An x86 program that computes
  2274. \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2275. \label{fig:p1-x86}
  2276. \end{figure}
  2277. \begin{figure}[tbp]
  2278. \centering
  2279. \begin{tabular}{|r|l|} \hline
  2280. Position & Contents \\ \hline
  2281. 8(\key{\%rbp}) & return address \\
  2282. 0(\key{\%rbp}) & old \key{rbp} \\
  2283. -8(\key{\%rbp}) & variable $1$ \\
  2284. -16(\key{\%rbp}) & variable $2$ \\
  2285. \ldots & \ldots \\
  2286. 0(\key{\%rsp}) & variable $n$\\ \hline
  2287. \end{tabular}
  2288. \caption{Memory layout of a frame.}
  2289. \label{fig:frame}
  2290. \end{figure}
  2291. Getting back to the program in Figure~\ref{fig:p1-x86}, consider how
  2292. control is transferred from the operating system to the \code{main}
  2293. function. The operating system issues a \code{callq main} instruction
  2294. which pushes its return address on the stack and then jumps to
  2295. \code{main}. In x86-64, the stack pointer \code{rsp} must be divisible
  2296. by 16 bytes prior to the execution of any \code{callq} instruction, so
  2297. when control arrives at \code{main}, the \code{rsp} is 8 bytes out of
  2298. alignment (because the \code{callq} pushed the return address). The
  2299. first three instructions are the typical
  2300. \emph{prelude}\index{subject}{prelude} for a procedure. The
  2301. instruction \code{pushq \%rbp} first subtracts $8$ from the stack
  2302. pointer \code{rsp} and then saves the base pointer of the caller at
  2303. address \code{rsp} on the stack. The next instruction \code{movq
  2304. \%rsp, \%rbp} sets the base pointer to the current stack pointer,
  2305. which is pointing at the location of the old base pointer. The
  2306. instruction \code{subq \$16, \%rsp} moves the stack pointer down to
  2307. make enough room for storing variables. This program needs one
  2308. variable ($8$ bytes) but we round up to 16 bytes so that \code{rsp} is
  2309. 16-byte aligned and we're ready to make calls to other functions.
  2310. \racket{The last instruction of the prelude is \code{jmp start}, which
  2311. transfers control to the instructions that were generated from the
  2312. expression \racket{\code{(+ 52 (- 10))}}\python{52 + -10}.}
  2313. \racket{The first instruction under the \code{start} label is}
  2314. %
  2315. \python{The first instruction after the prelude is}
  2316. %
  2317. \code{movq \$10, -8(\%rbp)}, which stores $10$ in variable $1$.
  2318. %
  2319. The instruction \code{negq -8(\%rbp)} changes the contents of variable
  2320. $1$ to $-10$.
  2321. %
  2322. The next instruction moves the $-10$ from variable $1$ into the
  2323. \code{rax} register. Finally, \code{addq \$52, \%rax} adds $52$ to
  2324. the value in \code{rax}, updating its contents to $42$.
  2325. \racket{The three instructions under the label \code{conclusion} are the
  2326. typical \emph{conclusion}\index{subject}{conclusion} of a procedure.}
  2327. %
  2328. \python{The \emph{conclusion}\index{subject}{conclusion} of the
  2329. \code{main} function consists of the last three instructions.}
  2330. %
  2331. The first two restore the \code{rsp} and \code{rbp} registers to the
  2332. state they were in at the beginning of the procedure. In particular,
  2333. \key{addq \$16, \%rsp} moves the stack pointer back to point at the
  2334. old base pointer. Then \key{popq \%rbp} restores the old base pointer
  2335. to \key{rbp} and adds $8$ to the stack pointer. The last instruction,
  2336. \key{retq}, jumps back to the procedure that called this one and adds
  2337. $8$ to the stack pointer.
  2338. Our compiler needs a convenient representation for manipulating x86
  2339. programs, so we define an abstract syntax for x86 in
  2340. Figure~\ref{fig:x86-int-ast}. We refer to this language as
  2341. \LangXInt{}.
  2342. %
  2343. {\if\edition\pythonEd%
  2344. The main difference compared to the concrete syntax of \LangXInt{}
  2345. (Figure~\ref{fig:x86-int-concrete}) is that labels, instruction
  2346. names, and register names are explicitly represented by strings.
  2347. \fi} %
  2348. {\if\edition\racketEd
  2349. The main difference compared to the concrete syntax of \LangXInt{}
  2350. (Figure~\ref{fig:x86-int-concrete}) is that labels are not allowed in
  2351. front of every instruction. Instead instructions are grouped into
  2352. \emph{blocks}\index{subject}{block} with a
  2353. label associated with every block, which is why the \key{X86Program}
  2354. struct includes an alist mapping labels to blocks. The reason for this
  2355. organization becomes apparent in Chapter~\ref{ch:Lif} when we
  2356. introduce conditional branching. The \code{Block} structure includes
  2357. an $\itm{info}$ field that is not needed for this chapter but becomes
  2358. useful in Chapter~\ref{ch:register-allocation-Lvar}. For now, the
  2359. $\itm{info}$ field should contain an empty list.
  2360. \fi}
  2361. %
  2362. Regarding the abstract syntax for \code{callq}, the \code{Callq} AST
  2363. node includes an integer for representing the arity of the function,
  2364. i.e., the number of arguments, which is helpful to know during
  2365. register allocation (Chapter~\ref{ch:register-allocation-Lvar}).
  2366. \newcommand{\allastregisters}{\skey{rsp} \MID \skey{rbp} \MID \skey{rax} \MID \skey{rbx} \MID \skey{rcx}
  2367. \MID \skey{rdx} \MID \skey{rsi} \MID \skey{rdi} \MID \\
  2368. && \skey{r8} \MID \skey{r9} \MID \skey{r10}
  2369. \MID \skey{r11} \MID \skey{r12} \MID \skey{r13}
  2370. \MID \skey{r14} \MID \skey{r15}}
  2371. \begin{figure}[tp]
  2372. \fbox{
  2373. \begin{minipage}{0.98\textwidth}
  2374. \small
  2375. {\if\edition\racketEd
  2376. \[
  2377. \begin{array}{lcl}
  2378. \Reg &::=& \allregisters{} \\
  2379. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2380. \MID \DEREF{\Reg}{\Int} \\
  2381. \Instr &::=& \BININSTR{\code{addq}}{\Arg}{\Arg}
  2382. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} \\
  2383. &\MID& \BININSTR{\code{movq}}{\Arg}{\Arg}
  2384. \MID \UNIINSTR{\code{negq}}{\Arg}\\
  2385. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2386. &\MID& \CALLQ{\itm{label}}{\itm{int}}
  2387. \MID \RETQ{}
  2388. \MID \JMP{\itm{label}} \\
  2389. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP} \\
  2390. \LangXIntM{} &::= & \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}
  2391. \end{array}
  2392. \]
  2393. \fi}
  2394. {\if\edition\pythonEd
  2395. \[
  2396. \begin{array}{lcl}
  2397. \Reg &::=& \allastregisters{} \\
  2398. \Arg &::=& \IMM{\Int} \MID \REG{\Reg}
  2399. \MID \DEREF{\Reg}{\Int} \\
  2400. \Instr &::=& \BININSTR{\scode{addq}}{\Arg}{\Arg}
  2401. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} \\
  2402. &\MID& \BININSTR{\scode{movq}}{\Arg}{\Arg}
  2403. \MID \UNIINSTR{\scode{negq}}{\Arg}\\
  2404. &\MID& \PUSHQ{\Arg} \MID \POPQ{\Arg} \\
  2405. &\MID& \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{} \MID \JMP{\itm{label}} \\
  2406. \LangXIntM{} &::= & \XPROGRAM{}{\Instr^{*}}{}
  2407. \end{array}
  2408. \]
  2409. \fi}
  2410. \end{minipage}
  2411. }
  2412. \caption{The abstract syntax of \LangXInt{} assembly.}
  2413. \label{fig:x86-int-ast}
  2414. \end{figure}
  2415. \section{Planning the trip to x86}
  2416. \label{sec:plan-s0-x86}
  2417. To compile one language to another it helps to focus on the
  2418. differences between the two languages because the compiler will need
  2419. to bridge those differences. What are the differences between \LangVar{}
  2420. and x86 assembly? Here are some of the most important ones:
  2421. \begin{enumerate}
  2422. \item x86 arithmetic instructions typically have two arguments and
  2423. update the second argument in place. In contrast, \LangVar{}
  2424. arithmetic operations take two arguments and produce a new value.
  2425. An x86 instruction may have at most one memory-accessing argument.
  2426. Furthermore, some x86 instructions place special restrictions on
  2427. their arguments.
  2428. \item An argument of an \LangVar{} operator can be a deeply-nested
  2429. expression, whereas x86 instructions restrict their arguments to be
  2430. integer constants, registers, and memory locations.
  2431. {\if\edition\racketEd
  2432. \item The order of execution in x86 is explicit in the syntax: a
  2433. sequence of instructions and jumps to labeled positions, whereas in
  2434. \LangVar{} the order of evaluation is a left-to-right depth-first
  2435. traversal of the abstract syntax tree.
  2436. \fi}
  2437. \item A program in \LangVar{} can have any number of variables
  2438. whereas x86 has 16 registers and the procedure call stack.
  2439. {\if\edition\racketEd
  2440. \item Variables in \LangVar{} can shadow other variables with the
  2441. same name. In x86, registers have unique names and memory locations
  2442. have unique addresses.
  2443. \fi}
  2444. \end{enumerate}
  2445. We ease the challenge of compiling from \LangVar{} to x86 by breaking
  2446. down the problem into several steps, dealing with the above
  2447. differences one at a time. Each of these steps is called a \emph{pass}
  2448. of the compiler.\index{subject}{pass}\index{subject}{compiler pass}
  2449. %
  2450. This terminology comes from the way each step passes over, or
  2451. traverses, the AST of the program.
  2452. %
  2453. Furthermore, we follow the nanopass approach, which means we strive
  2454. for each pass to accomplish one clear objective (not two or three at
  2455. the same time).
  2456. %
  2457. We begin by sketching how we might implement each pass, and give them
  2458. names. We then figure out an ordering of the passes and the
  2459. input/output language for each pass. The very first pass has
  2460. \LangVar{} as its input language and the last pass has \LangXInt{} as
  2461. its output language. In between we can choose whichever language is
  2462. most convenient for expressing the output of each pass, whether that
  2463. be \LangVar{}, \LangXInt{}, or new \emph{intermediate languages} of
  2464. our own design. Finally, to implement each pass we write one
  2465. recursive function per non-terminal in the grammar of the input
  2466. language of the pass. \index{subject}{intermediate language}
  2467. Our compiler for \LangVar{} consists of the following passes.
  2468. %
  2469. \begin{description}
  2470. {\if\edition\racketEd
  2471. \item[\key{uniquify}] deals with the shadowing of variables by
  2472. renaming every variable to a unique name.
  2473. \fi}
  2474. \item[\key{remove\_complex\_operands}] ensures that each subexpression
  2475. of a primitive operation or function call is a variable or integer,
  2476. that is, an \emph{atomic} expression. We refer to non-atomic
  2477. expressions as \emph{complex}. This pass introduces temporary
  2478. variables to hold the results of complex
  2479. subexpressions.\index{subject}{atomic
  2480. expression}\index{subject}{complex expression}%
  2481. {\if\edition\racketEd
  2482. \item[\key{explicate\_control}] makes the execution order of the
  2483. program explicit. It converts the abstract syntax tree
  2484. representation into a graph in which each node contains a sequence
  2485. of statements and the edges between nodes say which nodes contain
  2486. jumps to other nodes.
  2487. \fi}
  2488. \item[\key{select\_instructions}] handles the difference between
  2489. \LangVar{} operations and x86 instructions. This pass converts each
  2490. \LangVar{} operation to a short sequence of instructions that
  2491. accomplishes the same task.
  2492. \item[\key{assign\_homes}] replaces variables with registers or stack
  2493. locations.
  2494. \end{description}
  2495. %
  2496. {\if\edition\racketEd
  2497. %
  2498. Our treatment of \code{remove\_complex\_operands} and
  2499. \code{explicate\_control} as separate passes is an example of the
  2500. nanopass approach\footnote{For analogous decompositions of the
  2501. translation into continuation passing style, see the work of
  2502. \citet{Lawall:1993} and \citet{Hatcliff:1994ea}.}. The traditional
  2503. approach is to combine them into a single step~\citep{Aho:2006wb}.
  2504. %
  2505. \fi}
  2506. The next question is: in what order should we apply these passes? This
  2507. question can be challenging because it is difficult to know ahead of
  2508. time which orderings will be better (easier to implement, produce more
  2509. efficient code, etc.) so oftentimes trial-and-error is
  2510. involved. Nevertheless, we can plan ahead and make educated choices
  2511. regarding the ordering.
  2512. \racket{What should be the ordering of \key{explicate\_control} with respect to
  2513. \key{uniquify}? The \key{uniquify} pass should come first because
  2514. \key{explicate\_control} changes all the \key{let}-bound variables to
  2515. become local variables whose scope is the entire program, which would
  2516. confuse variables with the same name.}
  2517. %
  2518. \racket{We place \key{remove\_complex\_operands} before \key{explicate\_control}
  2519. because the later removes the \key{let} form, but it is convenient to
  2520. use \key{let} in the output of \key{remove\_complex\_operands}.}
  2521. %
  2522. \racket{The ordering of \key{uniquify} with respect to
  2523. \key{remove\_complex\_operands} does not matter so we arbitrarily choose
  2524. \key{uniquify} to come first.}
  2525. The \key{select\_instructions} and \key{assign\_homes} passes are
  2526. intertwined.
  2527. %
  2528. In Chapter~\ref{ch:Lfun} we learn that, in x86, registers are used for
  2529. passing arguments to functions and it is preferable to assign
  2530. parameters to their corresponding registers. This suggests that it
  2531. would be better to start with the \key{select\_instructions} pass,
  2532. which generates the instructions for argument passing, before
  2533. performing register allocation.
  2534. %
  2535. On the other hand, by selecting instructions first we may run into a
  2536. dead end in \key{assign\_homes}. Recall that only one argument of an
  2537. x86 instruction may be a memory access but \key{assign\_homes} might
  2538. be forced to assign both arguments to memory locations.
  2539. %
  2540. A sophisticated approach is to iteratively repeat the two passes until
  2541. a solution is found. However, to reduce implementation complexity we
  2542. recommend placing \key{select\_instructions} first, followed by the
  2543. \key{assign\_homes}, then a third pass named \key{patch\_instructions}
  2544. that uses a reserved register to fix outstanding problems.
  2545. \begin{figure}[tbp]
  2546. {\if\edition\racketEd
  2547. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2548. \node (Lvar) at (0,2) {\large \LangVar{}};
  2549. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  2550. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  2551. %\node (Cvar-1) at (6,0) {\large \LangCVar{}};
  2552. \node (Cvar-2) at (3,0) {\large \LangCVar{}};
  2553. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  2554. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  2555. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  2556. \node (x86-5) at (12,-2) {\large \LangXInt{}};
  2557. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  2558. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  2559. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-2);
  2560. \path[->,bend right=15] (Cvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  2561. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize assign\_homes} (x86-3);
  2562. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  2563. \path[->,bend left=15] (x86-4) edge [above] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  2564. \end{tikzpicture}
  2565. \fi}
  2566. {\if\edition\pythonEd
  2567. \begin{tikzpicture}[baseline=(current bounding box.center)]
  2568. \node (Lvar) at (0,2) {\large \LangVar{}};
  2569. \node (Lvar-2) at (3,2) {\large \LangVarANF{}};
  2570. \node (x86-1) at (3,0) {\large \LangXVar{}};
  2571. \node (x86-2) at (6,0) {\large \LangXVar{}};
  2572. \node (x86-3) at (9,0) {\large \LangXInt{}};
  2573. \node (x86-4) at (12,0) {\large \LangXInt{}};
  2574. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-2);
  2575. \path[->,bend right=15] (Lvar-2) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  2576. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  2577. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  2578. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-4);
  2579. \end{tikzpicture}
  2580. \fi}
  2581. \caption{Diagram of the passes for compiling \LangVar{}. }
  2582. \label{fig:Lvar-passes}
  2583. \end{figure}
  2584. Figure~\ref{fig:Lvar-passes} presents the ordering of the compiler
  2585. passes and identifies the input and output language of each pass.
  2586. %
  2587. The output of the \key{select\_instructions} pass is the \LangXVar{}
  2588. language, which extends \LangXInt{} with an unbounded number of
  2589. program-scope variables and removes the restrictions regarding
  2590. instruction arguments.
  2591. %
  2592. The last pass, \key{prelude\_and\_conclusion}, places the program
  2593. instructions inside a \code{main} function with instructions for the
  2594. prelude and conclusion.
  2595. %
  2596. \racket{In the next section we discuss the \LangCVar{} intermediate
  2597. language that serves as the output of \code{explicate\_control}.}
  2598. %
  2599. The remainder of this chapter provides guidance on the implementation
  2600. of each of the compiler passes in Figure~\ref{fig:Lvar-passes}.
  2601. %% The output of \key{uniquify} and \key{remove-complex-operands}
  2602. %% are programs that are still in the \LangVar{} language, though the
  2603. %% output of the later is a subset of \LangVar{} named \LangVarANF{}
  2604. %% (Section~\ref{sec:remove-complex-opera-Lvar}).
  2605. %% %
  2606. %% The output of \code{explicate\_control} is in an intermediate language
  2607. %% \LangCVar{} designed to make the order of evaluation explicit in its
  2608. %% syntax, which we introduce in the next section. The
  2609. %% \key{select-instruction} pass translates from \LangCVar{} to
  2610. %% \LangXVar{}. The \key{assign-homes} and
  2611. %% \key{patch-instructions}
  2612. %% passes input and output variants of x86 assembly.
  2613. \newcommand{\CvarGrammarRacket}{
  2614. \begin{array}{lcl}
  2615. \Atm &::=& \Int \MID \Var \\
  2616. \Exp &::=& \Atm \MID \CREAD{} \MID \CNEG{\Atm} \MID \CADD{\Atm}{\Atm} \MID \CSUB{\Atm}{\Atm}\\
  2617. \Stmt &::=& \CASSIGN{\Var}{\Exp} \\
  2618. \Tail &::= & \CRETURN{\Exp} \MID \Stmt~\Tail
  2619. \end{array}
  2620. }
  2621. \newcommand{\CvarASTRacket}{
  2622. \begin{array}{lcl}
  2623. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2624. \Exp &::=& \Atm \MID \READ{} \MID \NEG{\Atm} \\
  2625. &\MID& \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm}\\
  2626. \Stmt &::=& \ASSIGN{\VAR{\Var}}{\Exp} \\
  2627. \Tail &::= & \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  2628. \end{array}
  2629. }
  2630. {\if\edition\racketEd
  2631. \subsection{The \LangCVar{} Intermediate Language}
  2632. The output of \code{explicate\_control} is similar to the $C$
  2633. language~\citep{Kernighan:1988nx} in that it has separate syntactic
  2634. categories for expressions and statements, so we name it \LangCVar{}.
  2635. This style of intermediate language is also known as
  2636. \emph{three-address code}, to emphasize that the typical form of a
  2637. statement such as \CASSIGN{\key{x}}{\CADD{\key{y}}{\key{z}}} involves three
  2638. addresses: \code{x}, \code{y}, and \code{z}~\citep{Aho:2006wb}.
  2639. The concrete syntax for \LangCVar{} is defined in
  2640. Figure~\ref{fig:c0-concrete-syntax} and the abstract syntax for
  2641. \LangCVar{} is defined in Figure~\ref{fig:c0-syntax}.
  2642. %
  2643. The \LangCVar{} language supports the same operators as \LangVar{} but
  2644. the arguments of operators are restricted to atomic
  2645. expressions. Instead of \key{let} expressions, \LangCVar{} has
  2646. assignment statements which can be executed in sequence using the
  2647. \key{Seq} form. A sequence of statements always ends with
  2648. \key{Return}, a guarantee that is baked into the grammar rules for
  2649. \itm{tail}. The naming of this non-terminal comes from the term
  2650. \emph{tail position}\index{subject}{tail position}, which refers to an
  2651. expression that is the last one to execute within a function or
  2652. program.
  2653. A \LangCVar{} program consists of an alist mapping labels to
  2654. tails. This is more general than necessary for the present chapter, as
  2655. we do not yet introduce \key{goto} for jumping to labels, but it saves
  2656. us from having to change the syntax in Chapter~\ref{ch:Lif}. For now
  2657. there will be just one label, \key{start}, and the whole program is
  2658. its tail.
  2659. %
  2660. The $\itm{info}$ field of the \key{CProgram} form, after the
  2661. \code{explicate\_control} pass, contains a mapping from the symbol
  2662. \key{locals} to a list of variables, that is, a list of all the
  2663. variables used in the program. At the start of the program, these
  2664. variables are uninitialized; they become initialized on their first
  2665. assignment.
  2666. \begin{figure}[tbp]
  2667. \fbox{
  2668. \begin{minipage}{0.96\textwidth}
  2669. \[
  2670. \begin{array}{l}
  2671. \CvarGrammarRacket \\
  2672. \begin{array}{lcl}
  2673. \LangCVarM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  2674. \end{array}
  2675. \end{array}
  2676. \]
  2677. \end{minipage}
  2678. }
  2679. \caption{The concrete syntax of the \LangCVar{} intermediate language.}
  2680. \label{fig:c0-concrete-syntax}
  2681. \end{figure}
  2682. \begin{figure}[tbp]
  2683. \fbox{
  2684. \begin{minipage}{0.96\textwidth}
  2685. \[
  2686. \begin{array}{l}
  2687. \CvarASTRacket \\
  2688. \begin{array}{lcl}
  2689. \LangCVarM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  2690. \end{array}
  2691. \end{array}
  2692. \]
  2693. \end{minipage}
  2694. }
  2695. \caption{The abstract syntax of the \LangCVar{} intermediate language.}
  2696. \label{fig:c0-syntax}
  2697. \end{figure}
  2698. The definitional interpreter for \LangCVar{} is in the support code,
  2699. in the file \code{interp-Cvar.rkt}.
  2700. \fi}
  2701. {\if\edition\racketEd
  2702. \section{Uniquify Variables}
  2703. \label{sec:uniquify-Lvar}
  2704. The \code{uniquify} pass compiles \LangVar{} programs into \LangVar{}
  2705. programs in which every \key{let} binds a unique variable name. For
  2706. example, the \code{uniquify} pass should translate the program on the
  2707. left into the program on the right.
  2708. \begin{transformation}
  2709. \begin{lstlisting}
  2710. (let ([x 32])
  2711. (+ (let ([x 10]) x) x))
  2712. \end{lstlisting}
  2713. \compilesto
  2714. \begin{lstlisting}
  2715. (let ([x.1 32])
  2716. (+ (let ([x.2 10]) x.2) x.1))
  2717. \end{lstlisting}
  2718. \end{transformation}
  2719. The following is another example translation, this time of a program
  2720. with a \key{let} nested inside the initializing expression of another
  2721. \key{let}.
  2722. \begin{transformation}
  2723. \begin{lstlisting}
  2724. (let ([x (let ([x 4])
  2725. (+ x 1))])
  2726. (+ x 2))
  2727. \end{lstlisting}
  2728. \compilesto
  2729. \begin{lstlisting}
  2730. (let ([x.2 (let ([x.1 4])
  2731. (+ x.1 1))])
  2732. (+ x.2 2))
  2733. \end{lstlisting}
  2734. \end{transformation}
  2735. We recommend implementing \code{uniquify} by creating a structurally
  2736. recursive function named \code{uniquify\_exp} that mostly just copies
  2737. an expression. However, when encountering a \key{let}, it should
  2738. generate a unique name for the variable and associate the old name
  2739. with the new name in an alist.\footnote{The Racket function
  2740. \code{gensym} is handy for generating unique variable names.} The
  2741. \code{uniquify\_exp} function needs to access this alist when it gets
  2742. to a variable reference, so we add a parameter to \code{uniquify\_exp}
  2743. for the alist.
  2744. The skeleton of the \code{uniquify\_exp} function is shown in
  2745. Figure~\ref{fig:uniquify-Lvar}.
  2746. %% The function is curried so that it is
  2747. %% convenient to partially apply it to an alist and then apply it to
  2748. %% different expressions, as in the last case for primitive operations in
  2749. %% Figure~\ref{fig:uniquify-Lvar}.
  2750. The
  2751. %
  2752. \href{https://docs.racket-lang.org/reference/for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29}{\key{for/list}}
  2753. %
  2754. form of Racket is useful for transforming the element of a list to
  2755. produce a new list.\index{subject}{for/list}
  2756. \begin{figure}[tbp]
  2757. \begin{lstlisting}
  2758. (define (uniquify_exp env)
  2759. (lambda (e)
  2760. (match e
  2761. [(Var x) ___]
  2762. [(Int n) (Int n)]
  2763. [(Let x e body) ___]
  2764. [(Prim op es)
  2765. (Prim op (for/list ([e es]) ((uniquify_exp env) e)))])))
  2766. (define (uniquify p)
  2767. (match p
  2768. [(Program '() e) (Program '() ((uniquify_exp '()) e))]))
  2769. \end{lstlisting}
  2770. \caption{Skeleton for the \key{uniquify} pass.}
  2771. \label{fig:uniquify-Lvar}
  2772. \end{figure}
  2773. \begin{exercise}
  2774. \normalfont\normalsize % I don't like the italics for exercises. -Jeremy
  2775. Complete the \code{uniquify} pass by filling in the blanks in
  2776. Figure~\ref{fig:uniquify-Lvar}, that is, implement the cases for
  2777. variables and for the \key{let} form in the file \code{compiler.rkt}
  2778. in the support code.
  2779. \end{exercise}
  2780. \begin{exercise}
  2781. \normalfont\normalsize
  2782. \label{ex:Lvar}
  2783. Create five \LangVar{} programs that exercise the most interesting
  2784. parts of the \key{uniquify} pass, that is, the programs should include
  2785. \key{let} forms, variables, and variables that shadow each other.
  2786. The five programs should be placed in the subdirectory named
  2787. \key{tests} and the file names should start with \code{var\_test\_}
  2788. followed by a unique integer and end with the file extension
  2789. \key{.rkt}.
  2790. %
  2791. The \key{run-tests.rkt} script in the support code checks whether the
  2792. output programs produce the same result as the input programs. The
  2793. script uses the \key{interp-tests} function
  2794. (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  2795. your \key{uniquify} pass on the example programs. The \code{passes}
  2796. parameter of \key{interp-tests} is a list that should have one entry
  2797. for each pass in your compiler. For now, define \code{passes} to
  2798. contain just one entry for \code{uniquify} as shown below.
  2799. \begin{lstlisting}
  2800. (define passes
  2801. (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  2802. \end{lstlisting}
  2803. Run the \key{run-tests.rkt} script in the support code to check
  2804. whether the output programs produce the same result as the input
  2805. programs.
  2806. \end{exercise}
  2807. \fi}
  2808. \section{Remove Complex Operands}
  2809. \label{sec:remove-complex-opera-Lvar}
  2810. The \code{remove\_complex\_operands} pass compiles \LangVar{} programs
  2811. into a restricted form in which the arguments of operations are atomic
  2812. expressions. Put another way, this pass removes complex
  2813. operands\index{subject}{complex operand}, such as the expression
  2814. \racket{\code{(- 10)}}\python{\code{-10}}
  2815. in the program below. This is accomplished by introducing a new
  2816. temporary variable, assigning the complex operand to the new
  2817. variable, and then using the new variable in place of the complex
  2818. operand, as shown in the output of \code{remove\_complex\_operands} on the
  2819. right.
  2820. {\if\edition\racketEd
  2821. \begin{transformation}
  2822. % var_test_19.rkt
  2823. \begin{lstlisting}
  2824. (let ([x (+ 42 (- 10))])
  2825. (+ x 10))
  2826. \end{lstlisting}
  2827. \compilesto
  2828. \begin{lstlisting}
  2829. (let ([x (let ([tmp.1 (- 10)])
  2830. (+ 42 tmp.1))])
  2831. (+ x 10))
  2832. \end{lstlisting}
  2833. \end{transformation}
  2834. \fi}
  2835. {\if\edition\pythonEd
  2836. \begin{transformation}
  2837. \begin{lstlisting}
  2838. x = 42 + -10
  2839. print(x + 10)
  2840. \end{lstlisting}
  2841. \compilesto
  2842. \begin{lstlisting}
  2843. tmp_0 = -10
  2844. x = 42 + tmp_0
  2845. tmp_1 = x + 10
  2846. print(tmp_1)
  2847. \end{lstlisting}
  2848. \end{transformation}
  2849. \fi}
  2850. \newcommand{\LvarMonadASTRacket}{
  2851. \begin{array}{rcl}
  2852. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2853. \Exp &::=& \Atm \MID \READ{} \\
  2854. &\MID& \NEG{\Atm} \MID \ADD{\Atm}{\Atm} \MID \SUB{\Atm}{\Atm} \\
  2855. &\MID& \LET{\Var}{\Exp}{\Exp} \\
  2856. \end{array}
  2857. }
  2858. \newcommand{\LvarMonadASTPython}{
  2859. \begin{array}{rcl}
  2860. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \\
  2861. \Exp{} &::=& \Atm \MID \READ{} \\
  2862. &\MID& \UNIOP{\itm{unaryop}}{\Atm} \MID \BINOP{\Atm}{\itm{binaryop}}{\Atm} \\
  2863. \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  2864. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  2865. \end{array}
  2866. }
  2867. \begin{figure}[tp]
  2868. \centering
  2869. \fbox{
  2870. \begin{minipage}{0.96\textwidth}
  2871. {\if\edition\racketEd
  2872. \[
  2873. \begin{array}{l}
  2874. \LvarMonadASTRacket \\
  2875. \begin{array}{rcl}
  2876. \LangVarANFM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  2877. \end{array}
  2878. \end{array}
  2879. \]
  2880. \fi}
  2881. {\if\edition\pythonEd
  2882. \[
  2883. \begin{array}{l}
  2884. \LvarMonadASTPython \\
  2885. \begin{array}{rcl}
  2886. \LangVarANFM{} &::=& \PROGRAM{}{\Stmt^{*}}
  2887. \end{array}
  2888. \end{array}
  2889. \]
  2890. \fi}
  2891. \end{minipage}
  2892. }
  2893. \caption{\LangVarANF{} is \LangVar{} with operands restricted to
  2894. atomic expressions.}
  2895. \label{fig:Lvar-anf-syntax}
  2896. \end{figure}
  2897. Figure~\ref{fig:Lvar-anf-syntax} presents the grammar for the output
  2898. of this pass, the language \LangVarANF{}. The only difference is that
  2899. operator arguments are restricted to be atomic expressions that are
  2900. defined by the \Atm{} non-terminal. In particular, integer constants
  2901. and variables are atomic.
  2902. The atomic expressions are pure (they do not cause or depend on
  2903. side-effects) whereas complex expressions may have side effects, such
  2904. as \READ{}. A language with this separation between pure versus
  2905. side-effecting expressions is said to be in monadic normal
  2906. form~\citep{Moggi:1991in,Danvy:2003fk} which explains the \textit{mon}
  2907. in the name \LangVarANF{}. An important invariant of the
  2908. \code{remove\_complex\_operands} pass is that the relative ordering
  2909. among complex expressions is not changed, but the relative ordering
  2910. between atomic expressions and complex expressions can change and
  2911. often does. The reason that these changes are behaviour preserving is
  2912. that the atomic expressions are pure.
  2913. Another well-known form for intermediate languages is the
  2914. \emph{administrative normal form}
  2915. (ANF)~\citep{Danvy:1991fk,Flanagan:1993cg}.
  2916. \index{subject}{administrative normal form} \index{subject}{ANF}
  2917. %
  2918. The \LangVarANF{} language is not quite in ANF because we allow the
  2919. right-hand side of a \code{let} to be a complex expression.
  2920. {\if\edition\racketEd
  2921. We recommend implementing this pass with two mutually recursive
  2922. functions, \code{rco\_atom} and \code{rco\_exp}. The idea is to apply
  2923. \code{rco\_atom} to subexpressions that need to become atomic and to
  2924. apply \code{rco\_exp} to subexpressions that do not. Both functions
  2925. take an \LangVar{} expression as input. The \code{rco\_exp} function
  2926. returns an expression. The \code{rco\_atom} function returns two
  2927. things: an atomic expression and an alist mapping temporary variables to
  2928. complex subexpressions. You can return multiple things from a function
  2929. using Racket's \key{values} form and you can receive multiple things
  2930. from a function call using the \key{define-values} form.
  2931. \fi}
  2932. %
  2933. {\if\edition\pythonEd
  2934. %
  2935. We recommend implementing this pass with an auxiliary method named
  2936. \code{rco\_exp} with two parameters: an \LangVar{} expression and a
  2937. Boolean that specifies whether the expression needs to become atomic
  2938. or not. The \code{rco\_exp} method should return a pair consisting of
  2939. the new expression and a list of pairs, associating new temporary
  2940. variables with their initializing expressions.
  2941. %
  2942. \fi}
  2943. {\if\edition\racketEd
  2944. %
  2945. Returning to the example program with the expression \code{(+ 42 (-
  2946. 10))}, the subexpression \code{(- 10)} should be processed using the
  2947. \code{rco\_atom} function because it is an argument of the \code{+}
  2948. operator and therefore needs to become atomic. The output of
  2949. \code{rco\_atom} applied to \code{(- 10)} is as follows.
  2950. \begin{transformation}
  2951. \begin{lstlisting}
  2952. (- 10)
  2953. \end{lstlisting}
  2954. \compilesto
  2955. \begin{lstlisting}
  2956. tmp.1
  2957. ((tmp.1 . (- 10)))
  2958. \end{lstlisting}
  2959. \end{transformation}
  2960. \fi}
  2961. %
  2962. {\if\edition\pythonEd
  2963. %
  2964. Returning to the example program with the expression \code{42 + -10},
  2965. the subexpression \code{-10} should be processed using the
  2966. \code{rco\_exp} function with \code{True} as the second argument
  2967. because \code{-10} is an argument of the \code{+} operator and
  2968. therefore needs to become atomic. The output of \code{rco\_exp}
  2969. applied to \code{-10} is as follows.
  2970. \begin{transformation}
  2971. \begin{lstlisting}
  2972. -10
  2973. \end{lstlisting}
  2974. \compilesto
  2975. \begin{lstlisting}
  2976. tmp_1
  2977. [(tmp_1, -10)]
  2978. \end{lstlisting}
  2979. \end{transformation}
  2980. %
  2981. \fi}
  2982. Take special care of programs such as the following that
  2983. %
  2984. \racket{bind a variable to an atomic expression.}
  2985. %
  2986. \python{assign an atomic expression to a variable.}
  2987. %
  2988. You should leave such \racket{variable bindings}\python{assignments}
  2989. unchanged, as shown in the program on the right\\
  2990. %
  2991. {\if\edition\racketEd
  2992. \begin{transformation}
  2993. % var_test_20.rkt
  2994. \begin{lstlisting}
  2995. (let ([a 42])
  2996. (let ([b a])
  2997. b))
  2998. \end{lstlisting}
  2999. \compilesto
  3000. \begin{lstlisting}
  3001. (let ([a 42])
  3002. (let ([b a])
  3003. b))
  3004. \end{lstlisting}
  3005. \end{transformation}
  3006. \fi}
  3007. {\if\edition\pythonEd
  3008. \begin{transformation}
  3009. \begin{lstlisting}
  3010. a = 42
  3011. b = a
  3012. print(b)
  3013. \end{lstlisting}
  3014. \compilesto
  3015. \begin{lstlisting}
  3016. a = 42
  3017. b = a
  3018. print(b)
  3019. \end{lstlisting}
  3020. \end{transformation}
  3021. \fi}
  3022. %
  3023. \noindent A careless implementation might produce the following output with
  3024. unnecessary temporary variables.
  3025. \begin{center}
  3026. \begin{minipage}{0.4\textwidth}
  3027. {\if\edition\racketEd
  3028. \begin{lstlisting}
  3029. (let ([tmp.1 42])
  3030. (let ([a tmp.1])
  3031. (let ([tmp.2 a])
  3032. (let ([b tmp.2])
  3033. b))))
  3034. \end{lstlisting}
  3035. \fi}
  3036. {\if\edition\pythonEd
  3037. \begin{lstlisting}
  3038. tmp_1 = 42
  3039. a = tmp_1
  3040. tmp_2 = a
  3041. b = tmp_2
  3042. print(b)
  3043. \end{lstlisting}
  3044. \fi}
  3045. \end{minipage}
  3046. \end{center}
  3047. \begin{exercise}
  3048. \normalfont\normalsize
  3049. {\if\edition\racketEd
  3050. Implement the \code{remove\_complex\_operands} function in
  3051. \code{compiler.rkt}.
  3052. %
  3053. Create three new \LangVar{} programs that exercise the interesting
  3054. code in the \code{remove\_complex\_operands} pass. Follow the guidelines
  3055. regarding file names described in Exercise~\ref{ex:Lvar}.
  3056. %
  3057. In the \code{run-tests.rkt} script, add the following entry to the
  3058. list of \code{passes} and then run the script to test your compiler.
  3059. \begin{lstlisting}
  3060. (list "remove-complex" remove_complex_operands interp_Lvar type-check-Lvar)
  3061. \end{lstlisting}
  3062. While debugging your compiler, it is often useful to see the
  3063. intermediate programs that are output from each pass. To print the
  3064. intermediate programs, place \lstinline{(debug-level 1)} before the call to
  3065. \code{interp-tests} in \code{run-tests.rkt}.
  3066. \fi}
  3067. %
  3068. {\if\edition\pythonEd
  3069. Implement the \code{remove\_complex\_operands} pass in
  3070. \code{compiler.py}, creating auxiliary functions for each
  3071. non-terminal in the grammar, i.e., \code{rco\_exp}
  3072. and \code{rco\_stmt}. We recommend you use the function
  3073. \code{utils.generate\_name()} to generate fresh names from a stub string.
  3074. \fi}
  3075. \end{exercise}
  3076. {\if\edition\pythonEd
  3077. \begin{exercise}
  3078. \normalfont\normalsize
  3079. \label{ex:Lvar}
  3080. Create five \LangVar{} programs that exercise the most interesting
  3081. parts of the \code{remove\_complex\_operands} pass. The five programs
  3082. should be placed in the subdirectory named \key{tests} and the file
  3083. names should start with \code{var\_test\_} followed by a unique
  3084. integer and end with the file extension \key{.py}.
  3085. %% The \key{run-tests.rkt} script in the support code checks whether the
  3086. %% output programs produce the same result as the input programs. The
  3087. %% script uses the \key{interp-tests} function
  3088. %% (Appendix~\ref{appendix:utilities}) from \key{utilities.rkt} to test
  3089. %% your \key{uniquify} pass on the example programs. The \code{passes}
  3090. %% parameter of \key{interp-tests} is a list that should have one entry
  3091. %% for each pass in your compiler. For now, define \code{passes} to
  3092. %% contain just one entry for \code{uniquify} as shown below.
  3093. %% \begin{lstlisting}
  3094. %% (define passes
  3095. %% (list (list "uniquify" uniquify interp_Lvar type-check-Lvar)))
  3096. %% \end{lstlisting}
  3097. Run the \key{run-tests.py} script in the support code to check
  3098. whether the output programs produce the same result as the input
  3099. programs.
  3100. \end{exercise}
  3101. \fi}
  3102. {\if\edition\racketEd
  3103. \section{Explicate Control}
  3104. \label{sec:explicate-control-Lvar}
  3105. The \code{explicate\_control} pass compiles \LangVar{} programs into \LangCVar{}
  3106. programs that make the order of execution explicit in their
  3107. syntax. For now this amounts to flattening \key{let} constructs into a
  3108. sequence of assignment statements. For example, consider the following
  3109. \LangVar{} program.\\
  3110. % var_test_11.rkt
  3111. \begin{minipage}{0.96\textwidth}
  3112. \begin{lstlisting}
  3113. (let ([y (let ([x 20])
  3114. (+ x (let ([x 22]) x)))])
  3115. y)
  3116. \end{lstlisting}
  3117. \end{minipage}\\
  3118. %
  3119. The output of the previous pass is shown below, on the left, and the
  3120. output of \code{explicate\_control} is on the right. Recall that the
  3121. right-hand-side of a \key{let} executes before its body, so the order
  3122. of evaluation for this program is to assign \code{20} to \code{x.1},
  3123. \code{22} to \code{x.2}, and \code{(+ x.1 x.2)} to \code{y}, then
  3124. return \code{y}. Indeed, the output of \code{explicate\_control} makes
  3125. this ordering explicit.
  3126. \begin{transformation}
  3127. \begin{lstlisting}
  3128. (let ([y (let ([x.1 20])
  3129. (let ([x.2 22])
  3130. (+ x.1 x.2)))])
  3131. y)
  3132. \end{lstlisting}
  3133. \compilesto
  3134. \begin{lstlisting}[language=C]
  3135. start:
  3136. x.1 = 20;
  3137. x.2 = 22;
  3138. y = (+ x.1 x.2);
  3139. return y;
  3140. \end{lstlisting}
  3141. \end{transformation}
  3142. \begin{figure}[tbp]
  3143. \begin{lstlisting}
  3144. (define (explicate_tail e)
  3145. (match e
  3146. [(Var x) ___]
  3147. [(Int n) (Return (Int n))]
  3148. [(Let x rhs body) ___]
  3149. [(Prim op es) ___]
  3150. [else (error "explicate_tail unhandled case" e)]))
  3151. (define (explicate_assign e x cont)
  3152. (match e
  3153. [(Var x) ___]
  3154. [(Int n) (Seq (Assign (Var x) (Int n)) cont)]
  3155. [(Let y rhs body) ___]
  3156. [(Prim op es) ___]
  3157. [else (error "explicate_assign unhandled case" e)]))
  3158. (define (explicate_control p)
  3159. (match p
  3160. [(Program info body) ___]))
  3161. \end{lstlisting}
  3162. \caption{Skeleton for the \code{explicate\_control} pass.}
  3163. \label{fig:explicate-control-Lvar}
  3164. \end{figure}
  3165. The organization of this pass depends on the notion of tail position
  3166. that we have alluded to earlier. Here is the definition.
  3167. \begin{definition}
  3168. The following rules define when an expression is in \textbf{\emph{tail
  3169. position}}\index{subject}{tail position} for the language \LangVar{}.
  3170. \begin{enumerate}
  3171. \item In $\PROGRAM{\code{()}}{e}$, expression $e$ is in tail position.
  3172. \item If $\LET{x}{e_1}{e_2}$ is in tail position, then so is $e_2$.
  3173. \end{enumerate}
  3174. \end{definition}
  3175. We recommend implementing \code{explicate\_control} using two
  3176. recursive functions, \code{explicate\_tail} and
  3177. \code{explicate\_assign}, as suggested in the skeleton code in
  3178. Figure~\ref{fig:explicate-control-Lvar}. The \code{explicate\_tail}
  3179. function should be applied to expressions in tail position whereas the
  3180. \code{explicate\_assign} should be applied to expressions that occur on
  3181. the right-hand-side of a \key{let}.
  3182. %
  3183. The \code{explicate\_tail} function takes an \Exp{} in \LangVar{} as
  3184. input and produces a \Tail{} in \LangCVar{} (see
  3185. Figure~\ref{fig:c0-syntax}).
  3186. %
  3187. The \code{explicate\_assign} function takes an \Exp{} in \LangVar{},
  3188. the variable that it is to be assigned to, and a \Tail{} in
  3189. \LangCVar{} for the code that comes after the assignment. The
  3190. \code{explicate\_assign} function returns a $\Tail$ in \LangCVar{}.
  3191. The \code{explicate\_assign} function is in accumulator-passing style:
  3192. the \code{cont} parameter is used for accumulating the output. This
  3193. accumulator-passing style plays an important role in how we generate
  3194. high-quality code for conditional expressions in Chapter~\ref{ch:Lif}.
  3195. The abbreviation \code{cont} is for continuation because it contains
  3196. the generated code that should come after the current assignment.
  3197. This code organization is also related to continuation-passing style,
  3198. except that \code{cont} is not what happens next during compilation,
  3199. but what happens next in the generated code.
  3200. \begin{exercise}\normalfont\normalsize
  3201. %
  3202. Implement the \code{explicate\_control} function in
  3203. \code{compiler.rkt}. Create three new \LangInt{} programs that
  3204. exercise the code in \code{explicate\_control}.
  3205. %
  3206. In the \code{run-tests.rkt} script, add the following entry to the
  3207. list of \code{passes} and then run the script to test your compiler.
  3208. \begin{lstlisting}
  3209. (list "explicate control" explicate_control interp_Cvar type-check-Cvar)
  3210. \end{lstlisting}
  3211. \end{exercise}
  3212. \fi}
  3213. \section{Select Instructions}
  3214. \label{sec:select-Lvar}
  3215. \index{subject}{instruction selection}
  3216. In the \code{select\_instructions} pass we begin the work of
  3217. translating \racket{from \LangCVar{}} to \LangXVar{}. The target
  3218. language of this pass is a variant of x86 that still uses variables,
  3219. so we add an AST node of the form $\VAR{\itm{var}}$ to the \Arg{}
  3220. non-terminal of the \LangXInt{} abstract syntax
  3221. (Figure~\ref{fig:x86-int-ast}).
  3222. \racket{We recommend implementing the
  3223. \code{select\_instructions} with three auxiliary functions, one for
  3224. each of the non-terminals of \LangCVar{}: $\Atm$, $\Stmt$, and
  3225. $\Tail$.}
  3226. \python{We recommend implementing an auxiliary function
  3227. named \code{select\_stmt} for the $\Stmt$ non-terminal.}
  3228. \racket{The cases for $\Atm$ are straightforward; variables stay the
  3229. same and integer constants change to immediates, that is, $\INT{n}$
  3230. changes to $\IMM{n}$.}
  3231. Next consider the cases for the $\Stmt$ non-terminal, starting with
  3232. arithmetic operations. For example, consider the addition operation
  3233. below, on the left side. There is an \key{addq} instruction in x86,
  3234. but it performs an in-place update. So we could move $\Arg_1$
  3235. into the left-hand side \itm{var} and then add $\Arg_2$ to
  3236. \itm{var}, where $\Arg_1$ and $\Arg_2$ are the translations of
  3237. $\Atm_1$ and $\Atm_2$ respectively.
  3238. \begin{transformation}
  3239. {\if\edition\racketEd
  3240. \begin{lstlisting}
  3241. |$\itm{var}$| = (+ |$\Atm_1$| |$\Atm_2$|);
  3242. \end{lstlisting}
  3243. \fi}
  3244. {\if\edition\pythonEd
  3245. \begin{lstlisting}
  3246. |$\itm{var}$| = |$\Atm_1$| + |$\Atm_2$|
  3247. \end{lstlisting}
  3248. \fi}
  3249. \compilesto
  3250. \begin{lstlisting}
  3251. movq |$\Arg_1$|, |$\itm{var}$|
  3252. addq |$\Arg_2$|, |$\itm{var}$|
  3253. \end{lstlisting}
  3254. \end{transformation}
  3255. There are also cases that require special care to avoid generating
  3256. needlessly complicated code. For example, if one of the arguments of
  3257. the addition is the same variable as the left-hand side of the
  3258. assignment, as shown below, then there is no need for the extra move
  3259. instruction. The assignment statement can be translated into a single
  3260. \key{addq} instruction as follows.
  3261. \begin{transformation}
  3262. {\if\edition\racketEd
  3263. \begin{lstlisting}
  3264. |$\itm{var}$| = (+ |$\Atm_1$| |$\itm{var}$|);
  3265. \end{lstlisting}
  3266. \fi}
  3267. {\if\edition\pythonEd
  3268. \begin{lstlisting}
  3269. |$\itm{var}$| = |$\Atm_1$| + |$\itm{var}$|
  3270. \end{lstlisting}
  3271. \fi}
  3272. \compilesto
  3273. \begin{lstlisting}
  3274. addq |$\Arg_1$|, |$\itm{var}$|
  3275. \end{lstlisting}
  3276. \end{transformation}
  3277. The \READOP{} operation does not have a direct counterpart in x86
  3278. assembly, so we provide this functionality with the function
  3279. \code{read\_int} in the file \code{runtime.c}, written in
  3280. C~\citep{Kernighan:1988nx}. In general, we refer to all of the
  3281. functionality in this file as the \emph{runtime system}\index{subject}{runtime
  3282. system}, or simply the \emph{runtime} for short. When compiling your
  3283. generated x86 assembly code, you need to compile \code{runtime.c} to
  3284. \code{runtime.o} (an ``object file'', using \code{gcc} with option
  3285. \code{-c}) and link it into the executable. For our purposes of code
  3286. generation, all you need to do is translate an assignment of
  3287. \READOP{} into a call to the \code{read\_int} function followed by a
  3288. move from \code{rax} to the left-hand-side variable. (Recall that the
  3289. return value of a function goes into \code{rax}.)
  3290. \begin{transformation}
  3291. {\if\edition\racketEd
  3292. \begin{lstlisting}
  3293. |$\itm{var}$| = (read);
  3294. \end{lstlisting}
  3295. \fi}
  3296. {\if\edition\pythonEd
  3297. \begin{lstlisting}
  3298. |$\itm{var}$| = input_int();
  3299. \end{lstlisting}
  3300. \fi}
  3301. \compilesto
  3302. \begin{lstlisting}
  3303. callq read_int
  3304. movq %rax, |$\itm{var}$|
  3305. \end{lstlisting}
  3306. \end{transformation}
  3307. {\if\edition\pythonEd
  3308. %
  3309. Similarly, we translate the \code{print} operation, shown below, into
  3310. a call to the \code{print\_int} function defined in \code{runtime.c}.
  3311. In x86, the first six arguments to functions are passed in registers,
  3312. with the first argument passed in register \code{rdi}. So we move the
  3313. $\Arg$ into \code{rdi} and then call \code{print\_int} using the
  3314. \code{callq} instruction.
  3315. \begin{transformation}
  3316. \begin{lstlisting}
  3317. print(|$\Atm$|)
  3318. \end{lstlisting}
  3319. \compilesto
  3320. \begin{lstlisting}
  3321. movq |$\Arg$|, %rdi
  3322. callq print_int
  3323. \end{lstlisting}
  3324. \end{transformation}
  3325. %
  3326. \fi}
  3327. {\if\edition\racketEd
  3328. There are two cases for the $\Tail$ non-terminal: \key{Return} and
  3329. \key{Seq}. Regarding \key{Return}, we recommend treating it as an
  3330. assignment to the \key{rax} register followed by a jump to the
  3331. conclusion of the program (so the conclusion needs to be labeled).
  3332. For $\SEQ{s}{t}$, you can translate the statement $s$ and tail $t$
  3333. recursively and then append the resulting instructions.
  3334. \fi}
  3335. {\if\edition\pythonEd
  3336. We recommend that you use the function \code{utils.label\_name()} to
  3337. transform a string into an label argument suitably suitable for, e.g.,
  3338. the target of the \code{callq} instruction. This practice makes your
  3339. compiler portable across Linus and Mac OS X, which requires an underscore prefixed to
  3340. all labels.
  3341. \fi}
  3342. \begin{exercise}
  3343. \normalfont\normalsize
  3344. {\if\edition\racketEd
  3345. Implement the \code{select\_instructions} pass in
  3346. \code{compiler.rkt}. Create three new example programs that are
  3347. designed to exercise all of the interesting cases in this pass.
  3348. %
  3349. In the \code{run-tests.rkt} script, add the following entry to the
  3350. list of \code{passes} and then run the script to test your compiler.
  3351. \begin{lstlisting}
  3352. (list "instruction selection" select_instructions interp_pseudo-x86-0)
  3353. \end{lstlisting}
  3354. \fi}
  3355. {\if\edition\pythonEd
  3356. Implement the \key{select\_instructions} pass in
  3357. \code{compiler.py}. Create three new example programs that are
  3358. designed to exercise all of the interesting cases in this pass.
  3359. Run the \code{run-tests.py} script to to check
  3360. whether the output programs produce the same result as the input
  3361. programs.
  3362. \fi}
  3363. \end{exercise}
  3364. \section{Assign Homes}
  3365. \label{sec:assign-Lvar}
  3366. The \code{assign\_homes} pass compiles \LangXVar{} programs to
  3367. \LangXVar{} programs that no longer use program variables.
  3368. Thus, the \code{assign\_homes} pass is responsible for placing all of
  3369. the program variables in registers or on the stack. For runtime
  3370. efficiency, it is better to place variables in registers, but as there
  3371. are only 16 registers, some programs must necessarily resort to
  3372. placing some variables on the stack. In this chapter we focus on the
  3373. mechanics of placing variables on the stack. We study an algorithm for
  3374. placing variables in registers in
  3375. Chapter~\ref{ch:register-allocation-Lvar}.
  3376. Consider again the following \LangVar{} program from
  3377. Section~\ref{sec:remove-complex-opera-Lvar}.
  3378. % var_test_20.rkt
  3379. {\if\edition\racketEd
  3380. \begin{lstlisting}
  3381. (let ([a 42])
  3382. (let ([b a])
  3383. b))
  3384. \end{lstlisting}
  3385. \fi}
  3386. {\if\edition\pythonEd
  3387. \begin{lstlisting}
  3388. a = 42
  3389. b = a
  3390. print(b)
  3391. \end{lstlisting}
  3392. \fi}
  3393. %
  3394. The output of \code{select\_instructions} is shown below, on the left,
  3395. and the output of \code{assign\_homes} is on the right. In this
  3396. example, we assign variable \code{a} to stack location
  3397. \code{-8(\%rbp)} and variable \code{b} to location \code{-16(\%rbp)}.
  3398. \begin{transformation}
  3399. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3400. movq $42, a
  3401. movq a, b
  3402. movq b, %rax
  3403. \end{lstlisting}
  3404. \compilesto
  3405. %stack-space: 16
  3406. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  3407. movq $42, -8(%rbp)
  3408. movq -8(%rbp), -16(%rbp)
  3409. movq -16(%rbp), %rax
  3410. \end{lstlisting}
  3411. \end{transformation}
  3412. \racket{
  3413. The \code{assign\_homes} pass should replace all variables
  3414. with stack locations.
  3415. The list of variables can be obtain from
  3416. the \code{locals-types} entry in the $\itm{info}$ of the
  3417. \code{X86Program} node. The \code{locals-types} entry is an alist
  3418. mapping all the variables in the program to their types
  3419. (for now just \code{Integer}).
  3420. As an aside, the \code{locals-types} entry is
  3421. computed by \code{type-check-Cvar} in the support code, which
  3422. installs it in the $\itm{info}$ field of the \code{CProgram} node,
  3423. which you should propagate to the \code{X86Program} node.}
  3424. %
  3425. \python{The \code{assign\_homes} pass should replace all uses of
  3426. variables with stack locations.}
  3427. %
  3428. In the process of assigning variables to stack locations, it is
  3429. convenient for you to compute and store the size of the frame (in
  3430. bytes) in
  3431. \racket{the $\itm{info}$ field of the \key{X86Program} node, with the key \code{stack-space},}
  3432. %
  3433. \python{the field \code{stack\_space} of the \key{X86Program} node,}
  3434. %
  3435. which is needed later to generate the conclusion of the \code{main}
  3436. procedure. The x86-64 standard requires the frame size to be a
  3437. multiple of 16 bytes.\index{subject}{frame}
  3438. % TODO: store the number of variables instead? -Jeremy
  3439. \begin{exercise}\normalfont\normalsize
  3440. Implement the \code{assign\_homes} pass in
  3441. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}, defining
  3442. auxiliary functions for each of the non-terminals in the \LangXVar{}
  3443. grammar. We recommend that the auxiliary functions take an extra
  3444. parameter that maps variable names to homes (stack locations for now).
  3445. %
  3446. {\if\edition\racketEd
  3447. In the \code{run-tests.rkt} script, add the following entry to the
  3448. list of \code{passes} and then run the script to test your compiler.
  3449. \begin{lstlisting}
  3450. (list "assign homes" assign-homes interp_x86-0)
  3451. \end{lstlisting}
  3452. \fi}
  3453. {\if\edition\pythonEd
  3454. Run the \code{run-tests.py} script to to check
  3455. whether the output programs produce the same result as the input
  3456. programs.
  3457. \fi}
  3458. \end{exercise}
  3459. \section{Patch Instructions}
  3460. \label{sec:patch-s0}
  3461. The \code{patch\_instructions} pass compiles from \LangXVar{} to
  3462. \LangXInt{} by making sure that each instruction adheres to the
  3463. restriction that at most one argument of an instruction may be a
  3464. memory reference.
  3465. We return to the following example.\\
  3466. \begin{minipage}{0.5\textwidth}
  3467. % var_test_20.rkt
  3468. {\if\edition\racketEd
  3469. \begin{lstlisting}
  3470. (let ([a 42])
  3471. (let ([b a])
  3472. b))
  3473. \end{lstlisting}
  3474. \fi}
  3475. {\if\edition\pythonEd
  3476. \begin{lstlisting}
  3477. a = 42
  3478. b = a
  3479. print(b)
  3480. \end{lstlisting}
  3481. \fi}
  3482. \end{minipage}\\
  3483. The \code{assign\_homes} pass produces the following translation. \\
  3484. \begin{minipage}{0.5\textwidth}
  3485. {\if\edition\racketEd
  3486. \begin{lstlisting}
  3487. movq $42, -8(%rbp)
  3488. movq -8(%rbp), -16(%rbp)
  3489. movq -16(%rbp), %rax
  3490. \end{lstlisting}
  3491. \fi}
  3492. {\if\edition\pythonEd
  3493. \begin{lstlisting}
  3494. movq 42, -8(%rbp)
  3495. movq -8(%rbp), -16(%rbp)
  3496. movq -16(%rbp), %rdi
  3497. callq print_int
  3498. \end{lstlisting}
  3499. \fi}
  3500. \end{minipage}\\
  3501. The second \key{movq} instruction is problematic because both
  3502. arguments are stack locations. We suggest fixing this problem by
  3503. moving from the source location to the register \key{rax} and then
  3504. from \key{rax} to the destination location, as follows.
  3505. \begin{lstlisting}
  3506. movq -8(%rbp), %rax
  3507. movq %rax, -16(%rbp)
  3508. \end{lstlisting}
  3509. \begin{exercise}
  3510. \normalfont\normalsize Implement the \key{patch\_instructions} pass in
  3511. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3512. Create three new example programs that are
  3513. designed to exercise all of the interesting cases in this pass.
  3514. %
  3515. {\if\edition\racketEd
  3516. In the \code{run-tests.rkt} script, add the following entry to the
  3517. list of \code{passes} and then run the script to test your compiler.
  3518. \begin{lstlisting}
  3519. (list "patch instructions" patch_instructions interp_x86-0)
  3520. \end{lstlisting}
  3521. \fi}
  3522. {\if\edition\pythonEd
  3523. Run the \code{run-tests.py} script to to check
  3524. whether the output programs produce the same result as the input
  3525. programs.
  3526. \fi}
  3527. \end{exercise}
  3528. \section{Generate Prelude and Conclusion}
  3529. \label{sec:print-x86}
  3530. \index{subject}{prelude}\index{subject}{conclusion}
  3531. The last step of the compiler from \LangVar{} to x86 is to generate
  3532. the \code{main} function with a prelude and conclusion wrapped around
  3533. the rest of the program, as shown in Figure~\ref{fig:p1-x86} and
  3534. discussed in Section~\ref{sec:x86}.
  3535. When running on Mac OS X, your compiler should prefix an underscore to
  3536. all labels, e.g., changing \key{main} to \key{\_main}.
  3537. %
  3538. \racket{The Racket call \code{(system-type 'os)} is useful for
  3539. determining which operating system the compiler is running on. It
  3540. returns \code{'macosx}, \code{'unix}, or \code{'windows}.}
  3541. %
  3542. \python{The Python \code{platform} library includes a \code{system()}
  3543. function that returns \code{'Linux'}, \code{'Windows'}, or
  3544. \code{'Darwin'} (for Mac).}
  3545. \begin{exercise}\normalfont\normalsize
  3546. %
  3547. Implement the \key{prelude\_and\_conclusion} pass in
  3548. \racket{\code{compiler.rkt}}\python{\code{compiler.py}}.
  3549. %
  3550. {\if\edition\racketEd
  3551. In the \code{run-tests.rkt} script, add the following entry to the
  3552. list of \code{passes} and then run the script to test your compiler.
  3553. \begin{lstlisting}
  3554. (list "prelude and conclusion" prelude-and-conclusion interp_x86-0)
  3555. \end{lstlisting}
  3556. %
  3557. Uncomment the call to the \key{compiler-tests} function
  3558. (Appendix~\ref{appendix:utilities}), which tests your complete
  3559. compiler by executing the generated x86 code. It translates the x86
  3560. AST that you produce into a string by invoking the \code{print-x86}
  3561. method of the \code{print-x86-class} in \code{utilities.rkt}. Compile
  3562. the provided \key{runtime.c} file to \key{runtime.o} using
  3563. \key{gcc}. Run the script to test your compiler.
  3564. %
  3565. \fi}
  3566. {\if\edition\pythonEd
  3567. %
  3568. Run the \code{run-tests.py} script to to check whether the output
  3569. programs produce the same result as the input programs. That script
  3570. translates the x86 AST that you produce into a string by invoking the
  3571. \code{repr} method that is implemented by the x86 AST classes in
  3572. \code{x86\_ast.py}.
  3573. %
  3574. \fi}
  3575. \end{exercise}
  3576. \section{Challenge: Partial Evaluator for \LangVar{}}
  3577. \label{sec:pe-Lvar}
  3578. \index{subject}{partial evaluation}
  3579. This section describes two optional challenge exercises that involve
  3580. adapting and improving the partial evaluator for \LangInt{} that was
  3581. introduced in Section~\ref{sec:partial-evaluation}.
  3582. \begin{exercise}\label{ex:pe-Lvar}
  3583. \normalfont\normalsize
  3584. Adapt the partial evaluator from Section~\ref{sec:partial-evaluation}
  3585. (Figure~\ref{fig:pe-arith}) so that it applies to \LangVar{} programs
  3586. instead of \LangInt{} programs. Recall that \LangVar{} adds variables and
  3587. %
  3588. \racket{\key{let} binding}\python{assignment}
  3589. %
  3590. to the \LangInt{} language, so you will need to add cases for them in
  3591. the \code{pe\_exp}
  3592. %
  3593. \racket{function.}
  3594. %
  3595. \python{and \code{pe\_stmt} functions.}
  3596. %
  3597. Once complete, add the partial evaluation pass to the front of your
  3598. compiler and make sure that your compiler still passes all of the
  3599. tests.
  3600. \end{exercise}
  3601. \begin{exercise}
  3602. \normalfont\normalsize
  3603. Improve on the partial evaluator by replacing the \code{pe\_neg} and
  3604. \code{pe\_add} auxiliary functions with functions that know more about
  3605. arithmetic. For example, your partial evaluator should translate
  3606. {\if\edition\racketEd
  3607. \[
  3608. \code{(+ 1 (+ (read) 1))} \qquad \text{into} \qquad
  3609. \code{(+ 2 (read))}
  3610. \]
  3611. \fi}
  3612. {\if\edition\pythonEd
  3613. \[
  3614. \code{1 + (input\_int() + 1)} \qquad \text{into} \qquad
  3615. \code{2 + input\_int()}
  3616. \]
  3617. \fi}
  3618. To accomplish this, the \code{pe\_exp} function should produce output
  3619. in the form of the $\itm{residual}$ non-terminal of the following
  3620. grammar. The idea is that when processing an addition expression, we
  3621. can always produce either 1) an integer constant, 2) an addition
  3622. expression with an integer constant on the left-hand side but not the
  3623. right-hand side, or 3) or an addition expression in which neither
  3624. subexpression is a constant.
  3625. {\if\edition\racketEd
  3626. \[
  3627. \begin{array}{lcl}
  3628. \itm{inert} &::=& \Var
  3629. \MID \LP\key{read}\RP
  3630. \MID \LP\key{-} ~\Var\RP
  3631. \MID \LP\key{-} ~\LP\key{read}\RP\RP
  3632. \MID \LP\key{+} ~ \itm{inert} ~ \itm{inert}\RP\\
  3633. &\MID& \LP\key{let}~\LP\LS\Var~\itm{residual}\RS\RP~ \itm{residual} \RP \\
  3634. \itm{residual} &::=& \Int
  3635. \MID \LP\key{+}~ \Int~ \itm{inert}\RP
  3636. \MID \itm{inert}
  3637. \end{array}
  3638. \]
  3639. \fi}
  3640. {\if\edition\pythonEd
  3641. \[
  3642. \begin{array}{lcl}
  3643. \itm{inert} &::=& \Var
  3644. \MID \key{input\_int}\LP\RP
  3645. \MID \key{-} \Var
  3646. \MID \key{-} \key{input\_int}\LP\RP
  3647. \MID \itm{inert} ~ \key{+} ~ \itm{inert}\\
  3648. \itm{residual} &::=& \Int
  3649. \MID \Int ~ \key{+} ~ \itm{inert}
  3650. \MID \itm{inert}
  3651. \end{array}
  3652. \]
  3653. \fi}
  3654. The \code{pe\_add} and \code{pe\_neg} functions may assume that their
  3655. inputs are $\itm{residual}$ expressions and they should return
  3656. $\itm{residual}$ expressions. Once the improvements are complete,
  3657. make sure that your compiler still passes all of the tests. After
  3658. all, fast code is useless if it produces incorrect results!
  3659. \end{exercise}
  3660. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3661. \chapter{Register Allocation}
  3662. \label{ch:register-allocation-Lvar}
  3663. \index{subject}{register allocation}
  3664. In Chapter~\ref{ch:Lvar} we compiled \LangVar{} to x86, storing
  3665. variables on the procedure call stack. It can take 10s to 100s of
  3666. cycles for the CPU to access locations on the stack whereas accessing
  3667. a register takes only a single cycle. In this chapter we improve the
  3668. efficiency of our generated code by storing some variables in
  3669. registers. The goal of register allocation is to fit as many variables
  3670. into registers as possible. Some programs have more variables than
  3671. registers so we cannot always map each variable to a different
  3672. register. Fortunately, it is common for different variables to be
  3673. in-use during different periods of time during program execution, and
  3674. in those cases we can map multiple variables to the same register.
  3675. The program in Figure~\ref{fig:reg-eg} serves as a running
  3676. example. The source program is on the left and the output of
  3677. instruction selection is on the right. The program is almost in the
  3678. x86 assembly language but it still uses variables. Consider variables
  3679. \code{x} and \code{z}. After the variable \code{x} is moved to
  3680. \code{z} it is no longer in-use. Variable \code{z}, on the other
  3681. hand, is used only after this point, so \code{x} and \code{z} could
  3682. share the same register.
  3683. \begin{figure}
  3684. \begin{minipage}{0.45\textwidth}
  3685. Example \LangVar{} program:
  3686. % var_test_28.rkt
  3687. {\if\edition\racketEd
  3688. \begin{lstlisting}
  3689. (let ([v 1])
  3690. (let ([w 42])
  3691. (let ([x (+ v 7)])
  3692. (let ([y x])
  3693. (let ([z (+ x w)])
  3694. (+ z (- y)))))))
  3695. \end{lstlisting}
  3696. \fi}
  3697. {\if\edition\pythonEd
  3698. \begin{lstlisting}
  3699. v = 1
  3700. w = 42
  3701. x = v + 7
  3702. y = x
  3703. z = x + w
  3704. print(z + (- y))
  3705. \end{lstlisting}
  3706. \fi}
  3707. \end{minipage}
  3708. \begin{minipage}{0.45\textwidth}
  3709. After instruction selection:
  3710. {\if\edition\racketEd
  3711. \begin{lstlisting}
  3712. locals-types:
  3713. x : Integer, y : Integer,
  3714. z : Integer, t : Integer,
  3715. v : Integer, w : Integer
  3716. start:
  3717. movq $1, v
  3718. movq $42, w
  3719. movq v, x
  3720. addq $7, x
  3721. movq x, y
  3722. movq x, z
  3723. addq w, z
  3724. movq y, t
  3725. negq t
  3726. movq z, %rax
  3727. addq t, %rax
  3728. jmp conclusion
  3729. \end{lstlisting}
  3730. \fi}
  3731. {\if\edition\pythonEd
  3732. \begin{lstlisting}
  3733. movq $1, v
  3734. movq $42, w
  3735. movq v, x
  3736. addq $7, x
  3737. movq x, y
  3738. movq x, z
  3739. addq w, z
  3740. movq y, tmp_0
  3741. negq tmp_0
  3742. movq z, tmp_1
  3743. addq tmp_0, tmp_1
  3744. movq tmp_1, %rdi
  3745. callq print_int
  3746. \end{lstlisting}
  3747. \fi}
  3748. \end{minipage}
  3749. \caption{A running example for register allocation.}
  3750. \label{fig:reg-eg}
  3751. \end{figure}
  3752. The topic of Section~\ref{sec:liveness-analysis-Lvar} is how to
  3753. compute where a variable is in-use. Once we have that information, we
  3754. compute which variables are in-use at the same time, i.e., which ones
  3755. \emph{interfere}\index{subject}{interfere} with each other, and
  3756. represent this relation as an undirected graph whose vertices are
  3757. variables and edges indicate when two variables interfere
  3758. (Section~\ref{sec:build-interference}). We then model register
  3759. allocation as a graph coloring problem
  3760. (Section~\ref{sec:graph-coloring}).
  3761. If we run out of registers despite these efforts, we place the
  3762. remaining variables on the stack, similar to what we did in
  3763. Chapter~\ref{ch:Lvar}. It is common to use the verb
  3764. \emph{spill}\index{subject}{spill} for assigning a variable to a stack
  3765. location. The decision to spill a variable is handled as part of the
  3766. graph coloring process.
  3767. We make the simplifying assumption that each variable is assigned to
  3768. one location (a register or stack address). A more sophisticated
  3769. approach is to assign a variable to one or more locations in different
  3770. regions of the program. For example, if a variable is used many times
  3771. in short sequence and then only used again after many other
  3772. instructions, it could be more efficient to assign the variable to a
  3773. register during the initial sequence and then move it to the stack for
  3774. the rest of its lifetime. We refer the interested reader to
  3775. \citet{Cooper:2011aa} (Chapter 13) for more information about that
  3776. approach.
  3777. % discuss prioritizing variables based on how much they are used.
  3778. \section{Registers and Calling Conventions}
  3779. \label{sec:calling-conventions}
  3780. \index{subject}{calling conventions}
  3781. As we perform register allocation, we must be aware of the
  3782. \emph{calling conventions} \index{subject}{calling conventions} that
  3783. govern how functions calls are performed in x86.
  3784. %
  3785. Even though \LangVar{} does not include programmer-defined functions,
  3786. our generated code includes a \code{main} function that is called by
  3787. the operating system and our generated code contains calls to the
  3788. \code{read\_int} function.
  3789. Function calls require coordination between two pieces of code that
  3790. may be written by different programmers or generated by different
  3791. compilers. Here we follow the System V calling conventions that are
  3792. used by the GNU C compiler on Linux and
  3793. MacOS~\citep{Bryant:2005aa,Matz:2013aa}.
  3794. %
  3795. The calling conventions include rules about how functions share the
  3796. use of registers. In particular, the caller is responsible for freeing
  3797. up some registers prior to the function call for use by the callee.
  3798. These are called the \emph{caller-saved registers}
  3799. \index{subject}{caller-saved registers}
  3800. and they are
  3801. \begin{lstlisting}
  3802. rax rcx rdx rsi rdi r8 r9 r10 r11
  3803. \end{lstlisting}
  3804. On the other hand, the callee is responsible for preserving the values
  3805. of the \emph{callee-saved registers}, \index{subject}{callee-saved registers}
  3806. which are
  3807. \begin{lstlisting}
  3808. rsp rbp rbx r12 r13 r14 r15
  3809. \end{lstlisting}
  3810. We can think about this caller/callee convention from two points of
  3811. view, the caller view and the callee view:
  3812. \begin{itemize}
  3813. \item The caller should assume that all the caller-saved registers get
  3814. overwritten with arbitrary values by the callee. On the other hand,
  3815. the caller can safely assume that all the callee-saved registers
  3816. retain their original values.
  3817. \item The callee can freely use any of the caller-saved registers.
  3818. However, if the callee wants to use a callee-saved register, the
  3819. callee must arrange to put the original value back in the register
  3820. prior to returning to the caller. This can be accomplished by saving
  3821. the value to the stack in the prelude of the function and restoring
  3822. the value in the conclusion of the function.
  3823. \end{itemize}
  3824. In x86, registers are also used for passing arguments to a function
  3825. and for the return value. In particular, the first six arguments of a
  3826. function are passed in the following six registers, in this order.
  3827. \index{subject}{argument-passing registers}
  3828. \index{subject}{parameter-passing registers}
  3829. \begin{lstlisting}
  3830. rdi rsi rdx rcx r8 r9
  3831. \end{lstlisting}
  3832. If there are more than six arguments, then the convention is to use
  3833. space on the frame of the caller for the rest of the
  3834. arguments. However, in Chapter~\ref{ch:Lfun} we arrange never to
  3835. need more than six arguments.
  3836. %
  3837. \racket{For now, the only function we care about is \code{read\_int}
  3838. and it takes zero arguments.}
  3839. %
  3840. \python{For now, the only functions we care about are \code{read\_int}
  3841. and \code{print\_int}, which take zero and one argument, respectively.}
  3842. %
  3843. The register \code{rax} is used for the return value of a function.
  3844. The next question is how these calling conventions impact register
  3845. allocation. Consider the \LangVar{} program in
  3846. Figure~\ref{fig:example-calling-conventions}. We first analyze this
  3847. example from the caller point of view and then from the callee point
  3848. of view. We refer to a variable that is in-use during a function call
  3849. as being a \emph{call-live variable}\index{subject}{call-live
  3850. variable}.
  3851. The program makes two calls to \READOP{}. The variable \code{x} is
  3852. call-live because it is in-use during the second call to \READOP{}; we
  3853. must ensure that the value in \code{x} does not get overwritten during
  3854. the call to \READOP{}. One obvious approach is to save all the values
  3855. that reside in caller-saved registers to the stack prior to each
  3856. function call, and restore them after each call. That way, if the
  3857. register allocator chooses to assign \code{x} to a caller-saved
  3858. register, its value will be preserved across the call to \READOP{}.
  3859. However, saving and restoring to the stack is relatively slow. If
  3860. \code{x} is not used many times, it may be better to assign \code{x}
  3861. to a stack location in the first place. Or better yet, if we can
  3862. arrange for \code{x} to be placed in a callee-saved register, then it
  3863. won't need to be saved and restored during function calls.
  3864. The approach that we recommend for call-live variables is to either
  3865. assign them to callee-saved registers or to spill them to the
  3866. stack. On the other hand, for variables that are not call-live, we try
  3867. the following alternatives in order 1) look for an available
  3868. caller-saved register (to leave room for other variables in the
  3869. callee-saved register), 2) look for a callee-saved register, and 3)
  3870. spill the variable to the stack.
  3871. It is straightforward to implement this approach in a graph coloring
  3872. register allocator. First, we know which variables are call-live
  3873. because we already need to compute which variables are in-use at every
  3874. instruction (Section~\ref{sec:liveness-analysis-Lvar}). Second, when
  3875. we build the interference graph
  3876. (Section~\ref{sec:build-interference}), we can place an edge between
  3877. each of the call-live variables and the caller-saved registers in the
  3878. interference graph. This will prevent the graph coloring algorithm
  3879. from assigning them to caller-saved registers.
  3880. Returning to the example in
  3881. Figure~\ref{fig:example-calling-conventions}, let us analyze the
  3882. generated x86 code on the right-hand side. Notice that variable
  3883. \code{x} is assigned to \code{rbx}, a callee-saved register. Thus, it
  3884. is already in a safe place during the second call to
  3885. \code{read\_int}. Next, notice that variable \code{y} is assigned to
  3886. \code{rcx}, a caller-saved register, because \code{y} is not a
  3887. call-live variable.
  3888. Next we analyze the example from the callee point of view, focusing on
  3889. the prelude and conclusion of the \code{main} function. As usual the
  3890. prelude begins with saving the \code{rbp} register to the stack and
  3891. setting the \code{rbp} to the current stack pointer. We now know why
  3892. it is necessary to save the \code{rbp}: it is a callee-saved register.
  3893. The prelude then pushes \code{rbx} to the stack because 1) \code{rbx}
  3894. is a callee-saved register and 2) \code{rbx} is assigned to a variable
  3895. (\code{x}). The other callee-saved registers are not saved in the
  3896. prelude because they are not used. The prelude subtracts 8 bytes from
  3897. the \code{rsp} to make it 16-byte aligned. Shifting attention to the
  3898. conclusion, we see that \code{rbx} is restored from the stack with a
  3899. \code{popq} instruction.
  3900. \index{subject}{prelude}\index{subject}{conclusion}
  3901. \begin{figure}[tp]
  3902. \begin{minipage}{0.45\textwidth}
  3903. Example \LangVar{} program:
  3904. %var_test_14.rkt
  3905. {\if\edition\racketEd
  3906. \begin{lstlisting}
  3907. (let ([x (read)])
  3908. (let ([y (read)])
  3909. (+ (+ x y) 42)))
  3910. \end{lstlisting}
  3911. \fi}
  3912. {\if\edition\pythonEd
  3913. \begin{lstlisting}
  3914. x = input_int()
  3915. y = input_int()
  3916. print((x + y) + 42)
  3917. \end{lstlisting}
  3918. \fi}
  3919. \end{minipage}
  3920. \begin{minipage}{0.45\textwidth}
  3921. Generated x86 assembly:
  3922. {\if\edition\racketEd
  3923. \begin{lstlisting}
  3924. start:
  3925. callq read_int
  3926. movq %rax, %rbx
  3927. callq read_int
  3928. movq %rax, %rcx
  3929. addq %rcx, %rbx
  3930. movq %rbx, %rax
  3931. addq $42, %rax
  3932. jmp _conclusion
  3933. .globl main
  3934. main:
  3935. pushq %rbp
  3936. movq %rsp, %rbp
  3937. pushq %rbx
  3938. subq $8, %rsp
  3939. jmp start
  3940. conclusion:
  3941. addq $8, %rsp
  3942. popq %rbx
  3943. popq %rbp
  3944. retq
  3945. \end{lstlisting}
  3946. \fi}
  3947. {\if\edition\pythonEd
  3948. \begin{lstlisting}
  3949. .globl main
  3950. main:
  3951. pushq %rbp
  3952. movq %rsp, %rbp
  3953. pushq %rbx
  3954. subq $8, %rsp
  3955. callq read_int
  3956. movq %rax, %rbx
  3957. callq read_int
  3958. movq %rax, %rcx
  3959. movq %rbx, %rdx
  3960. addq %rcx, %rdx
  3961. movq %rdx, %rcx
  3962. addq $42, %rcx
  3963. movq %rcx, %rdi
  3964. callq print_int
  3965. addq $8, %rsp
  3966. popq %rbx
  3967. popq %rbp
  3968. retq
  3969. \end{lstlisting}
  3970. \fi}
  3971. \end{minipage}
  3972. \caption{An example with function calls.}
  3973. \label{fig:example-calling-conventions}
  3974. \end{figure}
  3975. %\clearpage
  3976. \section{Liveness Analysis}
  3977. \label{sec:liveness-analysis-Lvar}
  3978. \index{subject}{liveness analysis}
  3979. The \code{uncover\_live} \racket{pass}\python{function} performs
  3980. \emph{liveness analysis}, that is, it discovers which variables are
  3981. in-use in different regions of a program.
  3982. %
  3983. A variable or register is \emph{live} at a program point if its
  3984. current value is used at some later point in the program. We refer to
  3985. variables, stack locations, and registers collectively as
  3986. \emph{locations}.
  3987. %
  3988. Consider the following code fragment in which there are two writes to
  3989. \code{b}. Are variables \code{a} and \code{b} both live at the same
  3990. time?
  3991. \begin{center}
  3992. \begin{minipage}{0.96\textwidth}
  3993. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  3994. movq $5, a
  3995. movq $30, b
  3996. movq a, c
  3997. movq $10, b
  3998. addq b, c
  3999. \end{lstlisting}
  4000. \end{minipage}
  4001. \end{center}
  4002. The answer is no because \code{a} is live from line 1 to 3 and
  4003. \code{b} is live from line 4 to 5. The integer written to \code{b} on
  4004. line 2 is never used because it is overwritten (line 4) before the
  4005. next read (line 5).
  4006. The live locations for each instruction can be computed by traversing
  4007. the instruction sequence back to front (i.e., backwards in execution
  4008. order). Let $I_1,\ldots, I_n$ be the instruction sequence. We write
  4009. $L_{\mathsf{after}}(k)$ for the set of live locations after
  4010. instruction $I_k$ and $L_{\mathsf{before}}(k)$ for the set of live
  4011. locations before instruction $I_k$. \racket{We recommend representing
  4012. these sets with the Racket \code{set} data structure described in
  4013. Figure~\ref{fig:set}.} \python{We recommend representing these sets
  4014. with the Python
  4015. \href{https://docs.python.org/3.10/library/stdtypes.html\#set-types-set-frozenset}{\code{set}}
  4016. data structure.}
  4017. {\if\edition\racketEd
  4018. \begin{figure}[tp]
  4019. %\begin{wrapfigure}[19]{l}[0.75in]{0.55\textwidth}
  4020. \small
  4021. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/reference/sets.html}{The Racket Set Package}]
  4022. A \emph{set} is an unordered collection of elements without duplicates.
  4023. Here are some of the operations defined on sets.
  4024. \index{subject}{set}
  4025. \begin{description}
  4026. \item[$\LP\code{set}~v~\ldots\RP$] constructs a set containing the specified elements.
  4027. \item[$\LP\code{set-union}~set_1~set_2\RP$] returns the union of the two sets.
  4028. \item[$\LP\code{set-subtract}~set_1~set_2\RP$] returns the set
  4029. difference of the two sets.
  4030. \item[$\LP\code{set-member?}~set~v\RP$] answers whether element $v$ is in $set$.
  4031. \item[$\LP\code{set-count}~set\RP$] returns the number of unique elements in $set$.
  4032. \item[$\LP\code{set->list}~set\RP$] converts $set$ to a list.
  4033. \end{description}
  4034. \end{tcolorbox}
  4035. %\end{wrapfigure}
  4036. \caption{The \code{set} data structure.}
  4037. \label{fig:set}
  4038. \end{figure}
  4039. \fi}
  4040. The live locations after an instruction are always the same as the
  4041. live locations before the next instruction.
  4042. \index{subject}{live-after} \index{subject}{live-before}
  4043. \begin{equation} \label{eq:live-after-before-next}
  4044. L_{\mathsf{after}}(k) = L_{\mathsf{before}}(k+1)
  4045. \end{equation}
  4046. To start things off, there are no live locations after the last
  4047. instruction, so
  4048. \begin{equation}\label{eq:live-last-empty}
  4049. L_{\mathsf{after}}(n) = \emptyset
  4050. \end{equation}
  4051. We then apply the following rule repeatedly, traversing the
  4052. instruction sequence back to front.
  4053. \begin{equation}\label{eq:live-before-after-minus-writes-plus-reads}
  4054. L_{\mathtt{before}}(k) = (L_{\mathtt{after}}(k) - W(k)) \cup R(k),
  4055. \end{equation}
  4056. where $W(k)$ are the locations written to by instruction $I_k$ and
  4057. $R(k)$ are the locations read by instruction $I_k$.
  4058. {\if\edition\racketEd
  4059. %
  4060. There is a special case for \code{jmp} instructions. The locations
  4061. that are live before a \code{jmp} should be the locations in
  4062. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  4063. maintaining an alist named \code{label->live} that maps each label to
  4064. the $L_{\mathtt{before}}$ for the first instruction in its block. For
  4065. now the only \code{jmp} in a \LangXVar{} program is the jump to the
  4066. conclusion. (For example, see Figure~\ref{fig:reg-eg}.) The
  4067. conclusion reads from \ttm{rax} and \ttm{rsp}, so the alist should map
  4068. \code{conclusion} to the set $\{\ttm{rax},\ttm{rsp}\}$.
  4069. %
  4070. \fi}
  4071. Let us walk through the above example, applying these formulas
  4072. starting with the instruction on line 5. We collect the answers in
  4073. Figure~\ref{fig:liveness-example-0}. The $L_{\mathsf{after}}$ for the
  4074. \code{addq b, c} instruction is $\emptyset$ because it is the last
  4075. instruction (formula~\ref{eq:live-last-empty}). The
  4076. $L_{\mathsf{before}}$ for this instruction is $\{\ttm{b},\ttm{c}\}$
  4077. because it reads from variables \code{b} and \code{c}
  4078. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}), that is
  4079. \[
  4080. L_{\mathsf{before}}(5) = (\emptyset - \{\ttm{c}\}) \cup \{ \ttm{b}, \ttm{c} \} = \{ \ttm{b}, \ttm{c} \}
  4081. \]
  4082. Moving on the the instruction \code{movq \$10, b} at line 4, we copy
  4083. the live-before set from line 5 to be the live-after set for this
  4084. instruction (formula~\ref{eq:live-after-before-next}).
  4085. \[
  4086. L_{\mathsf{after}}(4) = \{ \ttm{b}, \ttm{c} \}
  4087. \]
  4088. This move instruction writes to \code{b} and does not read from any
  4089. variables, so we have the following live-before set
  4090. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}).
  4091. \[
  4092. L_{\mathsf{before}}(4) = (\{\ttm{b},\ttm{c}\} - \{\ttm{b}\}) \cup \emptyset = \{ \ttm{c} \}
  4093. \]
  4094. The live-before for instruction \code{movq a, c}
  4095. is $\{\ttm{a}\}$ because it writes to $\{\ttm{c}\}$ and reads from $\{\ttm{a}\}$
  4096. (formula~\ref{eq:live-before-after-minus-writes-plus-reads}). The
  4097. live-before for \code{movq \$30, b} is $\{\ttm{a}\}$ because it writes to a
  4098. variable that is not live and does not read from a variable.
  4099. Finally, the live-before for \code{movq \$5, a} is $\emptyset$
  4100. because it writes to variable \code{a}.
  4101. \begin{figure}[tbp]
  4102. \begin{minipage}{0.45\textwidth}
  4103. \begin{lstlisting}[numbers=left,numberstyle=\tiny]
  4104. movq $5, a
  4105. movq $30, b
  4106. movq a, c
  4107. movq $10, b
  4108. addq b, c
  4109. \end{lstlisting}
  4110. \end{minipage}
  4111. \vrule\hspace{10pt}
  4112. \begin{minipage}{0.45\textwidth}
  4113. \begin{align*}
  4114. L_{\mathsf{before}}(1)= \emptyset,
  4115. L_{\mathsf{after}}(1)= \{\ttm{a}\}\\
  4116. L_{\mathsf{before}}(2)= \{\ttm{a}\},
  4117. L_{\mathsf{after}}(2)= \{\ttm{a}\}\\
  4118. L_{\mathsf{before}}(3)= \{\ttm{a}\},
  4119. L_{\mathsf{after}}(2)= \{\ttm{c}\}\\
  4120. L_{\mathsf{before}}(4)= \{\ttm{c}\},
  4121. L_{\mathsf{after}}(4)= \{\ttm{b},\ttm{c}\}\\
  4122. L_{\mathsf{before}}(5)= \{\ttm{b},\ttm{c}\},
  4123. L_{\mathsf{after}}(5)= \emptyset
  4124. \end{align*}
  4125. \end{minipage}
  4126. \caption{Example output of liveness analysis on a short example.}
  4127. \label{fig:liveness-example-0}
  4128. \end{figure}
  4129. \begin{exercise}\normalfont\normalsize
  4130. Perform liveness analysis by hand on the running example in
  4131. Figure~\ref{fig:reg-eg}, computing the live-before and live-after
  4132. sets for each instruction. Compare your answers to the solution
  4133. shown in Figure~\ref{fig:live-eg}.
  4134. \end{exercise}
  4135. \begin{figure}[tp]
  4136. \hspace{20pt}
  4137. \begin{minipage}{0.45\textwidth}
  4138. {\if\edition\racketEd
  4139. \begin{lstlisting}
  4140. |$\{\ttm{rsp}\}$|
  4141. movq $1, v
  4142. |$\{\ttm{v},\ttm{rsp}\}$|
  4143. movq $42, w
  4144. |$\{\ttm{v},\ttm{w},\ttm{rsp}\}$|
  4145. movq v, x
  4146. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4147. addq $7, x
  4148. |$\{\ttm{w},\ttm{x},\ttm{rsp}\}$|
  4149. movq x, y
  4150. |$\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$|
  4151. movq x, z
  4152. |$\{\ttm{w},\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4153. addq w, z
  4154. |$\{\ttm{y},\ttm{z},\ttm{rsp}\}$|
  4155. movq y, t
  4156. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4157. negq t
  4158. |$\{\ttm{t},\ttm{z},\ttm{rsp}\}$|
  4159. movq z, %rax
  4160. |$\{\ttm{rax},\ttm{t},\ttm{rsp}\}$|
  4161. addq t, %rax
  4162. |$\{\ttm{rax},\ttm{rsp}\}$|
  4163. jmp conclusion
  4164. \end{lstlisting}
  4165. \fi}
  4166. {\if\edition\pythonEd
  4167. \begin{lstlisting}
  4168. movq $1, v
  4169. |$\{\ttm{v}\}$|
  4170. movq $42, w
  4171. |$\{\ttm{w}, \ttm{v}\}$|
  4172. movq v, x
  4173. |$\{\ttm{w}, \ttm{x}\}$|
  4174. addq $7, x
  4175. |$\{\ttm{w}, \ttm{x}\}$|
  4176. movq x, y
  4177. |$\{\ttm{w}, \ttm{x}, \ttm{y}\}$|
  4178. movq x, z
  4179. |$\{\ttm{w}, \ttm{y}, \ttm{z}\}$|
  4180. addq w, z
  4181. |$\{\ttm{y}, \ttm{z}\}$|
  4182. movq y, tmp_0
  4183. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4184. negq tmp_0
  4185. |$\{\ttm{tmp\_0}, \ttm{z}\}$|
  4186. movq z, tmp_1
  4187. |$\{\ttm{tmp\_0}, \ttm{tmp\_1}\}$|
  4188. addq tmp_0, tmp_1
  4189. |$\{\ttm{tmp\_1}\}$|
  4190. movq tmp_1, %rdi
  4191. |$\{\ttm{rdi}\}$|
  4192. callq print_int
  4193. |$\{\}$|
  4194. \end{lstlisting}
  4195. \fi}
  4196. \end{minipage}
  4197. \caption{The running example annotated with live-after sets.}
  4198. \label{fig:live-eg}
  4199. \end{figure}
  4200. \begin{exercise}\normalfont\normalsize
  4201. Implement the \code{uncover\_live} \racket{pass}\python{function}.
  4202. %
  4203. \racket{Store the sequence of live-after sets in the $\itm{info}$
  4204. field of the \code{Block} structure.}
  4205. %
  4206. \python{Return a dictionary that maps each instruction to its
  4207. live-after set.}
  4208. %
  4209. \racket{We recommend creating an auxiliary function that takes a list
  4210. of instructions and an initial live-after set (typically empty) and
  4211. returns the list of live-after sets.}
  4212. %
  4213. We recommend creating auxiliary functions to 1) compute the set
  4214. of locations that appear in an \Arg{}, 2) compute the locations read
  4215. by an instruction (the $R$ function), and 3) the locations written by
  4216. an instruction (the $W$ function). The \code{callq} instruction should
  4217. include all of the caller-saved registers in its write-set $W$ because
  4218. the calling convention says that those registers may be written to
  4219. during the function call. Likewise, the \code{callq} instruction
  4220. should include the appropriate argument-passing registers in its
  4221. read-set $R$, depending on the arity of the function being
  4222. called. (This is why the abstract syntax for \code{callq} includes the
  4223. arity.)
  4224. \end{exercise}
  4225. %\clearpage
  4226. \section{Build the Interference Graph}
  4227. \label{sec:build-interference}
  4228. {\if\edition\racketEd
  4229. \begin{figure}[tp]
  4230. %\begin{wrapfigure}[23]{r}[0.75in]{0.55\textwidth}
  4231. \small
  4232. \begin{tcolorbox}[title=\href{https://docs.racket-lang.org/graph/index.html}{The Racket Graph Library}]
  4233. A \emph{graph} is a collection of vertices and edges where each
  4234. edge connects two vertices. A graph is \emph{directed} if each
  4235. edge points from a source to a target. Otherwise the graph is
  4236. \emph{undirected}.
  4237. \index{subject}{graph}\index{subject}{directed graph}\index{subject}{undirected graph}
  4238. \begin{description}
  4239. %% We currently don't use directed graphs. We instead use
  4240. %% directed multi-graphs. -Jeremy
  4241. \item[$\LP\code{directed-graph}\,\itm{edges}\RP$] constructs a
  4242. directed graph from a list of edges. Each edge is a list
  4243. containing the source and target vertex.
  4244. \item[$\LP\code{undirected-graph}\,\itm{edges}\RP$] constructs a
  4245. undirected graph from a list of edges. Each edge is represented by
  4246. a list containing two vertices.
  4247. \item[$\LP\code{add-vertex!}\,\itm{graph}\,\itm{vertex}\RP$]
  4248. inserts a vertex into the graph.
  4249. \item[$\LP\code{add-edge!}\,\itm{graph}\,\itm{source}\,\itm{target}\RP$]
  4250. inserts an edge between the two vertices.
  4251. \item[$\LP\code{in-neighbors}\,\itm{graph}\,\itm{vertex}\RP$]
  4252. returns a sequence of vertices adjacent to the vertex.
  4253. \item[$\LP\code{in-vertices}\,\itm{graph}\RP$]
  4254. returns a sequence of all vertices in the graph.
  4255. \end{description}
  4256. \end{tcolorbox}
  4257. %\end{wrapfigure}
  4258. \caption{The Racket \code{graph} package.}
  4259. \label{fig:graph}
  4260. \end{figure}
  4261. \fi}
  4262. Based on the liveness analysis, we know where each location is live.
  4263. However, during register allocation, we need to answer questions of
  4264. the specific form: are locations $u$ and $v$ live at the same time?
  4265. (And therefore cannot be assigned to the same register.) To make this
  4266. question more efficient to answer, we create an explicit data
  4267. structure, an \emph{interference graph}\index{subject}{interference
  4268. graph}. An interference graph is an undirected graph that has an
  4269. edge between two locations if they are live at the same time, that is,
  4270. if they interfere with each other.
  4271. %
  4272. \racket{We recommend using the Racket \code{graph} package
  4273. (Figure~\ref{fig:graph}) to represent the interference graph.}
  4274. %
  4275. \python{We provide implementations of directed and undirected graph
  4276. data structures in the file \code{graph.py} of the support code.}
  4277. A straightforward way to compute the interference graph is to look at
  4278. the set of live locations between each instruction and add an edge to
  4279. the graph for every pair of variables in the same set. This approach
  4280. is less than ideal for two reasons. First, it can be expensive because
  4281. it takes $O(n^2)$ time to consider every pair in a set of $n$ live
  4282. locations. Second, in the special case where two locations hold the
  4283. same value (because one was assigned to the other), they can be live
  4284. at the same time without interfering with each other.
  4285. A better way to compute the interference graph is to focus on
  4286. writes~\citep{Appel:2003fk}. The writes performed by an instruction
  4287. must not overwrite something in a live location. So for each
  4288. instruction, we create an edge between the locations being written to
  4289. and the live locations. (Except that a location never interferes with
  4290. itself.) For the \key{callq} instruction, we consider all of the
  4291. caller-saved registers as being written to, so an edge is added
  4292. between every live variable and every caller-saved register. Also, for
  4293. \key{movq} there is the special case of two variables holding the same
  4294. value. If a live variable $v$ is the same as the source of the
  4295. \key{movq}, then there is no need to add an edge between $v$ and the
  4296. destination, because they both hold the same value.
  4297. %
  4298. So we have the following two rules.
  4299. \begin{enumerate}
  4300. \item If instruction $I_k$ is a move instruction of the form
  4301. \key{movq} $s$\key{,} $d$, then for every $v \in
  4302. L_{\mathsf{after}}(k)$, if $v \neq d$ and $v \neq s$, add the edge
  4303. $(d,v)$.
  4304. \item For any other instruction $I_k$, for every $d \in W(k)$ and
  4305. every $v \in L_{\mathsf{after}}(k)$, if $v \neq d$, add the edge
  4306. $(d,v)$.
  4307. \end{enumerate}
  4308. Working from the top to bottom of Figure~\ref{fig:live-eg}, we apply
  4309. the above rules to each instruction. We highlight a few of the
  4310. instructions. \racket{The first instruction is \lstinline{movq $1, v}
  4311. and the live-after set is $\{\ttm{v},\ttm{rsp}\}$. Rule 1 applies,
  4312. so \code{v} interferes with \code{rsp}.}
  4313. %
  4314. \python{The first instruction is \lstinline{movq $1, v} and the
  4315. live-after set is $\{\ttm{v}\}$. Rule 1 applies but there is
  4316. no interference because $\ttm{v}$ is the destination of the move.}
  4317. %
  4318. \racket{The fourth instruction is \lstinline{addq $7, x} and the
  4319. live-after set is $\{\ttm{w},\ttm{x},\ttm{rsp}\}$. Rule 2 applies so
  4320. $\ttm{x}$ interferes with \ttm{w} and \ttm{rsp}.}
  4321. %
  4322. \python{The fourth instruction is \lstinline{addq $7, x} and the
  4323. live-after set is $\{\ttm{w},\ttm{x}\}$. Rule 2 applies so
  4324. $\ttm{x}$ interferes with \ttm{w}.}
  4325. %
  4326. \racket{The next instruction is \lstinline{movq x, y} and the
  4327. live-after set is $\{\ttm{w},\ttm{x},\ttm{y},\ttm{rsp}\}$. Rule 1
  4328. applies, so \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not
  4329. \ttm{x} because \ttm{x} is the source of the move and therefore
  4330. \ttm{x} and \ttm{y} hold the same value.}
  4331. %
  4332. \python{The next instruction is \lstinline{movq x, y} and the
  4333. live-after set is $\{\ttm{w},\ttm{x},\ttm{y}\}$. Rule 1
  4334. applies, so \ttm{y} interferes with \ttm{w} but not
  4335. \ttm{x} because \ttm{x} is the source of the move and therefore
  4336. \ttm{x} and \ttm{y} hold the same value.}
  4337. %
  4338. Figure~\ref{fig:interference-results} lists the interference results
  4339. for all of the instructions and the resulting interference graph is
  4340. shown in Figure~\ref{fig:interfere}.
  4341. \begin{figure}[tbp]
  4342. \begin{quote}
  4343. {\if\edition\racketEd
  4344. \begin{tabular}{ll}
  4345. \lstinline!movq $1, v!& \ttm{v} interferes with \ttm{rsp},\\
  4346. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v} and \ttm{rsp},\\
  4347. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4348. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w} and \ttm{rsp},\\
  4349. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} and \ttm{rsp} but not \ttm{x},\\
  4350. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w}, \ttm{y}, and \ttm{rsp},\\
  4351. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} and \ttm{rsp}, \\
  4352. \lstinline!movq y, t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4353. \lstinline!negq t!& \ttm{t} interferes with \ttm{z} and \ttm{rsp}, \\
  4354. \lstinline!movq z, %rax! & \ttm{rax} interferes with \ttm{t} and \ttm{rsp}, \\
  4355. \lstinline!addq t, %rax! & \ttm{rax} interferes with \ttm{rsp}. \\
  4356. \lstinline!jmp conclusion!& no interference.
  4357. \end{tabular}
  4358. \fi}
  4359. {\if\edition\pythonEd
  4360. \begin{tabular}{ll}
  4361. \lstinline!movq $1, v!& no interference\\
  4362. \lstinline!movq $42, w!& \ttm{w} interferes with \ttm{v}\\
  4363. \lstinline!movq v, x!& \ttm{x} interferes with \ttm{w}\\
  4364. \lstinline!addq $7, x!& \ttm{x} interferes with \ttm{w}\\
  4365. \lstinline!movq x, y!& \ttm{y} interferes with \ttm{w} but not \ttm{x}\\
  4366. \lstinline!movq x, z!& \ttm{z} interferes with \ttm{w} and \ttm{y}\\
  4367. \lstinline!addq w, z!& \ttm{z} interferes with \ttm{y} \\
  4368. \lstinline!movq y, tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4369. \lstinline!negq tmp_0!& \ttm{tmp\_0} interferes with \ttm{z} \\
  4370. \lstinline!movq z, tmp_1! & \ttm{tmp\_0} interferes with \ttm{tmp\_1} \\
  4371. \lstinline!addq tmp_0, tmp_1! & no interference\\
  4372. \lstinline!movq tmp_1, %rdi! & no interference \\
  4373. \lstinline!callq print_int!& no interference.
  4374. \end{tabular}
  4375. \fi}
  4376. \end{quote}
  4377. \caption{Interference results for the running example.}
  4378. \label{fig:interference-results}
  4379. \end{figure}
  4380. \begin{figure}[tbp]
  4381. \large
  4382. {\if\edition\racketEd
  4383. \[
  4384. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4385. \node (rax) at (0,0) {$\ttm{rax}$};
  4386. \node (rsp) at (9,2) {$\ttm{rsp}$};
  4387. \node (t1) at (0,2) {$\ttm{t}$};
  4388. \node (z) at (3,2) {$\ttm{z}$};
  4389. \node (x) at (6,2) {$\ttm{x}$};
  4390. \node (y) at (3,0) {$\ttm{y}$};
  4391. \node (w) at (6,0) {$\ttm{w}$};
  4392. \node (v) at (9,0) {$\ttm{v}$};
  4393. \draw (t1) to (rax);
  4394. \draw (t1) to (z);
  4395. \draw (z) to (y);
  4396. \draw (z) to (w);
  4397. \draw (x) to (w);
  4398. \draw (y) to (w);
  4399. \draw (v) to (w);
  4400. \draw (v) to (rsp);
  4401. \draw (w) to (rsp);
  4402. \draw (x) to (rsp);
  4403. \draw (y) to (rsp);
  4404. \path[-.,bend left=15] (z) edge node {} (rsp);
  4405. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4406. \draw (rax) to (rsp);
  4407. \end{tikzpicture}
  4408. \]
  4409. \fi}
  4410. {\if\edition\pythonEd
  4411. \[
  4412. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4413. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  4414. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  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 (t0) to (t1);
  4421. \draw (t0) 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. \end{tikzpicture}
  4428. \]
  4429. \fi}
  4430. \caption{The interference graph of the example program.}
  4431. \label{fig:interfere}
  4432. \end{figure}
  4433. %% Our next concern is to choose a data structure for representing the
  4434. %% interference graph. There are many choices for how to represent a
  4435. %% graph, for example, \emph{adjacency matrix}, \emph{adjacency list},
  4436. %% and \emph{edge set}~\citep{Cormen:2001uq}. The right way to choose a
  4437. %% data structure is to study the algorithm that uses the data structure,
  4438. %% determine what operations need to be performed, and then choose the
  4439. %% data structure that provide the most efficient implementations of
  4440. %% those operations. Often times the choice of data structure can have an
  4441. %% effect on the time complexity of the algorithm, as it does here. If
  4442. %% you skim the next section, you will see that the register allocation
  4443. %% algorithm needs to ask the graph for all of its vertices and, given a
  4444. %% vertex, it needs to known all of the adjacent vertices. Thus, the
  4445. %% correct choice of graph representation is that of an adjacency
  4446. %% list. There are helper functions in \code{utilities.rkt} for
  4447. %% representing graphs using the adjacency list representation:
  4448. %% \code{make-graph}, \code{add-edge}, and \code{adjacent}
  4449. %% (Appendix~\ref{appendix:utilities}).
  4450. %% %
  4451. %% \margincomment{\footnotesize To do: change to use the
  4452. %% Racket graph library. \\ --Jeremy}
  4453. %% %
  4454. %% In particular, those functions use a hash table to map each vertex to
  4455. %% the set of adjacent vertices, and the sets are represented using
  4456. %% Racket's \key{set}, which is also a hash table.
  4457. \begin{exercise}\normalfont\normalsize
  4458. \racket{Implement the compiler pass named \code{build\_interference} according
  4459. to the algorithm suggested above. We recommend using the Racket
  4460. \code{graph} package to create and inspect the interference graph.
  4461. The output graph of this pass should be stored in the $\itm{info}$ field of
  4462. the program, under the key \code{conflicts}.}
  4463. %
  4464. \python{Implement a function named \code{build\_interference}
  4465. according to the algorithm suggested above that
  4466. returns the interference graph.}
  4467. \end{exercise}
  4468. \section{Graph Coloring via Sudoku}
  4469. \label{sec:graph-coloring}
  4470. \index{subject}{graph coloring}
  4471. \index{subject}{Sudoku}
  4472. \index{subject}{color}
  4473. We come to the main event of this chapter, mapping variables to
  4474. registers and stack locations. Variables that interfere with each
  4475. other must be mapped to different locations. In terms of the
  4476. interference graph, this means that adjacent vertices must be mapped
  4477. to different locations. If we think of locations as colors, the
  4478. register allocation problem becomes the graph coloring
  4479. problem~\citep{Balakrishnan:1996ve,Rosen:2002bh}.
  4480. The reader may be more familiar with the graph coloring problem than he
  4481. or she realizes; the popular game of Sudoku is an instance of the
  4482. graph coloring problem. The following describes how to build a graph
  4483. out of an initial Sudoku board.
  4484. \begin{itemize}
  4485. \item There is one vertex in the graph for each Sudoku square.
  4486. \item There is an edge between two vertices if the corresponding squares
  4487. are in the same row, in the same column, or if the squares are in
  4488. the same $3\times 3$ region.
  4489. \item Choose nine colors to correspond to the numbers $1$ to $9$.
  4490. \item Based on the initial assignment of numbers to squares in the
  4491. Sudoku board, assign the corresponding colors to the corresponding
  4492. vertices in the graph.
  4493. \end{itemize}
  4494. If you can color the remaining vertices in the graph with the nine
  4495. colors, then you have also solved the corresponding game of Sudoku.
  4496. Figure~\ref{fig:sudoku-graph} shows an initial Sudoku game board and
  4497. the corresponding graph with colored vertices. We map the Sudoku
  4498. number 1 to black, 2 to white, and 3 to gray. We only show edges for a
  4499. sampling of the vertices (the colored ones) because showing edges for
  4500. all of the vertices would make the graph unreadable.
  4501. \begin{figure}[tbp]
  4502. \includegraphics[width=0.45\textwidth]{figs/sudoku}
  4503. \includegraphics[width=0.5\textwidth]{figs/sudoku-graph-bw}
  4504. \caption{A Sudoku game board and the corresponding colored graph.}
  4505. \label{fig:sudoku-graph}
  4506. \end{figure}
  4507. Some techniques for playing Sudoku correspond to heuristics used in
  4508. graph coloring algorithms. For example, one of the basic techniques
  4509. for Sudoku is called Pencil Marks. The idea is to use a process of
  4510. elimination to determine what numbers are no longer available for a
  4511. square and write down those numbers in the square (writing very
  4512. small). For example, if the number $1$ is assigned to a square, then
  4513. write the pencil mark $1$ in all the squares in the same row, column,
  4514. and region to indicate that $1$ is no longer an option for those other
  4515. squares.
  4516. %
  4517. The Pencil Marks technique corresponds to the notion of
  4518. \emph{saturation}\index{subject}{saturation} due to \cite{Brelaz:1979eu}. The
  4519. saturation of a vertex, in Sudoku terms, is the set of numbers that
  4520. are no longer available. In graph terminology, we have the following
  4521. definition:
  4522. \begin{equation*}
  4523. \mathrm{saturation}(u) = \{ c \;|\; \exists v. v \in \mathrm{adjacent}(u)
  4524. \text{ and } \mathrm{color}(v) = c \}
  4525. \end{equation*}
  4526. where $\mathrm{adjacent}(u)$ is the set of vertices that share an
  4527. edge with $u$.
  4528. The Pencil Marks technique leads to a simple strategy for filling in
  4529. numbers: if there is a square with only one possible number left, then
  4530. choose that number! But what if there are no squares with only one
  4531. possibility left? One brute-force approach is to try them all: choose
  4532. the first one and if that ultimately leads to a solution, great. If
  4533. not, backtrack and choose the next possibility. One good thing about
  4534. Pencil Marks is that it reduces the degree of branching in the search
  4535. tree. Nevertheless, backtracking can be terribly time consuming. One
  4536. way to reduce the amount of backtracking is to use the
  4537. most-constrained-first heuristic (aka. minimum remaining
  4538. values)~\citep{Russell2003}. That is, when choosing a square, always
  4539. choose one with the fewest possibilities left (the vertex with the
  4540. highest saturation). The idea is that choosing highly constrained
  4541. squares earlier rather than later is better because later on there may
  4542. not be any possibilities left in the highly saturated squares.
  4543. However, register allocation is easier than Sudoku because the
  4544. register allocator can fall back to assigning variables to stack
  4545. locations when the registers run out. Thus, it makes sense to replace
  4546. backtracking with greedy search: make the best choice at the time and
  4547. keep going. We still wish to minimize the number of colors needed, so
  4548. we use the most-constrained-first heuristic in the greedy search.
  4549. Figure~\ref{fig:satur-algo} gives the pseudo-code for a simple greedy
  4550. algorithm for register allocation based on saturation and the
  4551. most-constrained-first heuristic. It is roughly equivalent to the
  4552. DSATUR graph coloring algorithm~\citep{Brelaz:1979eu}.
  4553. %,Gebremedhin:1999fk,Omari:2006uq
  4554. Just as in Sudoku, the algorithm represents colors with integers. The
  4555. integers $0$ through $k-1$ correspond to the $k$ registers that we use
  4556. for register allocation. The integers $k$ and larger correspond to
  4557. stack locations. The registers that are not used for register
  4558. allocation, such as \code{rax}, are assigned to negative integers. In
  4559. particular, we assign $-1$ to \code{rax} and $-2$ to \code{rsp}.
  4560. %% One might wonder why we include registers at all in the liveness
  4561. %% analysis and interference graph. For example, we never allocate a
  4562. %% variable to \code{rax} and \code{rsp}, so it would be harmless to
  4563. %% leave them out. As we see in Chapter~\ref{ch:Lvec}, when we begin
  4564. %% to use register for passing arguments to functions, it will be
  4565. %% necessary for those registers to appear in the interference graph
  4566. %% because those registers will also be assigned to variables, and we
  4567. %% don't want those two uses to encroach on each other. Regarding
  4568. %% registers such as \code{rax} and \code{rsp} that are not used for
  4569. %% variables, we could omit them from the interference graph but that
  4570. %% would require adding special cases to our algorithm, which would
  4571. %% complicate the logic for little gain.
  4572. \begin{figure}[btp]
  4573. \centering
  4574. \begin{lstlisting}[basicstyle=\rmfamily,deletekeywords={for,from,with,is,not,in,find},morekeywords={while},columns=fullflexible]
  4575. Algorithm: DSATUR
  4576. Input: a graph |$G$|
  4577. Output: an assignment |$\mathrm{color}[v]$| for each vertex |$v \in G$|
  4578. |$W \gets \mathrm{vertices}(G)$|
  4579. while |$W \neq \emptyset$| do
  4580. pick a vertex |$u$| from |$W$| with the highest saturation,
  4581. breaking ties randomly
  4582. find the lowest color |$c$| that is not in |$\{ \mathrm{color}[v] \;:\; v \in \mathrm{adjacent}(u)\}$|
  4583. |$\mathrm{color}[u] \gets c$|
  4584. |$W \gets W - \{u\}$|
  4585. \end{lstlisting}
  4586. \caption{The saturation-based greedy graph coloring algorithm.}
  4587. \label{fig:satur-algo}
  4588. \end{figure}
  4589. {\if\edition\racketEd
  4590. With the DSATUR algorithm in hand, let us return to the running
  4591. example and consider how to color the interference graph in
  4592. Figure~\ref{fig:interfere}.
  4593. %
  4594. We start by assigning the register nodes to their own color. For
  4595. example, \code{rax} is assigned the color $-1$ and \code{rsp} is
  4596. assigned $-2$. The variables are not yet colored, so they are
  4597. annotated with a dash. We then update the saturation for vertices that
  4598. are adjacent to a register, obtaining the following annotated
  4599. graph. For example, the saturation for \code{t} is $\{-1,-2\}$ because
  4600. it interferes with both \code{rax} and \code{rsp}.
  4601. \[
  4602. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4603. \node (rax) at (0,0) {$\ttm{rax}:-1,\{-2\}$};
  4604. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1\}$};
  4605. \node (t1) at (0,2) {$\ttm{t}:-,\{-1,-2\}$};
  4606. \node (z) at (3,2) {$\ttm{z}:-,\{-2\}$};
  4607. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4608. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4609. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4610. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4611. \draw (t1) to (rax);
  4612. \draw (t1) to (z);
  4613. \draw (z) to (y);
  4614. \draw (z) to (w);
  4615. \draw (x) to (w);
  4616. \draw (y) to (w);
  4617. \draw (v) to (w);
  4618. \draw (v) to (rsp);
  4619. \draw (w) to (rsp);
  4620. \draw (x) to (rsp);
  4621. \draw (y) to (rsp);
  4622. \path[-.,bend left=15] (z) edge node {} (rsp);
  4623. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4624. \draw (rax) to (rsp);
  4625. \end{tikzpicture}
  4626. \]
  4627. The algorithm says to select a maximally saturated vertex. So we pick
  4628. $\ttm{t}$ and color it with the first available integer, which is
  4629. $0$. We mark $0$ as no longer available for $\ttm{z}$, $\ttm{rax}$,
  4630. and \ttm{rsp} because they interfere with $\ttm{t}$.
  4631. \[
  4632. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4633. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4634. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0\}$};
  4635. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,-2\}$};
  4636. \node (z) at (3,2) {$\ttm{z}:-,\{0,-2\}$};
  4637. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4638. \node (y) at (3,0) {$\ttm{y}:-,\{-2\}$};
  4639. \node (w) at (6,0) {$\ttm{w}:-,\{-2\}$};
  4640. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4641. \draw (t1) to (rax);
  4642. \draw (t1) to (z);
  4643. \draw (z) to (y);
  4644. \draw (z) to (w);
  4645. \draw (x) to (w);
  4646. \draw (y) to (w);
  4647. \draw (v) to (w);
  4648. \draw (v) to (rsp);
  4649. \draw (w) to (rsp);
  4650. \draw (x) to (rsp);
  4651. \draw (y) to (rsp);
  4652. \path[-.,bend left=15] (z) edge node {} (rsp);
  4653. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4654. \draw (rax) to (rsp);
  4655. \end{tikzpicture}
  4656. \]
  4657. We repeat the process, selecting a maximally saturated vertex,
  4658. choosing is \code{z}, and color it with the first available number, which
  4659. is $1$. We add $1$ to the saturation for the neighboring vertices
  4660. \code{t}, \code{y}, \code{w}, and \code{rsp}.
  4661. \[
  4662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4663. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4664. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4665. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4666. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4667. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  4668. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  4669. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  4670. \node (v) at (10,0) {$\ttm{v}:-,\{-2\}$};
  4671. \draw (t1) to (rax);
  4672. \draw (t1) to (z);
  4673. \draw (z) to (y);
  4674. \draw (z) to (w);
  4675. \draw (x) to (w);
  4676. \draw (y) to (w);
  4677. \draw (v) to (w);
  4678. \draw (v) to (rsp);
  4679. \draw (w) to (rsp);
  4680. \draw (x) to (rsp);
  4681. \draw (y) to (rsp);
  4682. \path[-.,bend left=15] (z) edge node {} (rsp);
  4683. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4684. \draw (rax) to (rsp);
  4685. \end{tikzpicture}
  4686. \]
  4687. The most saturated vertices are now \code{w} and \code{y}. We color
  4688. \code{w} with the first available color, which is $0$.
  4689. \[
  4690. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4691. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4692. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1\}$};
  4693. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4694. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  4695. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4696. \node (y) at (3,0) {$\ttm{y}:-,\{0,1,-2\}$};
  4697. \node (w) at (6,0) {$\ttm{w}:0,\{1,-2\}$};
  4698. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4699. \draw (t1) to (rax);
  4700. \draw (t1) to (z);
  4701. \draw (z) to (y);
  4702. \draw (z) to (w);
  4703. \draw (x) to (w);
  4704. \draw (y) to (w);
  4705. \draw (v) to (w);
  4706. \draw (v) to (rsp);
  4707. \draw (w) to (rsp);
  4708. \draw (x) to (rsp);
  4709. \draw (y) to (rsp);
  4710. \path[-.,bend left=15] (z) edge node {} (rsp);
  4711. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4712. \draw (rax) to (rsp);
  4713. \end{tikzpicture}
  4714. \]
  4715. Vertex \code{y} is now the most highly saturated, so we color \code{y}
  4716. with $2$. We cannot choose $0$ or $1$ because those numbers are in
  4717. \code{y}'s saturation set. Indeed, \code{y} interferes with \code{w}
  4718. and \code{z}, whose colors are $0$ and $1$ respectively.
  4719. \[
  4720. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4721. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  4722. \node (rsp) at (10,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  4723. \node (t1) at (0,2) {$\ttm{t}:0,\{-1,1,-2\}$};
  4724. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  4725. \node (x) at (6,2) {$\ttm{x}:-,\{0,-2\}$};
  4726. \node (y) at (3,0) {$\ttm{y}:2,\{0,1,-2\}$};
  4727. \node (w) at (6,0) {$\ttm{w}:0,\{1,2,-2\}$};
  4728. \node (v) at (10,0) {$\ttm{v}:-,\{0,-2\}$};
  4729. \draw (t1) to (rax);
  4730. \draw (t1) to (z);
  4731. \draw (z) to (y);
  4732. \draw (z) to (w);
  4733. \draw (x) to (w);
  4734. \draw (y) to (w);
  4735. \draw (v) to (w);
  4736. \draw (v) to (rsp);
  4737. \draw (w) to (rsp);
  4738. \draw (x) to (rsp);
  4739. \draw (y) to (rsp);
  4740. \path[-.,bend left=15] (z) edge node {} (rsp);
  4741. \path[-.,bend left=10] (t1) edge node {} (rsp);
  4742. \draw (rax) to (rsp);
  4743. \end{tikzpicture}
  4744. \]
  4745. Now \code{x} and \code{v} are the most saturated, so we color \code{v} with $1$.
  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}:1,\{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. In the last step of the algorithm, we color \code{x} 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}:1,\{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. So we obtain the following coloring:
  4800. \[
  4801. \{
  4802. \ttm{rax} \mapsto -1,
  4803. \ttm{rsp} \mapsto -2,
  4804. \ttm{t} \mapsto 0,
  4805. \ttm{z} \mapsto 1,
  4806. \ttm{x} \mapsto 1,
  4807. \ttm{y} \mapsto 2,
  4808. \ttm{w} \mapsto 0,
  4809. \ttm{v} \mapsto 1
  4810. \}
  4811. \]
  4812. \fi}
  4813. %
  4814. {\if\edition\pythonEd
  4815. %
  4816. With the DSATUR algorithm in hand, let us return to the running
  4817. example and consider how to color the interference graph in
  4818. Figure~\ref{fig:interfere}. We annotate each variable node with a dash
  4819. to indicate that it has not yet been assigned a color. The saturation
  4820. sets are also shown for each node; all of them start as the empty set.
  4821. (We do not include the register nodes in the graph below because there
  4822. were no interference edges involving registers in this program, but in
  4823. general there can be.)
  4824. %
  4825. \[
  4826. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4827. \node (t0) at (0,2) {$\ttm{tmp\_0}: -, \{\}$};
  4828. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{\}$};
  4829. \node (z) at (3,2) {$\ttm{z}: -, \{\}$};
  4830. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4831. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4832. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4833. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4834. \draw (t0) to (t1);
  4835. \draw (t0) to (z);
  4836. \draw (z) to (y);
  4837. \draw (z) to (w);
  4838. \draw (x) to (w);
  4839. \draw (y) to (w);
  4840. \draw (v) to (w);
  4841. \end{tikzpicture}
  4842. \]
  4843. The algorithm says to select a maximally saturated vertex, but they
  4844. are all equally saturated. So we flip a coin and pick $\ttm{tmp\_0}$
  4845. then color it with the first available integer, which is $0$. We mark
  4846. $0$ as no longer available for $\ttm{tmp\_1}$ and $\ttm{z}$ because
  4847. they interfere with $\ttm{tmp\_0}$.
  4848. \[
  4849. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4850. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{\}$};
  4851. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4852. \node (z) at (3,2) {$\ttm{z}: -, \{0\}$};
  4853. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4854. \node (y) at (3,0) {$\ttm{y}: -, \{\}$};
  4855. \node (w) at (6,0) {$\ttm{w}: -, \{\}$};
  4856. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4857. \draw (t0) to (t1);
  4858. \draw (t0) to (z);
  4859. \draw (z) to (y);
  4860. \draw (z) to (w);
  4861. \draw (x) to (w);
  4862. \draw (y) to (w);
  4863. \draw (v) to (w);
  4864. \end{tikzpicture}
  4865. \]
  4866. We repeat the process. The most saturated vertices are \code{z} and
  4867. \code{tmp\_1}, so we choose \code{z} and color it with the first
  4868. available number, which is $1$. We add $1$ to the saturation for the
  4869. neighboring vertices \code{tmp\_0}, \code{y}, and \code{w}.
  4870. \[
  4871. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4872. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4873. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4874. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4875. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  4876. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  4877. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  4878. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  4879. \draw (t0) to (t1);
  4880. \draw (t0) to (z);
  4881. \draw (z) to (y);
  4882. \draw (z) to (w);
  4883. \draw (x) to (w);
  4884. \draw (y) to (w);
  4885. \draw (v) to (w);
  4886. \end{tikzpicture}
  4887. \]
  4888. The most saturated vertices are now \code{tmp\_1}, \code{w}, and
  4889. \code{y}. We color \code{w} with the first available color, which
  4890. is $0$.
  4891. \[
  4892. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4893. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4894. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4895. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  4896. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4897. \node (y) at (3,0) {$\ttm{y}: -, \{0,1\}$};
  4898. \node (w) at (6,0) {$\ttm{w}: 0, \{1\}$};
  4899. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4900. \draw (t0) to (t1);
  4901. \draw (t0) to (z);
  4902. \draw (z) to (y);
  4903. \draw (z) to (w);
  4904. \draw (x) to (w);
  4905. \draw (y) to (w);
  4906. \draw (v) to (w);
  4907. \end{tikzpicture}
  4908. \]
  4909. Now \code{y} is the most saturated, so we color it with $2$.
  4910. \[
  4911. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4912. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4913. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4914. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4915. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4916. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4917. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4918. \node (v) at (9,0) {$\ttm{v}: -, \{0\}$};
  4919. \draw (t0) to (t1);
  4920. \draw (t0) to (z);
  4921. \draw (z) to (y);
  4922. \draw (z) to (w);
  4923. \draw (x) to (w);
  4924. \draw (y) to (w);
  4925. \draw (v) to (w);
  4926. \end{tikzpicture}
  4927. \]
  4928. The most saturated vertices are \code{tmp\_1}, \code{x}, and \code{v}.
  4929. We choose to color \code{v} with $1$.
  4930. \[
  4931. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4932. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4933. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  4934. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4935. \node (x) at (6,2) {$\ttm{x}: -, \{0\}$};
  4936. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4937. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4938. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4939. \draw (t0) to (t1);
  4940. \draw (t0) to (z);
  4941. \draw (z) to (y);
  4942. \draw (z) to (w);
  4943. \draw (x) to (w);
  4944. \draw (y) to (w);
  4945. \draw (v) to (w);
  4946. \end{tikzpicture}
  4947. \]
  4948. We color the remaining two variables, \code{tmp\_1} and \code{x}, with $1$.
  4949. \[
  4950. \begin{tikzpicture}[baseline=(current bounding box.center)]
  4951. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  4952. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  4953. \node (z) at (3,2) {$\ttm{z}: 1, \{0,2\}$};
  4954. \node (x) at (6,2) {$\ttm{x}: 1, \{0\}$};
  4955. \node (y) at (3,0) {$\ttm{y}: 2, \{0,1\}$};
  4956. \node (w) at (6,0) {$\ttm{w}: 0, \{1,2\}$};
  4957. \node (v) at (9,0) {$\ttm{v}: 1, \{0\}$};
  4958. \draw (t0) to (t1);
  4959. \draw (t0) to (z);
  4960. \draw (z) to (y);
  4961. \draw (z) to (w);
  4962. \draw (x) to (w);
  4963. \draw (y) to (w);
  4964. \draw (v) to (w);
  4965. \end{tikzpicture}
  4966. \]
  4967. So we obtain the following coloring:
  4968. \[
  4969. \{ \ttm{tmp\_0} \mapsto 0,
  4970. \ttm{tmp\_1} \mapsto 1,
  4971. \ttm{z} \mapsto 1,
  4972. \ttm{x} \mapsto 1,
  4973. \ttm{y} \mapsto 2,
  4974. \ttm{w} \mapsto 0,
  4975. \ttm{v} \mapsto 1 \}
  4976. \]
  4977. \fi}
  4978. We recommend creating an auxiliary function named \code{color\_graph}
  4979. that takes an interference graph and a list of all the variables in
  4980. the program. This function should return a mapping of variables to
  4981. their colors (represented as natural numbers). By creating this helper
  4982. function, you will be able to reuse it in Chapter~\ref{ch:Lfun}
  4983. when we add support for functions.
  4984. To prioritize the processing of highly saturated nodes inside the
  4985. \code{color\_graph} function, we recommend using the priority queue
  4986. data structure \racket{described in Figure~\ref{fig:priority-queue}}\python{in the file \code{priority\_queue.py} of the support code}. \racket{In
  4987. addition, you will need to maintain a mapping from variables to their
  4988. ``handles'' in the priority queue so that you can notify the priority
  4989. queue when their saturation changes.}
  4990. {\if\edition\racketEd
  4991. \begin{figure}[tp]
  4992. %\begin{wrapfigure}[25]{r}[0.75in]{0.55\textwidth}
  4993. \small
  4994. \begin{tcolorbox}[title=Priority Queue]
  4995. A \emph{priority queue} is a collection of items in which the
  4996. removal of items is governed by priority. In a ``min'' queue,
  4997. lower priority items are removed first. An implementation is in
  4998. \code{priority\_queue.rkt} of the support code. \index{subject}{priority
  4999. queue} \index{subject}{minimum priority queue}
  5000. \begin{description}
  5001. \item[$\LP\code{make-pqueue}\,\itm{cmp}\RP$] constructs an empty
  5002. priority queue that uses the $\itm{cmp}$ predicate to determine
  5003. whether its first argument has lower or equal priority to its
  5004. second argument.
  5005. \item[$\LP\code{pqueue-count}\,\itm{queue}\RP$] returns the number of
  5006. items in the queue.
  5007. \item[$\LP\code{pqueue-push!}\,\itm{queue}\,\itm{item}\RP$] inserts
  5008. the item into the queue and returns a handle for the item in the
  5009. queue.
  5010. \item[$\LP\code{pqueue-pop!}\,\itm{queue}\RP$] returns the item with
  5011. the lowest priority.
  5012. \item[$\LP\code{pqueue-decrease-key!}\,\itm{queue}\,\itm{handle}\RP$]
  5013. notifies the queue that the priority has decreased for the item
  5014. associated with the given handle.
  5015. \end{description}
  5016. \end{tcolorbox}
  5017. %\end{wrapfigure}
  5018. \caption{The priority queue data structure.}
  5019. \label{fig:priority-queue}
  5020. \end{figure}
  5021. \fi}
  5022. With the coloring complete, we finalize the assignment of variables to
  5023. registers and stack locations. We map the first $k$ colors to the $k$
  5024. registers and the rest of the colors to stack locations. Suppose for
  5025. the moment that we have just one register to use for register
  5026. allocation, \key{rcx}. Then we have the following map from colors to
  5027. locations.
  5028. \[
  5029. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{-8(\%rbp)}, \; 2 \mapsto \key{-16(\%rbp)} \}
  5030. \]
  5031. Composing this mapping with the coloring, we arrive at the following
  5032. assignment of variables to locations.
  5033. {\if\edition\racketEd
  5034. \begin{gather*}
  5035. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5036. \ttm{w} \mapsto \key{\%rcx}, \,
  5037. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5038. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5039. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5040. \ttm{t} \mapsto \key{\%rcx} \}
  5041. \end{gather*}
  5042. \fi}
  5043. {\if\edition\pythonEd
  5044. \begin{gather*}
  5045. \{ \ttm{v} \mapsto \key{-8(\%rbp)}, \,
  5046. \ttm{w} \mapsto \key{\%rcx}, \,
  5047. \ttm{x} \mapsto \key{-8(\%rbp)}, \,
  5048. \ttm{y} \mapsto \key{-16(\%rbp)}, \\
  5049. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5050. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5051. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5052. \end{gather*}
  5053. \fi}
  5054. Adapt the code from the \code{assign\_homes} pass
  5055. (Section~\ref{sec:assign-Lvar}) to replace the variables with their
  5056. assigned location. Applying the above assignment to our running
  5057. example, on the left, yields the program on the right.
  5058. % why frame size of 32? -JGS
  5059. \begin{center}
  5060. {\if\edition\racketEd
  5061. \begin{minipage}{0.3\textwidth}
  5062. \begin{lstlisting}
  5063. movq $1, v
  5064. movq $42, w
  5065. movq v, x
  5066. addq $7, x
  5067. movq x, y
  5068. movq x, z
  5069. addq w, z
  5070. movq y, t
  5071. negq t
  5072. movq z, %rax
  5073. addq t, %rax
  5074. jmp conclusion
  5075. \end{lstlisting}
  5076. \end{minipage}
  5077. $\Rightarrow\qquad$
  5078. \begin{minipage}{0.45\textwidth}
  5079. \begin{lstlisting}
  5080. movq $1, -8(%rbp)
  5081. movq $42, %rcx
  5082. movq -8(%rbp), -8(%rbp)
  5083. addq $7, -8(%rbp)
  5084. movq -8(%rbp), -16(%rbp)
  5085. movq -8(%rbp), -8(%rbp)
  5086. addq %rcx, -8(%rbp)
  5087. movq -16(%rbp), %rcx
  5088. negq %rcx
  5089. movq -8(%rbp), %rax
  5090. addq %rcx, %rax
  5091. jmp conclusion
  5092. \end{lstlisting}
  5093. \end{minipage}
  5094. \fi}
  5095. {\if\edition\pythonEd
  5096. \begin{minipage}{0.3\textwidth}
  5097. \begin{lstlisting}
  5098. movq $1, v
  5099. movq $42, w
  5100. movq v, x
  5101. addq $7, x
  5102. movq x, y
  5103. movq x, z
  5104. addq w, z
  5105. movq y, tmp_0
  5106. negq tmp_0
  5107. movq z, tmp_1
  5108. addq tmp_0, tmp_1
  5109. movq tmp_1, %rdi
  5110. callq print_int
  5111. \end{lstlisting}
  5112. \end{minipage}
  5113. $\Rightarrow\qquad$
  5114. \begin{minipage}{0.45\textwidth}
  5115. \begin{lstlisting}
  5116. movq $1, -8(%rbp)
  5117. movq $42, %rcx
  5118. movq -8(%rbp), -8(%rbp)
  5119. addq $7, -8(%rbp)
  5120. movq -8(%rbp), -16(%rbp)
  5121. movq -8(%rbp), -8(%rbp)
  5122. addq %rcx, -8(%rbp)
  5123. movq -16(%rbp), %rcx
  5124. negq %rcx
  5125. movq -8(%rbp), -8(%rbp)
  5126. addq %rcx, -8(%rbp)
  5127. movq -8(%rbp), %rdi
  5128. callq print_int
  5129. \end{lstlisting}
  5130. \end{minipage}
  5131. \fi}
  5132. \end{center}
  5133. \begin{exercise}\normalfont\normalsize
  5134. Implement the \code{allocate\_registers} pass.
  5135. Create five programs that exercise all aspects of the register
  5136. allocation algorithm, including spilling variables to the stack.
  5137. %
  5138. {\if\edition\racketEd
  5139. Replace \code{assign\_homes} in the list of \code{passes} in the
  5140. \code{run-tests.rkt} script with the three new passes:
  5141. \code{uncover\_live}, \code{build\_interference}, and
  5142. \code{allocate\_registers}.
  5143. Temporarily remove the call to \code{compiler-tests}.
  5144. Run the script to test the register allocator.
  5145. \fi}
  5146. %
  5147. {\if\edition\pythonEd
  5148. Run the \code{run-tests.py} script to to check whether the
  5149. output programs produce the same result as the input programs.
  5150. \fi}
  5151. \end{exercise}
  5152. \section{Patch Instructions}
  5153. \label{sec:patch-instructions}
  5154. The remaining step in the compilation to x86 is to ensure that the
  5155. instructions have at most one argument that is a memory access.
  5156. %
  5157. In the running example, the instruction \code{movq -8(\%rbp),
  5158. -16(\%rbp)} is problematic. Recall from Section~\ref{sec:patch-s0}
  5159. that the fix is to first move \code{-8(\%rbp)} into \code{rax} and
  5160. then move \code{rax} into \code{-16(\%rbp)}.
  5161. %
  5162. The moves from \code{-8(\%rbp)} to \code{-8(\%rbp)} are also
  5163. problematic, but they can simply be deleted. In general, we recommend
  5164. deleting all the trivial moves whose source and destination are the
  5165. same location.
  5166. %
  5167. The following is the output of \code{patch\_instructions} on the
  5168. running example.
  5169. \begin{center}
  5170. {\if\edition\racketEd
  5171. \begin{minipage}{0.4\textwidth}
  5172. \begin{lstlisting}
  5173. movq $1, -8(%rbp)
  5174. movq $42, %rcx
  5175. movq -8(%rbp), -8(%rbp)
  5176. addq $7, -8(%rbp)
  5177. movq -8(%rbp), -16(%rbp)
  5178. movq -8(%rbp), -8(%rbp)
  5179. addq %rcx, -8(%rbp)
  5180. movq -16(%rbp), %rcx
  5181. negq %rcx
  5182. movq -8(%rbp), %rax
  5183. addq %rcx, %rax
  5184. jmp conclusion
  5185. \end{lstlisting}
  5186. \end{minipage}
  5187. $\Rightarrow\qquad$
  5188. \begin{minipage}{0.45\textwidth}
  5189. \begin{lstlisting}
  5190. movq $1, -8(%rbp)
  5191. movq $42, %rcx
  5192. addq $7, -8(%rbp)
  5193. movq -8(%rbp), %rax
  5194. movq %rax, -16(%rbp)
  5195. addq %rcx, -8(%rbp)
  5196. movq -16(%rbp), %rcx
  5197. negq %rcx
  5198. movq -8(%rbp), %rax
  5199. addq %rcx, %rax
  5200. jmp conclusion
  5201. \end{lstlisting}
  5202. \end{minipage}
  5203. \fi}
  5204. {\if\edition\pythonEd
  5205. \begin{minipage}{0.4\textwidth}
  5206. \begin{lstlisting}
  5207. movq $1, -8(%rbp)
  5208. movq $42, %rcx
  5209. movq -8(%rbp), -8(%rbp)
  5210. addq $7, -8(%rbp)
  5211. movq -8(%rbp), -16(%rbp)
  5212. movq -8(%rbp), -8(%rbp)
  5213. addq %rcx, -8(%rbp)
  5214. movq -16(%rbp), %rcx
  5215. negq %rcx
  5216. movq -8(%rbp), -8(%rbp)
  5217. addq %rcx, -8(%rbp)
  5218. movq -8(%rbp), %rdi
  5219. callq print_int
  5220. \end{lstlisting}
  5221. \end{minipage}
  5222. $\Rightarrow\qquad$
  5223. \begin{minipage}{0.45\textwidth}
  5224. \begin{lstlisting}
  5225. movq $1, -8(%rbp)
  5226. movq $42, %rcx
  5227. addq $7, -8(%rbp)
  5228. movq -8(%rbp), %rax
  5229. movq %rax, -16(%rbp)
  5230. addq %rcx, -8(%rbp)
  5231. movq -16(%rbp), %rcx
  5232. negq %rcx
  5233. addq %rcx, -8(%rbp)
  5234. movq -8(%rbp), %rdi
  5235. callq print_int
  5236. \end{lstlisting}
  5237. \end{minipage}
  5238. \fi}
  5239. \end{center}
  5240. \begin{exercise}\normalfont\normalsize
  5241. %
  5242. Update the \code{patch\_instructions} compiler pass to delete trivial moves.
  5243. %
  5244. %Insert it after \code{allocate\_registers} in the list of \code{passes}
  5245. %in the \code{run-tests.rkt} script.
  5246. %
  5247. Run the script to test the \code{patch\_instructions} pass.
  5248. \end{exercise}
  5249. \section{Prelude and Conclusion}
  5250. \label{sec:print-x86-reg-alloc}
  5251. \index{subject}{calling conventions}
  5252. \index{subject}{prelude}\index{subject}{conclusion}
  5253. Recall that this pass generates the prelude and conclusion
  5254. instructions to satisfy the x86 calling conventions
  5255. (Section~\ref{sec:calling-conventions}). With the addition of the
  5256. register allocator, the callee-saved registers used by the register
  5257. allocator must be saved in the prelude and restored in the conclusion.
  5258. In the \code{allocate\_registers} pass,
  5259. %
  5260. \racket{add an entry to the \itm{info}
  5261. of \code{X86Program} named \code{used\_callee}}
  5262. %
  5263. \python{add a field named \code{used\_callee} to the \code{X86Program} AST node}
  5264. %
  5265. that stores the set of callee-saved registers that were assigned to
  5266. variables. The \code{prelude\_and\_conclusion} pass can then access
  5267. this information to decide which callee-saved registers need to be
  5268. saved and restored.
  5269. %
  5270. When calculating the amount to adjust the \code{rsp} in the prelude,
  5271. make sure to take into account the space used for saving the
  5272. callee-saved registers. Also, don't forget that the frame needs to be
  5273. a multiple of 16 bytes! We recommend using the following equation for
  5274. the amount $A$ to subtract from the \code{rsp}. Let $S$ be the number
  5275. of spilled variables and $C$ be the number of callee-saved registers
  5276. that were allocated to variables. The $\itm{align}$ function rounds a
  5277. number up to the nearest 16 bytes.
  5278. \[
  5279. \itm{A} = \itm{align}(8\itm{S} + 8\itm{C}) - 8\itm{C}
  5280. \]
  5281. The reason we subtract $8\itm{C}$ in the above equation is because the
  5282. prelude uses \code{pushq} to save each of the callee-saved registers,
  5283. and \code{pushq} subtracts $8$ from the \code{rsp}.
  5284. \racket{An overview of all of the passes involved in register
  5285. allocation is shown in Figure~\ref{fig:reg-alloc-passes}.}
  5286. {\if\edition\racketEd
  5287. \begin{figure}[tbp]
  5288. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5289. \node (Lvar) at (0,2) {\large \LangVar{}};
  5290. \node (Lvar-2) at (3,2) {\large \LangVar{}};
  5291. \node (Lvar-3) at (6,2) {\large \LangVarANF{}};
  5292. \node (Cvar-1) at (3,0) {\large \LangCVar{}};
  5293. \node (x86-2) at (3,-2) {\large \LangXVar{}};
  5294. \node (x86-3) at (6,-2) {\large \LangXVar{}};
  5295. \node (x86-4) at (9,-2) {\large \LangXInt{}};
  5296. \node (x86-5) at (9,-4) {\large \LangXInt{}};
  5297. \node (x86-2-1) at (3,-4) {\large \LangXVar{}};
  5298. \node (x86-2-2) at (6,-4) {\large \LangXVar{}};
  5299. \path[->,bend left=15] (Lvar) edge [above] node {\ttfamily\footnotesize uniquify} (Lvar-2);
  5300. \path[->,bend left=15] (Lvar-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvar-3);
  5301. \path[->,bend left=15] (Lvar-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (Cvar-1);
  5302. \path[->,bend right=15] (Cvar-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  5303. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  5304. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  5305. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  5306. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  5307. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  5308. \end{tikzpicture}
  5309. \caption{Diagram of the passes for \LangVar{} with register allocation.}
  5310. \label{fig:reg-alloc-passes}
  5311. \end{figure}
  5312. \fi}
  5313. Figure~\ref{fig:running-example-x86} shows the x86 code generated for
  5314. the running example (Figure~\ref{fig:reg-eg}). To demonstrate both the
  5315. use of registers and the stack, we limit the register allocator for
  5316. this example to use just two registers: \code{rbx} and \code{rcx}. In
  5317. the prelude\index{subject}{prelude} of the \code{main} function, we
  5318. push \code{rbx} onto the stack because it is a callee-saved register
  5319. and it was assigned to a variable by the register allocator. We
  5320. subtract \code{8} from the \code{rsp} at the end of the prelude to
  5321. reserve space for the one spilled variable. After that subtraction,
  5322. the \code{rsp} is aligned to 16 bytes.
  5323. Moving on to the program proper, we see how the registers were
  5324. allocated.
  5325. %
  5326. \racket{Variables \code{v}, \code{x}, and \code{y} were assigned to
  5327. \code{rbx} and variable \code{z} was assigned to \code{rcx}.}
  5328. %
  5329. \python{Variables \code{v}, \code{x}, \code{y}, and \code{tmp\_0}
  5330. were assigned to \code{rcx} and variables \code{w} and \code{tmp\_1}
  5331. were assigned to \code{rbx}.}
  5332. %
  5333. Variable \racket{\code{w}}\python{\code{z}} was spilled to the stack
  5334. location \code{-16(\%rbp)}. Recall that the prelude saved the
  5335. callee-save register \code{rbx} onto the stack. The spilled variables
  5336. must be placed lower on the stack than the saved callee-save
  5337. registers, so in this case \racket{\code{w}}\python{z} is placed at
  5338. \code{-16(\%rbp)}.
  5339. In the conclusion\index{subject}{conclusion}, we undo the work that was
  5340. done in the prelude. We move the stack pointer up by \code{8} bytes
  5341. (the room for spilled variables), then we pop the old values of
  5342. \code{rbx} and \code{rbp} (callee-saved registers), and finish with
  5343. \code{retq} to return control to the operating system.
  5344. \begin{figure}[tbp]
  5345. % var_test_28.rkt
  5346. % (use-minimal-set-of-registers! #t)
  5347. % and only rbx rcx
  5348. % tmp 0 rbx
  5349. % z 1 rcx
  5350. % y 0 rbx
  5351. % w 2 16(%rbp)
  5352. % v 0 rbx
  5353. % x 0 rbx
  5354. {\if\edition\racketEd
  5355. \begin{lstlisting}
  5356. start:
  5357. movq $1, %rbx
  5358. movq $42, -16(%rbp)
  5359. addq $7, %rbx
  5360. movq %rbx, %rcx
  5361. addq -16(%rbp), %rcx
  5362. negq %rbx
  5363. movq %rcx, %rax
  5364. addq %rbx, %rax
  5365. jmp conclusion
  5366. .globl main
  5367. main:
  5368. pushq %rbp
  5369. movq %rsp, %rbp
  5370. pushq %rbx
  5371. subq $8, %rsp
  5372. jmp start
  5373. conclusion:
  5374. addq $8, %rsp
  5375. popq %rbx
  5376. popq %rbp
  5377. retq
  5378. \end{lstlisting}
  5379. \fi}
  5380. {\if\edition\pythonEd
  5381. %{v: %rcx, x: %rcx, z: -16(%rbp), w: %rbx, tmp_1: %rbx, y: %rcx, tmp_0: %rcx}
  5382. \begin{lstlisting}
  5383. .globl main
  5384. main:
  5385. pushq %rbp
  5386. movq %rsp, %rbp
  5387. pushq %rbx
  5388. subq $8, %rsp
  5389. movq $1, %rcx
  5390. movq $42, %rbx
  5391. addq $7, %rcx
  5392. movq %rcx, -16(%rbp)
  5393. addq %rbx, -16(%rbp)
  5394. negq %rcx
  5395. movq -16(%rbp), %rbx
  5396. addq %rcx, %rbx
  5397. movq %rbx, %rdi
  5398. callq print_int
  5399. addq $8, %rsp
  5400. popq %rbx
  5401. popq %rbp
  5402. retq
  5403. \end{lstlisting}
  5404. \fi}
  5405. \caption{The x86 output from the running example
  5406. (Figure~\ref{fig:reg-eg}), limiting allocation to just \code{rbx}
  5407. and \code{rcx}.}
  5408. \label{fig:running-example-x86}
  5409. \end{figure}
  5410. \begin{exercise}\normalfont\normalsize
  5411. Update the \code{prelude\_and\_conclusion} pass as described in this section.
  5412. %
  5413. \racket{
  5414. In the \code{run-tests.rkt} script, add \code{prelude\_and\_conclusion} to the
  5415. list of passes and the call to \code{compiler-tests}.}
  5416. %
  5417. Run the script to test the complete compiler for \LangVar{} that
  5418. performs register allocation.
  5419. \end{exercise}
  5420. \section{Challenge: Move Biasing}
  5421. \label{sec:move-biasing}
  5422. \index{subject}{move biasing}
  5423. This section describes an enhancement to the register allocator,
  5424. called move biasing, for students who are looking for an extra
  5425. challenge.
  5426. {\if\edition\racketEd
  5427. To motivate the need for move biasing we return to the running example
  5428. but this time we use all of the general purpose registers. So we have
  5429. the following mapping of color numbers to registers.
  5430. \[
  5431. \{ 0 \mapsto \key{\%rcx}, \; 1 \mapsto \key{\%rdx}, \; 2 \mapsto \key{\%rsi}, \ldots \}
  5432. \]
  5433. Using the same assignment of variables to color numbers that was
  5434. produced by the register allocator described in the last section, we
  5435. get the following program.
  5436. \begin{center}
  5437. \begin{minipage}{0.3\textwidth}
  5438. \begin{lstlisting}
  5439. movq $1, v
  5440. movq $42, w
  5441. movq v, x
  5442. addq $7, x
  5443. movq x, y
  5444. movq x, z
  5445. addq w, z
  5446. movq y, t
  5447. negq t
  5448. movq z, %rax
  5449. addq t, %rax
  5450. jmp conclusion
  5451. \end{lstlisting}
  5452. \end{minipage}
  5453. $\Rightarrow\qquad$
  5454. \begin{minipage}{0.45\textwidth}
  5455. \begin{lstlisting}
  5456. movq $1, %rdx
  5457. movq $42, %rcx
  5458. movq %rdx, %rdx
  5459. addq $7, %rdx
  5460. movq %rdx, %rsi
  5461. movq %rdx, %rdx
  5462. addq %rcx, %rdx
  5463. movq %rsi, %rcx
  5464. negq %rcx
  5465. movq %rdx, %rax
  5466. addq %rcx, %rax
  5467. jmp conclusion
  5468. \end{lstlisting}
  5469. \end{minipage}
  5470. \end{center}
  5471. In the above output code there are two \key{movq} instructions that
  5472. can be removed because their source and target are the same. However,
  5473. if we had put \key{t}, \key{v}, \key{x}, and \key{y} into the same
  5474. register, we could instead remove three \key{movq} instructions. We
  5475. can accomplish this by taking into account which variables appear in
  5476. \key{movq} instructions with which other variables.
  5477. \fi}
  5478. {\if\edition\pythonEd
  5479. %
  5480. To motivate the need for move biasing we return to the running example
  5481. and recall that in Section~\ref{sec:patch-instructions} we were able to
  5482. remove three trivial move instructions from the running
  5483. example. However, we could remove another trivial move if we were able
  5484. to allocate \code{y} and \code{tmp\_0} to the same register. \fi}
  5485. We say that two variables $p$ and $q$ are \emph{move
  5486. related}\index{subject}{move related} if they participate together in
  5487. a \key{movq} instruction, that is, \key{movq} $p$\key{,} $q$ or
  5488. \key{movq} $q$\key{,} $p$. When deciding which variable to color next,
  5489. when there are multiple variables with the same saturation, prefer
  5490. variables that can be assigned to a color that is the same as the
  5491. color of a move related variable. Furthermore, when the register
  5492. allocator chooses a color for a variable, it should prefer a color
  5493. that has already been used for a move-related variable (assuming that
  5494. they do not interfere). Of course, this preference should not override
  5495. the preference for registers over stack locations. So this preference
  5496. should be used as a tie breaker when choosing between registers or
  5497. when choosing between stack locations.
  5498. We recommend representing the move relationships in a graph, similar
  5499. to how we represented interference. The following is the \emph{move
  5500. graph} for our running example.
  5501. {\if\edition\racketEd
  5502. \[
  5503. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5504. \node (rax) at (0,0) {$\ttm{rax}$};
  5505. \node (rsp) at (9,2) {$\ttm{rsp}$};
  5506. \node (t) at (0,2) {$\ttm{t}$};
  5507. \node (z) at (3,2) {$\ttm{z}$};
  5508. \node (x) at (6,2) {$\ttm{x}$};
  5509. \node (y) at (3,0) {$\ttm{y}$};
  5510. \node (w) at (6,0) {$\ttm{w}$};
  5511. \node (v) at (9,0) {$\ttm{v}$};
  5512. \draw (v) to (x);
  5513. \draw (x) to (y);
  5514. \draw (x) to (z);
  5515. \draw (y) to (t);
  5516. \end{tikzpicture}
  5517. \]
  5518. \fi}
  5519. %
  5520. {\if\edition\pythonEd
  5521. \[
  5522. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5523. \node (t0) at (0,2) {$\ttm{tmp\_0}$};
  5524. \node (t1) at (0,0) {$\ttm{tmp\_1}$};
  5525. \node (z) at (3,2) {$\ttm{z}$};
  5526. \node (x) at (6,2) {$\ttm{x}$};
  5527. \node (y) at (3,0) {$\ttm{y}$};
  5528. \node (w) at (6,0) {$\ttm{w}$};
  5529. \node (v) at (9,0) {$\ttm{v}$};
  5530. \draw (y) to (t0);
  5531. \draw (z) to (x);
  5532. \draw (z) to (t1);
  5533. \draw (x) to (y);
  5534. \draw (x) to (v);
  5535. \end{tikzpicture}
  5536. \]
  5537. \fi}
  5538. {\if\edition\racketEd
  5539. Now we replay the graph coloring, pausing to see the coloring of
  5540. \code{y}. Recall the following configuration. The most saturated vertices
  5541. were \code{w} and \code{y}.
  5542. \[
  5543. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5544. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5545. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5546. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5547. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5548. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5549. \node (y) at (3,0) {$\ttm{y}:-,\{1,-2\}$};
  5550. \node (w) at (6,0) {$\ttm{w}:-,\{1,-2\}$};
  5551. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5552. \draw (t1) to (rax);
  5553. \draw (t1) to (z);
  5554. \draw (z) to (y);
  5555. \draw (z) to (w);
  5556. \draw (x) to (w);
  5557. \draw (y) to (w);
  5558. \draw (v) to (w);
  5559. \draw (v) to (rsp);
  5560. \draw (w) to (rsp);
  5561. \draw (x) to (rsp);
  5562. \draw (y) to (rsp);
  5563. \path[-.,bend left=15] (z) edge node {} (rsp);
  5564. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5565. \draw (rax) to (rsp);
  5566. \end{tikzpicture}
  5567. \]
  5568. %
  5569. Last time we chose to color \code{w} with $0$. But this time we see
  5570. that \code{w} is not move related to any vertex, but \code{y} is move
  5571. related to \code{t}. So we choose to color \code{y} with $0$, the
  5572. same color as \code{t}.
  5573. \[
  5574. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5575. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5576. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5577. \node (t1) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5578. \node (z) at (3,2) {$\ttm{z}:1,\{0,-2\}$};
  5579. \node (x) at (6,2) {$\ttm{x}:-,\{-2\}$};
  5580. \node (y) at (3,0) {$\ttm{y}:0,\{1,-2\}$};
  5581. \node (w) at (6,0) {$\ttm{w}:-,\{0,1,-2\}$};
  5582. \node (v) at (9,0) {$\ttm{v}:-,\{-2\}$};
  5583. \draw (t1) to (rax);
  5584. \draw (t1) to (z);
  5585. \draw (z) to (y);
  5586. \draw (z) to (w);
  5587. \draw (x) to (w);
  5588. \draw (y) to (w);
  5589. \draw (v) to (w);
  5590. \draw (v) to (rsp);
  5591. \draw (w) to (rsp);
  5592. \draw (x) to (rsp);
  5593. \draw (y) to (rsp);
  5594. \path[-.,bend left=15] (z) edge node {} (rsp);
  5595. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5596. \draw (rax) to (rsp);
  5597. \end{tikzpicture}
  5598. \]
  5599. Now \code{w} is the most saturated, so we color it $2$.
  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,-2\}$};
  5606. \node (x) at (6,2) {$\ttm{x}:-,\{2,-2\}$};
  5607. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5608. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5609. \node (v) at (9,0) {$\ttm{v}:-,\{2,-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. At this point, vertices \code{x} and \code{v} are most saturated, but
  5627. \code{x} is move related to \code{y} and \code{z}, so we color
  5628. \code{x} to $0$ to match \code{y}. Finally, we color \code{v} to $0$.
  5629. \[
  5630. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5631. \node (rax) at (0,0) {$\ttm{rax}:-1,\{0,-2\}$};
  5632. \node (rsp) at (9,2) {$\ttm{rsp}:-2,\{-1,0,1,2\}$};
  5633. \node (t) at (0,2) {$\ttm{t}:0,\{1,-2\}$};
  5634. \node (z) at (3,2) {$\ttm{z}:1,\{0,2,-2\}$};
  5635. \node (x) at (6,2) {$\ttm{x}:0,\{2,-2\}$};
  5636. \node (y) at (3,0) {$\ttm{y}:0,\{1,2,-2\}$};
  5637. \node (w) at (6,0) {$\ttm{w}:2,\{0,1,-2\}$};
  5638. \node (v) at (9,0) {$\ttm{v}:0,\{2,-2\}$};
  5639. \draw (t1) to (rax);
  5640. \draw (t) to (z);
  5641. \draw (z) to (y);
  5642. \draw (z) to (w);
  5643. \draw (x) to (w);
  5644. \draw (y) to (w);
  5645. \draw (v) to (w);
  5646. \draw (v) to (rsp);
  5647. \draw (w) to (rsp);
  5648. \draw (x) to (rsp);
  5649. \draw (y) to (rsp);
  5650. \path[-.,bend left=15] (z) edge node {} (rsp);
  5651. \path[-.,bend left=10] (t1) edge node {} (rsp);
  5652. \draw (rax) to (rsp);
  5653. \end{tikzpicture}
  5654. \]
  5655. \fi}
  5656. %
  5657. {\if\edition\pythonEd
  5658. Now we replay the graph coloring, pausing before the coloring of
  5659. \code{w}. Recall the following configuration. The most saturated vertices
  5660. were \code{tmp\_1}, \code{w}, and \code{y}.
  5661. \[
  5662. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5663. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5664. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5665. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5666. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5667. \node (y) at (3,0) {$\ttm{y}: -, \{1\}$};
  5668. \node (w) at (6,0) {$\ttm{w}: -, \{1\}$};
  5669. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5670. \draw (t0) to (t1);
  5671. \draw (t0) to (z);
  5672. \draw (z) to (y);
  5673. \draw (z) to (w);
  5674. \draw (x) to (w);
  5675. \draw (y) to (w);
  5676. \draw (v) to (w);
  5677. \end{tikzpicture}
  5678. \]
  5679. We have arbitrarily chosen to color \code{w} instead of \code{tmp\_1}
  5680. or \code{y}, but note that \code{w} is not move related to any
  5681. variables, whereas \code{y} and \code{tmp\_1} are move related to
  5682. \code{tmp\_0} and \code{z}, respectively. If we instead choose
  5683. \code{y} and color it $0$, we can delete another move instruction.
  5684. \[
  5685. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5686. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5687. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5688. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5689. \node (x) at (6,2) {$\ttm{x}: -, \{\}$};
  5690. \node (y) at (3,0) {$\ttm{y}: 0, \{1\}$};
  5691. \node (w) at (6,0) {$\ttm{w}: -, \{0,1\}$};
  5692. \node (v) at (9,0) {$\ttm{v}: -, \{\}$};
  5693. \draw (t0) to (t1);
  5694. \draw (t0) to (z);
  5695. \draw (z) to (y);
  5696. \draw (z) to (w);
  5697. \draw (x) to (w);
  5698. \draw (y) to (w);
  5699. \draw (v) to (w);
  5700. \end{tikzpicture}
  5701. \]
  5702. Now \code{w} is the most saturated, so we color it $2$.
  5703. \[
  5704. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5705. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5706. \node (t1) at (0,0) {$\ttm{tmp\_1}: -, \{0\}$};
  5707. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5708. \node (x) at (6,2) {$\ttm{x}: -, \{2\}$};
  5709. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5710. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5711. \node (v) at (9,0) {$\ttm{v}: -, \{2\}$};
  5712. \draw (t0) to (t1);
  5713. \draw (t0) to (z);
  5714. \draw (z) to (y);
  5715. \draw (z) to (w);
  5716. \draw (x) to (w);
  5717. \draw (y) to (w);
  5718. \draw (v) to (w);
  5719. \end{tikzpicture}
  5720. \]
  5721. To finish the coloring, \code{x} and \code{v} get $0$ and
  5722. \code{tmp\_1} gets $1$.
  5723. \[
  5724. \begin{tikzpicture}[baseline=(current bounding box.center)]
  5725. \node (t0) at (0,2) {$\ttm{tmp\_0}: 0, \{1\}$};
  5726. \node (t1) at (0,0) {$\ttm{tmp\_1}: 1, \{0\}$};
  5727. \node (z) at (3,2) {$\ttm{z}: 1, \{0\}$};
  5728. \node (x) at (6,2) {$\ttm{x}: 0, \{2\}$};
  5729. \node (y) at (3,0) {$\ttm{y}: 0, \{1,2\}$};
  5730. \node (w) at (6,0) {$\ttm{w}: 2, \{0,1\}$};
  5731. \node (v) at (9,0) {$\ttm{v}: 0, \{2\}$};
  5732. \draw (t0) to (t1);
  5733. \draw (t0) to (z);
  5734. \draw (z) to (y);
  5735. \draw (z) to (w);
  5736. \draw (x) to (w);
  5737. \draw (y) to (w);
  5738. \draw (v) to (w);
  5739. \end{tikzpicture}
  5740. \]
  5741. \fi}
  5742. So we have the following assignment of variables to registers.
  5743. {\if\edition\racketEd
  5744. \begin{gather*}
  5745. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5746. \ttm{w} \mapsto \key{\%rsi}, \,
  5747. \ttm{x} \mapsto \key{\%rcx}, \,
  5748. \ttm{y} \mapsto \key{\%rcx}, \,
  5749. \ttm{z} \mapsto \key{\%rdx}, \,
  5750. \ttm{t} \mapsto \key{\%rcx} \}
  5751. \end{gather*}
  5752. \fi}
  5753. {\if\edition\pythonEd
  5754. \begin{gather*}
  5755. \{ \ttm{v} \mapsto \key{\%rcx}, \,
  5756. \ttm{w} \mapsto \key{-16(\%rbp)}, \,
  5757. \ttm{x} \mapsto \key{\%rcx}, \,
  5758. \ttm{y} \mapsto \key{\%rcx}, \\
  5759. \ttm{z} \mapsto \key{-8(\%rbp)}, \,
  5760. \ttm{tmp\_0} \mapsto \key{\%rcx}, \,
  5761. \ttm{tmp\_1} \mapsto \key{-8(\%rbp)} \}
  5762. \end{gather*}
  5763. \fi}
  5764. We apply this register assignment to the running example, on the left,
  5765. to obtain the code in the middle. The \code{patch\_instructions} then
  5766. deletes the trivial moves to obtain the code on the right.
  5767. {\if\edition\racketEd
  5768. \begin{minipage}{0.25\textwidth}
  5769. \begin{lstlisting}
  5770. movq $1, v
  5771. movq $42, w
  5772. movq v, x
  5773. addq $7, x
  5774. movq x, y
  5775. movq x, z
  5776. addq w, z
  5777. movq y, t
  5778. negq t
  5779. movq z, %rax
  5780. addq t, %rax
  5781. jmp conclusion
  5782. \end{lstlisting}
  5783. \end{minipage}
  5784. $\Rightarrow\qquad$
  5785. \begin{minipage}{0.25\textwidth}
  5786. \begin{lstlisting}
  5787. movq $1, %rcx
  5788. movq $42, %rsi
  5789. movq %rcx, %rcx
  5790. addq $7, %rcx
  5791. movq %rcx, %rcx
  5792. movq %rcx, %rdx
  5793. addq %rsi, %rdx
  5794. movq %rcx, %rcx
  5795. negq %rcx
  5796. movq %rdx, %rax
  5797. addq %rcx, %rax
  5798. jmp conclusion
  5799. \end{lstlisting}
  5800. \end{minipage}
  5801. $\Rightarrow\qquad$
  5802. \begin{minipage}{0.25\textwidth}
  5803. \begin{lstlisting}
  5804. movq $1, %rcx
  5805. movq $42, %rsi
  5806. addq $7, %rcx
  5807. movq %rcx, %rdx
  5808. addq %rsi, %rdx
  5809. negq %rcx
  5810. movq %rdx, %rax
  5811. addq %rcx, %rax
  5812. jmp conclusion
  5813. \end{lstlisting}
  5814. \end{minipage}
  5815. \fi}
  5816. {\if\edition\pythonEd
  5817. \begin{minipage}{0.20\textwidth}
  5818. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5819. movq $1, v
  5820. movq $42, w
  5821. movq v, x
  5822. addq $7, x
  5823. movq x, y
  5824. movq x, z
  5825. addq w, z
  5826. movq y, tmp_0
  5827. negq tmp_0
  5828. movq z, tmp_1
  5829. addq tmp_0, tmp_1
  5830. movq tmp_1, %rdi
  5831. callq _print_int
  5832. \end{lstlisting}
  5833. \end{minipage}
  5834. ${\Rightarrow\qquad}$
  5835. \begin{minipage}{0.30\textwidth}
  5836. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5837. movq $1, %rcx
  5838. movq $42, -16(%rbp)
  5839. movq %rcx, %rcx
  5840. addq $7, %rcx
  5841. movq %rcx, %rcx
  5842. movq %rcx, -8(%rbp)
  5843. addq -16(%rbp), -8(%rbp)
  5844. movq %rcx, %rcx
  5845. negq %rcx
  5846. movq -8(%rbp), -8(%rbp)
  5847. addq %rcx, -8(%rbp)
  5848. movq -8(%rbp), %rdi
  5849. callq _print_int
  5850. \end{lstlisting}
  5851. \end{minipage}
  5852. ${\Rightarrow\qquad}$
  5853. \begin{minipage}{0.20\textwidth}
  5854. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  5855. movq $1, %rcx
  5856. movq $42, -16(%rbp)
  5857. addq $7, %rcx
  5858. movq %rcx, -8(%rbp)
  5859. movq -16(%rbp), %rax
  5860. addq %rax, -8(%rbp)
  5861. negq %rcx
  5862. addq %rcx, -8(%rbp)
  5863. movq -8(%rbp), %rdi
  5864. callq print_int
  5865. \end{lstlisting}
  5866. \end{minipage}
  5867. \fi}
  5868. \begin{exercise}\normalfont\normalsize
  5869. Change your implementation of \code{allocate\_registers} to take move
  5870. biasing into account. Create two new tests that include at least one
  5871. opportunity for move biasing and visually inspect the output x86
  5872. programs to make sure that your move biasing is working properly. Make
  5873. sure that your compiler still passes all of the tests.
  5874. \end{exercise}
  5875. %To do: another neat challenge would be to do
  5876. % live range splitting~\citep{Cooper:1998ly}. \\ --Jeremy
  5877. %% \subsection{Output of the Running Example}
  5878. %% \label{sec:reg-alloc-output}
  5879. % challenge: prioritize variables based on execution frequencies
  5880. % and the number of uses of a variable
  5881. % challenge: enhance the coloring algorithm using Chaitin's
  5882. % approach of prioritizing high-degree variables
  5883. % by removing low-degree variables (coloring them later)
  5884. % from the interference graph
  5885. \section{Further Reading}
  5886. \label{sec:register-allocation-further-reading}
  5887. Early register allocation algorithms were developed for Fortran
  5888. compilers in the 1950s~\citep{Horwitz:1966aa,Backus:1978aa}. The use
  5889. of graph coloring began in the late 1970s and early 1980s with the
  5890. work of \citet{Chaitin:1981vl} on an optimizing compiler for PL/I. The
  5891. algorithm is based on the following observation of
  5892. \citet{Kempe:1879aa}. If a graph $G$ has a vertex $v$ with degree
  5893. lower than $k$, then $G$ is $k$ colorable if the subgraph of $G$ with
  5894. $v$ removed is also $k$ colorable. To see why, suppose that the
  5895. subgraph is $k$ colorable. At worst the neighbors of $v$ are assigned
  5896. different colors, but since there are less than $k$ neighbors, there
  5897. will be one or more colors left over to use for coloring $v$ in $G$.
  5898. The algorithm of \citet{Chaitin:1981vl} removes a vertex $v$ of degree
  5899. less than $k$ from the graph and recursively colors the rest of the
  5900. graph. Upon returning from the recursion, it colors $v$ with one of
  5901. the available colors and returns. \citet{Chaitin:1982vn} augments
  5902. this algorithm to handle spilling as follows. If there are no vertices
  5903. of degree lower than $k$ then pick a vertex at random, spill it,
  5904. remove it from the graph, and proceed recursively to color the rest of
  5905. the graph.
  5906. Prior to coloring, \citet{Chaitin:1981vl} merge variables that are
  5907. move-related and that don't interfere with each other, a process
  5908. called \emph{coalescing}. While coalescing decreases the number of
  5909. moves, it can make the graph more difficult to
  5910. color. \citet{Briggs:1994kx} propose \emph{conservative coalescing} in
  5911. which two variables are merged only if they have fewer than $k$
  5912. neighbors of high degree. \citet{George:1996aa} observe that
  5913. conservative coalescing is sometimes too conservative and make it more
  5914. aggressive by iterating the coalescing with the removal of low-degree
  5915. vertices.
  5916. %
  5917. Attacking the problem from a different angle, \citet{Briggs:1994kx}
  5918. also propose \emph{biased coloring} in which a variable is assigned to
  5919. the same color as another move-related variable if possible, as
  5920. discussed in Section~\ref{sec:move-biasing}.
  5921. %
  5922. The algorithm of \citet{Chaitin:1981vl} and its successors iteratively
  5923. performs coalescing, graph coloring, and spill code insertion until
  5924. all variables have been assigned a location.
  5925. \citet{Briggs:1994kx} observes that \citet{Chaitin:1982vn} sometimes
  5926. spills variables that don't have to be: a high-degree variable can be
  5927. colorable if many of its neighbors are assigned the same color.
  5928. \citet{Briggs:1994kx} propose \emph{optimistic coloring}, in which a
  5929. high-degree vertex is not immediately spilled. Instead the decision is
  5930. deferred until after the recursive call, at which point it is apparent
  5931. whether there is actually an available color or not. We observe that
  5932. this algorithm is equivalent to the smallest-last ordering
  5933. algorithm~\citep{Matula:1972aa} if one takes the first $k$ colors to
  5934. be registers and the rest to be stack locations.
  5935. %% biased coloring
  5936. Earlier editions of the compiler course at Indiana University
  5937. \citep{Dybvig:2010aa} were based on the algorithm of
  5938. \citet{Briggs:1994kx}.
  5939. The smallest-last ordering algorithm is one of many \emph{greedy}
  5940. coloring algorithms. A greedy coloring algorithm visits all the
  5941. vertices in a particular order and assigns each one the first
  5942. available color. An \emph{offline} greedy algorithm chooses the
  5943. ordering up-front, prior to assigning colors. The algorithm of
  5944. \citet{Chaitin:1981vl} should be considered offline because the vertex
  5945. ordering does not depend on the colors assigned. Other orderings are
  5946. possible. For example, \citet{Chow:1984ys} order variables according
  5947. to an estimate of runtime cost.
  5948. An \emph{online} greedy coloring algorithm uses information about the
  5949. current assignment of colors to influence the order in which the
  5950. remaining vertices are colored. The saturation-based algorithm
  5951. described in this chapter is one such algorithm. We choose to use
  5952. saturation-based coloring because it is fun to introduce graph
  5953. coloring via Sudoku!
  5954. A register allocator may choose to map each variable to just one
  5955. location, as in \citet{Chaitin:1981vl}, or it may choose to map a
  5956. variable to one or more locations. The later can be achieved by
  5957. \emph{live range splitting}, where a variable is replaced by several
  5958. variables that each handle part of its live
  5959. range~\citep{Chow:1984ys,Briggs:1994kx,Cooper:1998ly}.
  5960. %% 1950s, Sheldon Best, Fortran \cite{Backus:1978aa}, Belady's page
  5961. %% replacement algorithm, bottom-up local
  5962. %% \citep{Horwitz:1966aa} straight-line programs, single basic block,
  5963. %% Cooper: top-down (priority bassed), bottom-up
  5964. %% top-down
  5965. %% order variables by priority (estimated cost)
  5966. %% caveat: split variables into two groups:
  5967. %% constrained (>k neighbors) and unconstrained (<k neighbors)
  5968. %% color the constrained ones first
  5969. %% \citet{Schwartz:1975aa} graph-coloring, no spill
  5970. %% cite J. Cocke for an algorithm that colors variables
  5971. %% in a high-degree first ordering
  5972. %Register Allocation via Usage Counts, Freiburghouse CACM
  5973. \citet{Palsberg:2007si} observe that many of the interference graphs
  5974. that arise from Java programs in the JoeQ compiler are \emph{chordal},
  5975. that is, every cycle with four or more edges has an edge which is not
  5976. part of the cycle but which connects two vertices on the cycle. Such
  5977. graphs can be optimally colored by the greedy algorithm with a vertex
  5978. ordering determined by maximum cardinality search.
  5979. In situations where compile time is of utmost importance, such as in
  5980. just-in-time compilers, graph coloring algorithms can be too expensive
  5981. and the linear scan algorithm of \citet{Poletto:1999uq} may be more
  5982. appropriate.
  5983. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  5984. \chapter{Booleans and Conditionals}
  5985. \label{ch:Lif}
  5986. \index{subject}{Boolean}
  5987. \index{subject}{control flow}
  5988. \index{subject}{conditional expression}
  5989. The \LangVar{} language only has a single kind of value, the
  5990. integers. In this chapter we add a second kind of value, the Booleans,
  5991. to create the \LangIf{} language. The Boolean values \emph{true} and
  5992. \emph{false} are written \TRUE{} and \FALSE{} respectively in
  5993. \racket{Racket}\python{Python}. The \LangIf{} language includes
  5994. several operations that involve Booleans (\key{and}, \key{not},
  5995. \racket{\key{eq?}}\python{==}, \key{<}, etc.) and the \key{if}
  5996. expression \python{and statement}. With the addition of \key{if},
  5997. programs can have non-trivial control flow which
  5998. %
  5999. \racket{impacts \code{explicate\_control} and liveness analysis}
  6000. %
  6001. \python{impacts liveness analysis and motivates a new pass named
  6002. \code{explicate\_control}}.
  6003. %
  6004. Also, because we now have two kinds of values, we need to handle
  6005. programs that apply an operation to the wrong kind of value, such as
  6006. \racket{\code{(not 1)}}\python{\code{not 1}}.
  6007. There are two language design options for such situations. One option
  6008. is to signal an error and the other is to provide a wider
  6009. interpretation of the operation. \racket{The Racket
  6010. language}\python{Python} uses a mixture of these two options,
  6011. depending on the operation and the kind of value. For example, the
  6012. result of \racket{\code{(not 1)}}\python{\code{not 1}} is
  6013. \racket{\code{\#f}}\python{False} because \racket{Racket}\python{Python}
  6014. treats non-zero integers as if they were \racket{\code{\#t}}\python{\code{True}}.
  6015. %
  6016. \racket{On the other hand, \code{(car 1)} results in a run-time error
  6017. in Racket because \code{car} expects a pair.}
  6018. %
  6019. \python{On the other hand, \code{1[0]} results in a run-time error
  6020. in Python because an ``\code{int} object is not subscriptable''.}
  6021. \racket{Typed Racket}\python{The MyPy type checker} makes similar
  6022. design choices as \racket{Racket}\python{Python}, except much of the
  6023. error detection happens at compile time instead of run
  6024. time\python{~\citep{Lehtosalo2021:MyPy}}. \racket{Typed Racket}\python{MyPy}
  6025. accepts \racket{\code{(not 1)}}\python{\code{not 1}}. But in the case
  6026. of \racket{\code{(car 1)}}\python{\code{1[0]}}, \racket{Typed
  6027. Racket}\python{MyPy} reports a compile-time error
  6028. %
  6029. \racket{because Racket expects the type of the argument to be of the form
  6030. \code{(Listof T)} or \code{(Pairof T1 T2)}.}
  6031. %
  6032. \python{stating that a ``value of type \code{int} is not indexable''.}
  6033. The \LangIf{} language performs type checking during compilation like
  6034. \racket{Typed Racket}\python{MyPy}. In Chapter~\ref{ch:Ldyn} we study
  6035. the alternative choice, that is, a dynamically typed language like
  6036. \racket{Racket}\python{Python}. The \LangIf{} language is a subset of
  6037. \racket{Typed Racket}\python{MyPy}; for some operations we are more
  6038. restrictive, for example, rejecting \racket{\code{(not
  6039. 1)}}\python{\code{not 1}}. We keep the type checker for \LangIf{}
  6040. fairly simple because the focus of this book is on compilation, not
  6041. type systems, about which there are already several excellent
  6042. books~\citep{Pierce:2002hj,Pierce:2004fk,Harper2016,Pierce:SF2}.
  6043. This chapter is organized as follows. We begin by defining the syntax
  6044. and interpreter for the \LangIf{} language
  6045. (Section~\ref{sec:lang-if}). We then introduce the idea of type
  6046. checking and define a type checker for \LangIf{}
  6047. (Section~\ref{sec:type-check-Lif}).
  6048. %
  6049. \racket{To compile \LangIf{} we need to enlarge the intermediate
  6050. language \LangCVar{} into \LangCIf{} (Section~\ref{sec:Cif}) and
  6051. \LangXInt{} into \LangXIf{} (Section~\ref{sec:x86-if}).}
  6052. %
  6053. The remaining sections of this chapter discuss how Booleans and
  6054. conditional control flow require changes to the existing compiler
  6055. passes and the addition of new ones. We introduce the \code{shrink}
  6056. pass to translates some operators into others, thereby reducing the
  6057. number of operators that need to be handled in later passes.
  6058. %
  6059. The main event of this chapter is the \code{explicate\_control} pass
  6060. that is responsible for translating \code{if}'s into conditional
  6061. \code{goto}'s (Section~\ref{sec:explicate-control-Lif}).
  6062. %
  6063. Regarding register allocation, there is the interesting question of
  6064. how to handle conditional \code{goto}'s during liveness analysis.
  6065. \section{The \LangIf{} Language}
  6066. \label{sec:lang-if}
  6067. The concrete and abstract syntax of the \LangIf{} language are defined in
  6068. Figures~\ref{fig:Lif-concrete-syntax} and~\ref{fig:Lif-syntax},
  6069. respectively. The \LangIf{} language includes all of
  6070. \LangVar{} {(shown in gray)}, the Boolean literals \TRUE{} and
  6071. \FALSE{},\racket{ and} the \code{if} expression\python{, and the
  6072. \code{if} statement}. We expand the set of operators to include
  6073. \begin{enumerate}
  6074. \item the logical operators \key{and}, \key{or}, and \key{not},
  6075. \item the \racket{\key{eq?} operation}\python{\key{==} and \key{!=} operations}
  6076. for comparing integers or Booleans for equality, and
  6077. \item the \key{<}, \key{<=}, \key{>}, and \key{>=} operations for
  6078. comparing integers.
  6079. \end{enumerate}
  6080. \racket{We reorganize the abstract syntax for the primitive
  6081. operations in Figure~\ref{fig:Lif-syntax}, using only one grammar
  6082. rule for all of them. This means that the grammar no longer checks
  6083. whether the arity of an operators matches the number of
  6084. arguments. That responsibility is moved to the type checker for
  6085. \LangIf{} (Section~\ref{sec:type-check-Lif}).}
  6086. \newcommand{\LifGrammarRacket}{
  6087. \begin{array}{lcl}
  6088. \Type &::=& \key{Boolean} \\
  6089. \itm{bool} &::=& \TRUE \MID \FALSE \\
  6090. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6091. \Exp &::=& \itm{bool}
  6092. \MID (\key{and}\;\Exp\;\Exp) \MID (\key{or}\;\Exp\;\Exp)
  6093. \MID (\key{not}\;\Exp) \\
  6094. &\MID& (\itm{cmp}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp}
  6095. \end{array}
  6096. }
  6097. \newcommand{\LifASTRacket}{
  6098. \begin{array}{lcl}
  6099. \Type &::=& \key{Boolean} \\
  6100. \itm{bool} &::=& \code{\#t} \MID \code{\#f} \\
  6101. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6102. \itm{op} &::= & \itm{cmp} \MID \code{and} \MID \code{or} \MID \code{not} \\
  6103. \Exp &::=& \BOOL{\itm{bool}} \MID \IF{\Exp}{\Exp}{\Exp}
  6104. \end{array}
  6105. }
  6106. \newcommand{\LintOpAST}{
  6107. \begin{array}{rcl}
  6108. \Type &::=& \key{Integer} \\
  6109. \itm{op} &::= & \code{read} \MID \code{+} \MID \code{-}\\
  6110. \Exp{} &::=& \INT{\Int} \MID \PRIM{\itm{op}}{\Exp\ldots}
  6111. \end{array}
  6112. }
  6113. \newcommand{\LifGrammarPython}{
  6114. \begin{array}{rcl}
  6115. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  6116. \Exp &::=& \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp} \MID \COR{\Exp}{\Exp}
  6117. \MID \key{not}~\Exp \\
  6118. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  6119. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  6120. \Stmt &::=& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  6121. \end{array}
  6122. }
  6123. \newcommand{\LifASTPython}{
  6124. \begin{array}{lcl}
  6125. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  6126. \itm{unaryop} &::=& \code{Not()} \\
  6127. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  6128. \itm{bool} &::=& \code{True} \MID \code{False} \\
  6129. \Exp &::=& \BOOL{\itm{bool}}
  6130. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  6131. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  6132. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  6133. \end{array}
  6134. }
  6135. \begin{figure}[tp]
  6136. \centering
  6137. \fbox{
  6138. \begin{minipage}{0.96\textwidth}
  6139. {\if\edition\racketEd
  6140. \[
  6141. \begin{array}{l}
  6142. \gray{\LintGrammarRacket{}} \\ \hline
  6143. \gray{\LvarGrammarRacket{}} \\ \hline
  6144. \LifGrammarRacket{} \\
  6145. \begin{array}{lcl}
  6146. \LangIfM{} &::=& \Exp
  6147. \end{array}
  6148. \end{array}
  6149. \]
  6150. \fi}
  6151. {\if\edition\pythonEd
  6152. \[
  6153. \begin{array}{l}
  6154. \gray{\LintGrammarPython} \\ \hline
  6155. \gray{\LvarGrammarPython} \\ \hline
  6156. \LifGrammarPython \\
  6157. \begin{array}{rcl}
  6158. \LangIfM{} &::=& \Stmt^{*}
  6159. \end{array}
  6160. \end{array}
  6161. \]
  6162. \fi}
  6163. \end{minipage}
  6164. }
  6165. \caption{The concrete syntax of \LangIf{}, extending \LangVar{}
  6166. (Figure~\ref{fig:Lvar-concrete-syntax}) with Booleans and conditionals.}
  6167. \label{fig:Lif-concrete-syntax}
  6168. \end{figure}
  6169. \begin{figure}[tp]
  6170. \centering
  6171. \fbox{
  6172. \begin{minipage}{0.96\textwidth}
  6173. {\if\edition\racketEd
  6174. \[
  6175. \begin{array}{l}
  6176. \gray{\LintOpAST} \\ \hline
  6177. \gray{\LvarASTRacket{}} \\ \hline
  6178. \LifASTRacket{} \\
  6179. \begin{array}{lcl}
  6180. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Exp}
  6181. \end{array}
  6182. \end{array}
  6183. \]
  6184. \fi}
  6185. {\if\edition\pythonEd
  6186. \[
  6187. \begin{array}{l}
  6188. \gray{\LintASTPython} \\ \hline
  6189. \gray{\LvarASTPython} \\ \hline
  6190. \LifASTPython \\
  6191. \begin{array}{lcl}
  6192. \LangIfM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  6193. \end{array}
  6194. \end{array}
  6195. \]
  6196. \fi}
  6197. \end{minipage}
  6198. }
  6199. \caption{The abstract syntax of \LangIf{}.}
  6200. \label{fig:Lif-syntax}
  6201. \end{figure}
  6202. Figure~\ref{fig:interp-Lif} defines the interpreter for \LangIf{},
  6203. which inherits from the interpreter for \LangVar{}
  6204. (Figure~\ref{fig:interp-Lvar}). The literals \TRUE{} and \FALSE{}
  6205. evaluate to the corresponding Boolean values. The conditional
  6206. expression $\CIF{e_1}{e_2}{\itm{e_3}}$ evaluates expression $e_1$
  6207. and then either evaluates $e_2$ or $e_3$ depending on whether
  6208. $e_1$ produced \TRUE{} or \FALSE{}. The logical operations
  6209. \code{and}, \code{or}, and \code{not} behave according to
  6210. propositional logic. In addition, the \code{and} and \code{or}
  6211. operations perform \emph{short-circuit evaluation}.
  6212. %
  6213. That is, given the expression $\CAND{e_1}{e_2}$, the expression $e_2$
  6214. is not evaluated if $e_1$ evaluates to \FALSE{}.
  6215. %
  6216. Similarly, given $\COR{e_1}{e_2}$, the expression $e_2$ is not
  6217. evaluated if $e_1$ evaluates to \TRUE{}.
  6218. \racket{With the increase in the number of primitive operations, the
  6219. interpreter would become repetitive without some care. We refactor
  6220. the case for \code{Prim}, moving the code that differs with each
  6221. operation into the \code{interp\_op} method shown in in
  6222. Figure~\ref{fig:interp-op-Lif}. We handle the \code{and} and
  6223. \code{or} operations separately because of their short-circuiting
  6224. behavior.}
  6225. \begin{figure}[tbp]
  6226. {\if\edition\racketEd
  6227. \begin{lstlisting}
  6228. (define interp_Lif_class
  6229. (class interp_Lvar_class
  6230. (super-new)
  6231. (define/public (interp_op op) ...)
  6232. (define/override ((interp_exp env) e)
  6233. (define recur (interp_exp env))
  6234. (match e
  6235. [(Bool b) b]
  6236. [(If cnd thn els)
  6237. (match (recur cnd)
  6238. [#t (recur thn)]
  6239. [#f (recur els)])]
  6240. [(Prim 'and (list e1 e2))
  6241. (match (recur e1)
  6242. [#t (match (recur e2) [#t #t] [#f #f])]
  6243. [#f #f])]
  6244. [(Prim 'or (list e1 e2))
  6245. (define v1 (recur e1))
  6246. (match v1
  6247. [#t #t]
  6248. [#f (match (recur e2) [#t #t] [#f #f])])]
  6249. [(Prim op args)
  6250. (apply (interp_op op) (for/list ([e args]) (recur e)))]
  6251. [else ((super interp_exp env) e)]))
  6252. ))
  6253. (define (interp_Lif p)
  6254. (send (new interp_Lif_class) interp_program p))
  6255. \end{lstlisting}
  6256. \fi}
  6257. {\if\edition\pythonEd
  6258. \begin{lstlisting}
  6259. class InterpLif(InterpLvar):
  6260. def interp_exp(self, e, env):
  6261. match e:
  6262. case IfExp(test, body, orelse):
  6263. if self.interp_exp(test, env):
  6264. return self.interp_exp(body, env)
  6265. else:
  6266. return self.interp_exp(orelse, env)
  6267. case UnaryOp(Not(), v):
  6268. return not self.interp_exp(v, env)
  6269. case BoolOp(And(), values):
  6270. if self.interp_exp(values[0], env):
  6271. return self.interp_exp(values[1], env)
  6272. else:
  6273. return False
  6274. case BoolOp(Or(), values):
  6275. if self.interp_exp(values[0], env):
  6276. return True
  6277. else:
  6278. return self.interp_exp(values[1], env)
  6279. case Compare(left, [cmp], [right]):
  6280. l = self.interp_exp(left, env)
  6281. r = self.interp_exp(right, env)
  6282. return self.interp_cmp(cmp)(l, r)
  6283. case _:
  6284. return super().interp_exp(e, env)
  6285. def interp_stmts(self, ss, env):
  6286. if len(ss) == 0:
  6287. return
  6288. match ss[0]:
  6289. case If(test, body, orelse):
  6290. if self.interp_exp(test, env):
  6291. return self.interp_stmts(body + ss[1:], env)
  6292. else:
  6293. return self.interp_stmts(orelse + ss[1:], env)
  6294. case _:
  6295. return super().interp_stmts(ss, env)
  6296. ...
  6297. \end{lstlisting}
  6298. \fi}
  6299. \caption{Interpreter for the \LangIf{} language. \racket{(See
  6300. Figure~\ref{fig:interp-op-Lif} for \code{interp-op}.)}
  6301. \python{(See Figure~\ref{fig:interp-cmp-Lif} for \code{interp\_cmp}.)}}
  6302. \label{fig:interp-Lif}
  6303. \end{figure}
  6304. {\if\edition\racketEd
  6305. \begin{figure}[tbp]
  6306. \begin{lstlisting}
  6307. (define/public (interp_op op)
  6308. (match op
  6309. ['+ fx+]
  6310. ['- fx-]
  6311. ['read read-fixnum]
  6312. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  6313. ['eq? (lambda (v1 v2)
  6314. (cond [(or (and (fixnum? v1) (fixnum? v2))
  6315. (and (boolean? v1) (boolean? v2))
  6316. (and (vector? v1) (vector? v2)))
  6317. (eq? v1 v2)]))]
  6318. ['< (lambda (v1 v2)
  6319. (cond [(and (fixnum? v1) (fixnum? v2))
  6320. (< v1 v2)]))]
  6321. ['<= (lambda (v1 v2)
  6322. (cond [(and (fixnum? v1) (fixnum? v2))
  6323. (<= v1 v2)]))]
  6324. ['> (lambda (v1 v2)
  6325. (cond [(and (fixnum? v1) (fixnum? v2))
  6326. (> v1 v2)]))]
  6327. ['>= (lambda (v1 v2)
  6328. (cond [(and (fixnum? v1) (fixnum? v2))
  6329. (>= v1 v2)]))]
  6330. [else (error 'interp_op "unknown operator")]))
  6331. \end{lstlisting}
  6332. \caption{Interpreter for the primitive operators in the \LangIf{} language.}
  6333. \label{fig:interp-op-Lif}
  6334. \end{figure}
  6335. \fi}
  6336. {\if\edition\pythonEd
  6337. \begin{figure}
  6338. \begin{lstlisting}
  6339. class InterpLif(InterpLvar):
  6340. ...
  6341. def interp_cmp(self, cmp):
  6342. match cmp:
  6343. case Lt():
  6344. return lambda x, y: x < y
  6345. case LtE():
  6346. return lambda x, y: x <= y
  6347. case Gt():
  6348. return lambda x, y: x > y
  6349. case GtE():
  6350. return lambda x, y: x >= y
  6351. case Eq():
  6352. return lambda x, y: x == y
  6353. case NotEq():
  6354. return lambda x, y: x != y
  6355. \end{lstlisting}
  6356. \caption{Interpreter for the comparison operators in the \LangIf{} language.}
  6357. \label{fig:interp-cmp-Lif}
  6358. \end{figure}
  6359. \fi}
  6360. \section{Type Checking \LangIf{} Programs}
  6361. \label{sec:type-check-Lif}
  6362. \index{subject}{type checking}
  6363. \index{subject}{semantic analysis}
  6364. It is helpful to think about type checking in two complementary
  6365. ways. A type checker predicts the type of value that will be produced
  6366. by each expression in the program. For \LangIf{}, we have just two types,
  6367. \INTTY{} and \BOOLTY{}. So a type checker should predict that
  6368. {\if\edition\racketEd
  6369. \begin{lstlisting}
  6370. (+ 10 (- (+ 12 20)))
  6371. \end{lstlisting}
  6372. \fi}
  6373. {\if\edition\pythonEd
  6374. \begin{lstlisting}
  6375. 10 + -(12 + 20)
  6376. \end{lstlisting}
  6377. \fi}
  6378. \noindent produces a value of type \INTTY{} while
  6379. {\if\edition\racketEd
  6380. \begin{lstlisting}
  6381. (and (not #f) #t)
  6382. \end{lstlisting}
  6383. \fi}
  6384. {\if\edition\pythonEd
  6385. \begin{lstlisting}
  6386. (not False) and True
  6387. \end{lstlisting}
  6388. \fi}
  6389. \noindent produces a value of type \BOOLTY{}.
  6390. A second way to think about type checking is that it enforces a set of
  6391. rules about which operators can be applied to which kinds of
  6392. values. For example, our type checker for \LangIf{} signals an error
  6393. for the below expression {\if\edition\racketEd
  6394. \begin{lstlisting}
  6395. (not (+ 10 (- (+ 12 20))))
  6396. \end{lstlisting}
  6397. \fi}
  6398. {\if\edition\pythonEd
  6399. \begin{lstlisting}
  6400. not (10 + -(12 + 20))
  6401. \end{lstlisting}
  6402. \fi}
  6403. \noindent The subexpression
  6404. \racket{\code{(+ 10 (- (+ 12 20)))}}
  6405. \python{\code{(10 + -(12 + 20))}}
  6406. has type \INTTY{} but the type checker enforces the rule that the
  6407. argument of \code{not} must be an expression of type \BOOLTY{}.
  6408. We implement type checking using classes and methods because they
  6409. provide the open recursion needed to reuse code as we extend the type
  6410. checker in later chapters, analogous to the use of classes and methods
  6411. for the interpreters (Section~\ref{sec:extensible-interp}).
  6412. We separate the type checker for the \LangVar{} subset into its own
  6413. class, shown in Figure~\ref{fig:type-check-Lvar}. The type checker for
  6414. \LangIf{} is shown in Figure~\ref{fig:type-check-Lif} and it inherits
  6415. from the type checker for \LangVar{}. These type checkers are in the
  6416. files
  6417. \racket{\code{type-check-Lvar.rkt}}\python{\code{type\_check\_Lvar.py}}
  6418. and
  6419. \racket{\code{type-check-Lif.rkt}}\python{\code{type\_check\_Lif.py}}
  6420. of the support code.
  6421. %
  6422. Each type checker is a structurally recursive function over the AST.
  6423. Given an input expression \code{e}, the type checker either signals an
  6424. error or returns \racket{an expression and} its type.
  6425. %
  6426. \racket{It returns an expression because there are situations in which
  6427. we want to change or update the expression.}
  6428. Next we discuss the \code{type\_check\_exp} function of \LangVar{} in
  6429. Figure~\ref{fig:type-check-Lvar}. The type of an integer constant is
  6430. \INTTY{}. To handle variables, the type checker uses the environment
  6431. \code{env} to map variables to types.
  6432. %
  6433. \racket{Consider the case for \key{let}. We type check the
  6434. initializing expression to obtain its type \key{T} and then
  6435. associate type \code{T} with the variable \code{x} in the
  6436. environment used to type check the body of the \key{let}. Thus,
  6437. when the type checker encounters a use of variable \code{x}, it can
  6438. find its type in the environment.}
  6439. %
  6440. \python{Consider the case for assignment. We type check the
  6441. initializing expression to obtain its type \key{t}. If the variable
  6442. \code{lhs.id} is already in the environment because there was a
  6443. prior assignment, we check that this initializer has the same type
  6444. as the prior one. If this is the first assignment to the variable,
  6445. we associate type \code{t} with the variable \code{lhs.id} in the
  6446. environment. Thus, when the type checker encounters a use of
  6447. variable \code{x}, it can find its type in the environment.}
  6448. %
  6449. \racket{Regarding primitive operators, we recursively analyze the
  6450. arguments and then invoke \code{type\_check\_op} to check whether
  6451. the argument types are allowed.}
  6452. %
  6453. \python{Regarding addition, subtraction, and negation, we recursively analyze the
  6454. arguments, check that they have type \INTTY{}, and return \INTTY{}.}
  6455. \racket{Several auxiliary methods are used in the type checker. The
  6456. method \code{operator-types} defines a dictionary that maps the
  6457. operator names to their parameter and return types. The
  6458. \code{type-equal?} method determines whether two types are equal,
  6459. which for now simply dispatches to \code{equal?} (deep
  6460. equality). The \code{check-type-equal?} method triggers an error if
  6461. the two types are not equal. The \code{type-check-op} method looks
  6462. up the operator in the \code{operator-types} dictionary and then
  6463. checks whether the argument types are equal to the parameter types.
  6464. The result is the return type of the operator.}
  6465. %
  6466. \python{The auxiliary method \code{check\_type\_equal} triggers
  6467. an error if the two types are not equal.}
  6468. \begin{figure}[tbp]
  6469. {\if\edition\racketEd
  6470. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6471. (define type-check-Lvar_class
  6472. (class object%
  6473. (super-new)
  6474. (define/public (operator-types)
  6475. '((+ . ((Integer Integer) . Integer))
  6476. (- . ((Integer) . Integer))
  6477. (read . (() . Integer))))
  6478. (define/public (type-equal? t1 t2) (equal? t1 t2))
  6479. (define/public (check-type-equal? t1 t2 e)
  6480. (unless (type-equal? t1 t2)
  6481. (error 'type-check "~a != ~a\nin ~v" t1 t2 e)))
  6482. (define/public (type-check-op op arg-types e)
  6483. (match (dict-ref (operator-types) op)
  6484. [`(,param-types . ,return-type)
  6485. (for ([at arg-types] [pt param-types])
  6486. (check-type-equal? at pt e))
  6487. return-type]
  6488. [else (error 'type-check-op "unrecognized ~a" op)]))
  6489. (define/public (type-check-exp env)
  6490. (lambda (e)
  6491. (match e
  6492. [(Int n) (values (Int n) 'Integer)]
  6493. [(Var x) (values (Var x) (dict-ref env x))]
  6494. [(Let x e body)
  6495. (define-values (e^ Te) ((type-check-exp env) e))
  6496. (define-values (b Tb) ((type-check-exp (dict-set env x Te)) body))
  6497. (values (Let x e^ b) Tb)]
  6498. [(Prim op es)
  6499. (define-values (new-es ts)
  6500. (for/lists (exprs types) ([e es]) ((type-check-exp env) e)))
  6501. (values (Prim op new-es) (type-check-op op ts e))]
  6502. [else (error 'type-check-exp "couldn't match" e)])))
  6503. (define/public (type-check-program e)
  6504. (match e
  6505. [(Program info body)
  6506. (define-values (body^ Tb) ((type-check-exp '()) body))
  6507. (check-type-equal? Tb 'Integer body)
  6508. (Program info body^)]
  6509. [else (error 'type-check-Lvar "couldn't match ~a" e)]))
  6510. ))
  6511. (define (type-check-Lvar p)
  6512. (send (new type-check-Lvar_class) type-check-program p))
  6513. \end{lstlisting}
  6514. \fi}
  6515. {\if\edition\pythonEd
  6516. \begin{lstlisting}[escapechar=`]
  6517. class TypeCheckLvar:
  6518. def check_type_equal(self, t1, t2, e):
  6519. if t1 != t2:
  6520. msg = 'error: ' + repr(t1) + ' != ' + repr(t2) + ' in ' + repr(e)
  6521. raise Exception(msg)
  6522. def type_check_exp(self, e, env):
  6523. match e:
  6524. case BinOp(left, (Add() | Sub()), right):
  6525. l = self.type_check_exp(left, env)
  6526. check_type_equal(l, int, left)
  6527. r = self.type_check_exp(right, env)
  6528. check_type_equal(r, int, right)
  6529. return int
  6530. case UnaryOp(USub(), v):
  6531. t = self.type_check_exp(v, env)
  6532. check_type_equal(t, int, v)
  6533. return int
  6534. case Name(id):
  6535. return env[id]
  6536. case Constant(value) if isinstance(value, int):
  6537. return int
  6538. case Call(Name('input_int'), []):
  6539. return int
  6540. def type_check_stmts(self, ss, env):
  6541. if len(ss) == 0:
  6542. return
  6543. match ss[0]:
  6544. case Assign([lhs], value):
  6545. t = self.type_check_exp(value, env)
  6546. if lhs.id in env:
  6547. check_type_equal(env[lhs.id], t, value)
  6548. else:
  6549. env[lhs.id] = t
  6550. return self.type_check_stmts(ss[1:], env)
  6551. case Expr(Call(Name('print'), [arg])):
  6552. t = self.type_check_exp(arg, env)
  6553. check_type_equal(t, int, arg)
  6554. return self.type_check_stmts(ss[1:], env)
  6555. case Expr(value):
  6556. self.type_check_exp(value, env)
  6557. return self.type_check_stmts(ss[1:], env)
  6558. def type_check_P(self, p):
  6559. match p:
  6560. case Module(body):
  6561. self.type_check_stmts(body, {})
  6562. \end{lstlisting}
  6563. \fi}
  6564. \caption{Type checker for the \LangVar{} language.}
  6565. \label{fig:type-check-Lvar}
  6566. \end{figure}
  6567. \begin{figure}[tbp]
  6568. {\if\edition\racketEd
  6569. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  6570. (define type-check-Lif_class
  6571. (class type-check-Lvar_class
  6572. (super-new)
  6573. (inherit check-type-equal?)
  6574. (define/override (operator-types)
  6575. (append '((- . ((Integer Integer) . Integer))
  6576. (and . ((Boolean Boolean) . Boolean))
  6577. (or . ((Boolean Boolean) . Boolean))
  6578. (< . ((Integer Integer) . Boolean))
  6579. (<= . ((Integer Integer) . Boolean))
  6580. (> . ((Integer Integer) . Boolean))
  6581. (>= . ((Integer Integer) . Boolean))
  6582. (not . ((Boolean) . Boolean))
  6583. )
  6584. (super operator-types)))
  6585. (define/override (type-check-exp env)
  6586. (lambda (e)
  6587. (match e
  6588. [(Bool b) (values (Bool b) 'Boolean)]
  6589. [(Prim 'eq? (list e1 e2))
  6590. (define-values (e1^ T1) ((type-check-exp env) e1))
  6591. (define-values (e2^ T2) ((type-check-exp env) e2))
  6592. (check-type-equal? T1 T2 e)
  6593. (values (Prim 'eq? (list e1^ e2^)) 'Boolean)]
  6594. [(If cnd thn els)
  6595. (define-values (cnd^ Tc) ((type-check-exp env) cnd))
  6596. (define-values (thn^ Tt) ((type-check-exp env) thn))
  6597. (define-values (els^ Te) ((type-check-exp env) els))
  6598. (check-type-equal? Tc 'Boolean e)
  6599. (check-type-equal? Tt Te e)
  6600. (values (If cnd^ thn^ els^) Te)]
  6601. [else ((super type-check-exp env) e)])))
  6602. ))
  6603. (define (type-check-Lif p)
  6604. (send (new type-check-Lif_class) type-check-program p))
  6605. \end{lstlisting}
  6606. \fi}
  6607. {\if\edition\pythonEd
  6608. \begin{lstlisting}
  6609. class TypeCheckLif(TypeCheckLvar):
  6610. def type_check_exp(self, e, env):
  6611. match e:
  6612. case Constant(value) if isinstance(value, bool):
  6613. return bool
  6614. case BinOp(left, Sub(), right):
  6615. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6616. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6617. return int
  6618. case UnaryOp(Not(), v):
  6619. t = self.type_check_exp(v, env); check_type_equal(t, bool, v)
  6620. return bool
  6621. case BoolOp(op, values):
  6622. left = values[0] ; right = values[1]
  6623. l = self.type_check_exp(left, env); check_type_equal(l, bool, left)
  6624. r = self.type_check_exp(right, env); check_type_equal(r, bool, right)
  6625. return bool
  6626. case Compare(left, [cmp], [right]) if isinstance(cmp, Eq) \
  6627. or isinstance(cmp, NotEq):
  6628. l = self.type_check_exp(left, env)
  6629. r = self.type_check_exp(right, env)
  6630. check_type_equal(l, r, e)
  6631. return bool
  6632. case Compare(left, [cmp], [right]):
  6633. l = self.type_check_exp(left, env); check_type_equal(l, int, left)
  6634. r = self.type_check_exp(right, env); check_type_equal(r, int, right)
  6635. return bool
  6636. case IfExp(test, body, orelse):
  6637. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6638. b = self.type_check_exp(body, env)
  6639. o = self.type_check_exp(orelse, env)
  6640. check_type_equal(b, o, e)
  6641. return b
  6642. case _:
  6643. return super().type_check_exp(e, env)
  6644. def type_check_stmts(self, ss, env):
  6645. if len(ss) == 0:
  6646. return
  6647. match ss[0]:
  6648. case If(test, body, orelse):
  6649. t = self.type_check_exp(test, env); check_type_equal(bool, t, test)
  6650. b = self.type_check_stmts(body, env)
  6651. o = self.type_check_stmts(orelse, env)
  6652. check_type_equal(b, o, ss[0])
  6653. return self.type_check_stmts(ss[1:], env)
  6654. case _:
  6655. return super().type_check_stmts(ss, env)
  6656. \end{lstlisting}
  6657. \fi}
  6658. \caption{Type checker for the \LangIf{} language.}
  6659. \label{fig:type-check-Lif}
  6660. \end{figure}
  6661. The type checker for \LangIf{} is defined in
  6662. Figure~\ref{fig:type-check-Lif}.
  6663. %
  6664. The type of a Boolean constant is \BOOLTY{}.
  6665. %
  6666. \racket{The \code{operator-types} function adds dictionary entries for
  6667. the new operators.}
  6668. %
  6669. \python{Logical not requires its argument to be a \BOOLTY{} and
  6670. produces a \BOOLTY{}. Similarly for logical and and logical or. }
  6671. %
  6672. The equality operators require the two arguments to have the same
  6673. type.
  6674. %
  6675. \python{The other comparisons (less-than, etc.) require their
  6676. arguments to be of type \INTTY{} and they produce a \BOOLTY{}.}
  6677. %
  6678. The condition of an \code{if} must
  6679. be of \BOOLTY{} type and the two branches must have the same type.
  6680. \begin{exercise}\normalfont\normalsize
  6681. Create 10 new test programs in \LangIf{}. Half of the programs should
  6682. have a type error. For those programs, create an empty file with the
  6683. same base name but with file extension \code{.tyerr}. For example, if
  6684. the test
  6685. \racket{\code{cond\_test\_14.rkt}}\python{\code{cond\_test\_14.py}}
  6686. is expected to error, then create
  6687. an empty file named \code{cond\_test\_14.tyerr}.
  6688. %
  6689. \racket{This indicates to \code{interp-tests} and
  6690. \code{compiler-tests} that a type error is expected. }
  6691. %
  6692. The other half of the test programs should not have type errors.
  6693. %
  6694. \racket{In the \code{run-tests.rkt} script, change the second argument
  6695. of \code{interp-tests} and \code{compiler-tests} to
  6696. \code{type-check-Lif}, which causes the type checker to run prior to
  6697. the compiler passes. Temporarily change the \code{passes} to an
  6698. empty list and run the script, thereby checking that the new test
  6699. programs either type check or not as intended.}
  6700. %
  6701. Run the test script to check that these test programs type check as
  6702. expected.
  6703. \end{exercise}
  6704. \clearpage
  6705. \section{The \LangCIf{} Intermediate Language}
  6706. \label{sec:Cif}
  6707. {\if\edition\racketEd
  6708. %
  6709. Figure~\ref{fig:c1-concrete-syntax} defines the concrete syntax of the
  6710. \LangCIf{} intermediate language and Figure~\ref{fig:c1-syntax}
  6711. defines its abstract syntax. Compared to \LangCVar{}, the \LangCIf{}
  6712. language adds logical and comparison operators to the \Exp{}
  6713. non-terminal and the literals \TRUE{} and \FALSE{} to the \Arg{}
  6714. non-terminal.
  6715. Regarding control flow, \LangCIf{} adds \key{goto} and \code{if}
  6716. statements to the \Tail{} non-terminal. The condition of an \code{if}
  6717. statement is a comparison operation and the branches are \code{goto}
  6718. statements, making it straightforward to compile \code{if} statements
  6719. to x86.
  6720. %
  6721. \fi}
  6722. %
  6723. {\if\edition\pythonEd
  6724. %
  6725. The output of \key{explicate\_control} is a language similar to the
  6726. $C$ language~\citep{Kernighan:1988nx} in that it has labels and
  6727. \code{goto} statements, so we name it \LangCIf{}. The
  6728. concrete syntax for \LangCIf{} is defined in
  6729. Figure~\ref{fig:c1-concrete-syntax}
  6730. and the abstract syntax is defined in Figure~\ref{fig:c1-syntax}.
  6731. %
  6732. The \LangCIf{} language supports the same operators as \LangIf{} but
  6733. the arguments of operators are restricted to atomic expressions. The
  6734. \LangCIf{} language does not include \code{if} expressions but it does
  6735. include a restricted form of \code{if} statment. The condition must be
  6736. a comparison and the two branches may only contain \code{goto}
  6737. statements. These restrictions make it easier to translate \code{if}
  6738. statements to x86.
  6739. %
  6740. \fi}
  6741. %
  6742. Besides the \code{goto} statement, \LangCIf{}, also adds a
  6743. \code{return} statement to finish a function call with a specified value.
  6744. %
  6745. The \key{CProgram} construct contains
  6746. %
  6747. \racket{an alist}\python{a dictionary}
  6748. %
  6749. mapping labels to
  6750. \racket{$\Tail$ expressions, which can be \code{return} statements,
  6751. an assignment statement followed by a $\Tail$ expression, a
  6752. \code{goto}, or a conditional \code{goto}.}
  6753. \python{lists of statements, which comprise of assignment statements
  6754. and end in a \code{return} statement, a \code{goto}, or a
  6755. conditional \code{goto}.
  6756. \index{subject}{basic block}
  6757. Statement lists of this form are called
  6758. \emph{basic blocks}: there is a control transfer at the end and
  6759. control only enters at the beginning of the list, which is marked by
  6760. the label. }
  6761. \newcommand{\CifGrammarRacket}{
  6762. \begin{array}{lcl}
  6763. \Atm &::=& \itm{bool} \\
  6764. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6765. \Exp &::=& \CNOT{\Atm} \MID \LP \itm{cmp}~\Atm~\Atm\RP \\
  6766. \Tail &::= & \key{goto}~\itm{label}\key{;}\\
  6767. &\MID& \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;}
  6768. \end{array}
  6769. }
  6770. \newcommand{\CifASTRacket}{
  6771. \begin{array}{lcl}
  6772. \Atm &::=& \BOOL{\itm{bool}} \\
  6773. \itm{cmp} &::= & \code{eq?} \MID \code{<} \MID \code{<=} \MID \code{>} \MID \code{>=} \\
  6774. \Exp &::= & \UNIOP{\key{'not}}{\Atm} \MID \BINOP{\key{'}\itm{cmp}}{\Atm}{\Atm} \\
  6775. \Tail &::= & \GOTO{\itm{label}} \\
  6776. &\MID& \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}}
  6777. \end{array}
  6778. }
  6779. \newcommand{\CifGrammarPython}{
  6780. \begin{array}{lcl}
  6781. \Atm &::=& \Int \MID \Var \MID \itm{bool} \\
  6782. \Exp &::= & \Atm \MID \CREAD{}
  6783. \MID \CBINOP{\itm{binaryop}}{\Atm}{\Atm}
  6784. \MID \CUNIOP{\itm{unaryop}}{\Atm} \\
  6785. &\MID& \CCMP{\itm{cmp}}{\Atm}{\Atm} \\
  6786. \Stmt &::=& \CPRINT{\Atm} \MID \Exp \\
  6787. &\MID& \CASSIGN{\Var}{\Exp}
  6788. \MID \CRETURN{\Exp} \MID \CGOTO{\itm{label}} \\
  6789. &\MID& \CIFSTMT{\CCMP{\itm{cmp}}{\Atm}{\Atm}}{\CGOTO{\itm{label}}}{\CGOTO{\itm{label}}}
  6790. \end{array}
  6791. }
  6792. \newcommand{\CifASTPython}{
  6793. \begin{array}{lcl}
  6794. \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  6795. \Exp &::= & \Atm \MID \READ{} \\
  6796. &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  6797. \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  6798. &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  6799. \Stmt &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  6800. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}
  6801. \MID \RETURN{\Exp} \MID \GOTO{\itm{label}} \\
  6802. &\MID& \IFSTMT{\CMP{\Atm}{\itm{cmp}}{\Atm}}{\LS\GOTO{\itm{label}}\RS}{\LS\GOTO{\itm{label}}\RS}
  6803. \end{array}
  6804. }
  6805. \begin{figure}[tbp]
  6806. \fbox{
  6807. \begin{minipage}{0.96\textwidth}
  6808. \small
  6809. {\if\edition\racketEd
  6810. \[
  6811. \begin{array}{l}
  6812. \gray{\CvarGrammarRacket} \\ \hline
  6813. \CifGrammarRacket \\
  6814. \begin{array}{lcl}
  6815. \LangCIfM{} & ::= & (\itm{label}\key{:}~ \Tail)\ldots
  6816. \end{array}
  6817. \end{array}
  6818. \]
  6819. \fi}
  6820. {\if\edition\pythonEd
  6821. \[
  6822. \begin{array}{l}
  6823. \CifGrammarPython \\
  6824. \begin{array}{lcl}
  6825. \LangCIfM{} & ::= & (\itm{label}\code{:}~\Stmt^{*}) \ldots
  6826. \end{array}
  6827. \end{array}
  6828. \]
  6829. \fi}
  6830. \end{minipage}
  6831. }
  6832. \caption{The concrete syntax of the \LangCIf{} intermediate language.}
  6833. \label{fig:c1-concrete-syntax}
  6834. \end{figure}
  6835. \begin{figure}[tp]
  6836. \fbox{
  6837. \begin{minipage}{0.96\textwidth}
  6838. \small
  6839. {\if\edition\racketEd
  6840. \[
  6841. \begin{array}{l}
  6842. \gray{\CvarASTRacket} \\ \hline
  6843. \CifASTRacket \\
  6844. \begin{array}{lcl}
  6845. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  6846. \end{array}
  6847. \end{array}
  6848. \]
  6849. \fi}
  6850. {\if\edition\pythonEd
  6851. \[
  6852. \begin{array}{l}
  6853. \CifASTPython \\
  6854. \begin{array}{lcl}
  6855. \LangCIfM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  6856. \end{array}
  6857. \end{array}
  6858. \]
  6859. \fi}
  6860. \end{minipage}
  6861. }
  6862. \caption{The abstract syntax of \LangCIf{}\racket{, an extension of \LangCVar{}
  6863. (Figure~\ref{fig:c0-syntax})}.}
  6864. \label{fig:c1-syntax}
  6865. \end{figure}
  6866. \section{The \LangXIf{} Language}
  6867. \label{sec:x86-if}
  6868. \index{subject}{x86} To implement the new logical operations, the comparison
  6869. operations, and the \key{if} expression\python{ and statement}, we need to delve further into
  6870. the x86 language. Figures~\ref{fig:x86-1-concrete} and \ref{fig:x86-1}
  6871. define the concrete and abstract syntax for the \LangXIf{} subset
  6872. of x86, which includes instructions for logical operations,
  6873. comparisons, and \racket{conditional} jumps.
  6874. One challenge is that x86 does not provide an instruction that
  6875. directly implements logical negation (\code{not} in \LangIf{} and
  6876. \LangCIf{}). However, the \code{xorq} instruction can be used to
  6877. encode \code{not}. The \key{xorq} instruction takes two arguments,
  6878. performs a pairwise exclusive-or ($\mathrm{XOR}$) operation on each
  6879. bit of its arguments, and writes the results into its second argument.
  6880. Recall the truth table for exclusive-or:
  6881. \begin{center}
  6882. \begin{tabular}{l|cc}
  6883. & 0 & 1 \\ \hline
  6884. 0 & 0 & 1 \\
  6885. 1 & 1 & 0
  6886. \end{tabular}
  6887. \end{center}
  6888. For example, applying $\mathrm{XOR}$ to each bit of the binary numbers
  6889. $0011$ and $0101$ yields $0110$. Notice that in the row of the table
  6890. for the bit $1$, the result is the opposite of the second bit. Thus,
  6891. the \code{not} operation can be implemented by \code{xorq} with $1$ as
  6892. the first argument as follows, where $\Arg$ is the translation of
  6893. $\Atm$.
  6894. \[
  6895. \CASSIGN{\Var}{\CUNIOP{\key{not}}{\Atm}}
  6896. \qquad\Rightarrow\qquad
  6897. \begin{array}{l}
  6898. \key{movq}~ \Arg\key{,} \Var\\
  6899. \key{xorq}~ \key{\$1,} \Var
  6900. \end{array}
  6901. \]
  6902. \begin{figure}[tp]
  6903. \fbox{
  6904. \begin{minipage}{0.96\textwidth}
  6905. \[
  6906. \begin{array}{lcl}
  6907. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6908. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6909. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} } \MID \key{\%}\itm{bytereg}\\
  6910. \itm{cc} & ::= & \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6911. \Instr &::=& \gray{ \key{addq} \; \Arg\key{,} \Arg \MID
  6912. \key{subq} \; \Arg\key{,} \Arg \MID
  6913. \key{negq} \; \Arg \MID \key{movq} \; \Arg\key{,} \Arg \MID } \\
  6914. && \gray{ \key{callq} \; \itm{label} \MID
  6915. \key{pushq}\;\Arg \MID \key{popq}\;\Arg \MID \key{retq} \MID \racket{\key{jmp}\,\itm{label} \MID} } \python{\key{jmp}\,\itm{label} \MID} \\
  6916. && \racket{\gray{ \itm{label}\key{:}\; \Instr }}\python{\itm{label}\key{:}\; \Instr}
  6917. \MID \key{xorq}~\Arg\key{,}~\Arg
  6918. \MID \key{cmpq}~\Arg\key{,}~\Arg \MID \\
  6919. && \key{set}cc~\Arg
  6920. \MID \key{movzbq}~\Arg\key{,}~\Arg
  6921. \MID \key{j}cc~\itm{label}
  6922. \\
  6923. \LangXIfM{} &::= & \gray{ \key{.globl main} }\\
  6924. & & \gray{ \key{main:} \; \Instr\ldots }
  6925. \end{array}
  6926. \]
  6927. \end{minipage}
  6928. }
  6929. \caption{The concrete syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-concrete}).}
  6930. \label{fig:x86-1-concrete}
  6931. \end{figure}
  6932. \begin{figure}[tp]
  6933. \fbox{
  6934. \begin{minipage}{0.98\textwidth}
  6935. \small
  6936. {\if\edition\racketEd
  6937. \[
  6938. \begin{array}{lcl}
  6939. \itm{bytereg} &::=& \key{ah} \MID \key{al} \MID \key{bh} \MID \key{bl}
  6940. \MID \key{ch} \MID \key{cl} \MID \key{dh} \MID \key{dl} \\
  6941. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6942. \MID \BYTEREG{\itm{bytereg}} \\
  6943. \itm{cc} & ::= & \key{e} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} \\
  6944. \Instr &::=& \gray{ \BININSTR{\code{addq}}{\Arg}{\Arg}
  6945. \MID \BININSTR{\code{subq}}{\Arg}{\Arg} } \\
  6946. &\MID& \gray{ \BININSTR{\code{'movq}}{\Arg}{\Arg}
  6947. \MID \UNIINSTR{\code{negq}}{\Arg} } \\
  6948. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6949. \MID \PUSHQ{\Arg} \MID \POPQ{\Arg} \MID \JMP{\itm{label}} } \\
  6950. &\MID& \BININSTR{\code{xorq}}{\Arg}{\Arg}
  6951. \MID \BININSTR{\code{cmpq}}{\Arg}{\Arg}\\
  6952. &\MID& \BININSTR{\code{set}}{\itm{cc}}{\Arg}
  6953. \MID \BININSTR{\code{movzbq}}{\Arg}{\Arg}\\
  6954. &\MID& \JMPIF{'\itm{cc}'}{\itm{label}} \\
  6955. \Block &::= & \gray{\BLOCK{\itm{info}}{\LP\Instr\ldots\RP}} \\
  6956. \LangXIfM{} &::= & \gray{\XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP}}
  6957. \end{array}
  6958. \]
  6959. \fi}
  6960. %
  6961. {\if\edition\pythonEd
  6962. \[
  6963. \begin{array}{lcl}
  6964. \itm{bytereg} &::=& \skey{ah} \MID \skey{al} \MID \skey{bh} \MID \skey{bl}
  6965. \MID \skey{ch} \MID \skey{cl} \MID \skey{dh} \MID \skey{dl} \\
  6966. \Arg &::=& \gray{\IMM{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}}
  6967. \MID \BYTEREG{\itm{bytereg}} \\
  6968. \itm{cc} & ::= & \skey{e} \MID \skey{ne} \MID \skey{l} \MID \skey{le} \MID \skey{g} \MID \skey{ge} \\
  6969. \Instr &::=& \gray{ \BININSTR{\scode{addq}}{\Arg}{\Arg}
  6970. \MID \BININSTR{\scode{subq}}{\Arg}{\Arg} } \\
  6971. &\MID& \gray{ \BININSTR{\scode{movq}}{\Arg}{\Arg}
  6972. \MID \UNIINSTR{\scode{negq}}{\Arg} } \\
  6973. &\MID& \gray{ \CALLQ{\itm{label}}{\itm{int}} \MID \RETQ{}
  6974. \MID \PUSHQ{\Arg}} \\
  6975. &\MID& \gray{ \POPQ{\Arg} \MID \racket{\JMP{\itm{label}}} } \python{\JMP{\itm{label}}}\\
  6976. &\MID& \BININSTR{\scode{xorq}}{\Arg}{\Arg}
  6977. \MID \BININSTR{\scode{cmpq}}{\Arg}{\Arg}\\
  6978. &\MID& \BININSTR{\scode{set}}{\itm{cc}}{\Arg}
  6979. \MID \BININSTR{\scode{movzbq}}{\Arg}{\Arg}\\
  6980. &\MID& \JMPIF{\itm{cc}}{\itm{label}} \\
  6981. \LangXIfM{} &::= & \XPROGRAM{\itm{info}}{\LC\itm{label} \,\key{:}\, \Instr^{*} \key{,} \ldots \RC }
  6982. \end{array}
  6983. \]
  6984. \fi}
  6985. \end{minipage}
  6986. }
  6987. \caption{The abstract syntax of \LangXIf{} (extends \LangXInt{} of Figure~\ref{fig:x86-int-ast}).}
  6988. \label{fig:x86-1}
  6989. \end{figure}
  6990. Next we consider the x86 instructions that are relevant for compiling
  6991. the comparison operations. The \key{cmpq} instruction compares its two
  6992. arguments to determine whether one argument is less than, equal, or
  6993. greater than the other argument. The \key{cmpq} instruction is unusual
  6994. regarding the order of its arguments and where the result is
  6995. placed. The argument order is backwards: if you want to test whether
  6996. $x < y$, then write \code{cmpq} $y$\code{,} $x$. The result of
  6997. \key{cmpq} is placed in the special EFLAGS register. This register
  6998. cannot be accessed directly but it can be queried by a number of
  6999. instructions, including the \key{set} instruction. The instruction
  7000. $\key{set}cc~d$ puts a \key{1} or \key{0} into the destination $d$
  7001. depending on whether the comparison comes out according to the
  7002. condition code \itm{cc} (\key{e} for equal, \key{l} for less, \key{le}
  7003. for less-or-equal, \key{g} for greater, \key{ge} for
  7004. greater-or-equal). The \key{set} instruction has a quirk in
  7005. that its destination argument must be single byte register, such as
  7006. \code{al} (L for lower bits) or \code{ah} (H for higher bits), which
  7007. are part of the \code{rax} register. Thankfully, the \key{movzbq}
  7008. instruction can be used to move from a single byte register to a
  7009. normal 64-bit register. The abstract syntax for the \code{set}
  7010. instruction differs from the concrete syntax in that it separates the
  7011. instruction name from the condition code.
  7012. \python{The x86 instructions for jumping are relevant to the
  7013. compilation of \key{if} expressions.}
  7014. %
  7015. \python{The instruction $\key{jmp}\,\itm{label}$ updates the program
  7016. counter to the address of the instruction after the specified
  7017. label.}
  7018. %
  7019. \racket{The x86 instruction for conditional jump is relevant to the
  7020. compilation of \key{if} expressions.}
  7021. %
  7022. The instruction $\key{j}\itm{cc}~\itm{label}$ updates the program
  7023. counter to point to the instruction after \itm{label} depending on
  7024. whether the result in the EFLAGS register matches the condition code
  7025. \itm{cc}, otherwise the jump instruction falls through to the next
  7026. instruction. Like the abstract syntax for \code{set}, the abstract
  7027. syntax for conditional jump separates the instruction name from the
  7028. condition code. For example, \JMPIF{\key{'le'}}{\key{foo}} corresponds
  7029. to \code{jle foo}. Because the conditional jump instruction relies on
  7030. the EFLAGS register, it is common for it to be immediately preceded by
  7031. a \key{cmpq} instruction to set the EFLAGS register.
  7032. \section{Shrink the \LangIf{} Language}
  7033. \label{sec:shrink-Lif}
  7034. The \LangIf{} language includes several features that are easily
  7035. expressible with other features. For example, \code{and} and \code{or}
  7036. are expressible using \code{if} as follows.
  7037. \begin{align*}
  7038. \CAND{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{e_2}{\FALSE{}}\\
  7039. \COR{e_1}{e_2} & \quad \Rightarrow \quad \CIF{e_1}{\TRUE{}}{e_2}
  7040. \end{align*}
  7041. By performing these translations in the front-end of the compiler,
  7042. subsequent passes of the compiler do not need to deal with these features,
  7043. making the passes shorter.
  7044. %% For example, subtraction is
  7045. %% expressible using addition and negation.
  7046. %% \[
  7047. %% \key{(-}\; e_1 \; e_2\key{)} \quad \Rightarrow \quad \LP\key{+} \; e_1 \; \LP\key{-} \; e_2\RP\RP
  7048. %% \]
  7049. %% Several of the comparison operations are expressible using less-than
  7050. %% and logical negation.
  7051. %% \[
  7052. %% \LP\key{<=}\; e_1 \; e_2\RP \quad \Rightarrow \quad
  7053. %% \LP\key{let}~\LP\LS\key{tmp.1}~e_1\RS\RP~\LP\key{not}\;\LP\key{<}\;e_2\;\key{tmp.1})\RP\RP
  7054. %% \]
  7055. %% The \key{let} is needed in the above translation to ensure that
  7056. %% expression $e_1$ is evaluated before $e_2$.
  7057. On the other hand, sometimes translations reduce the efficiency of the
  7058. generated code by increasing the number of instructions. For example,
  7059. expressing subtraction in terms of negation
  7060. \[
  7061. \CBINOP{\key{-}}{e_1}{e_2} \quad \Rightarrow \quad
  7062. \CBINOP{\key{+}}{e_1}{ \CUNIOP{\key{-}}{e_2} }
  7063. \]
  7064. produces code with two x86 instructions (\code{negq} and \code{addq})
  7065. instead of just one (\code{subq}).
  7066. %% However,
  7067. %% these differences typically do not affect the number of accesses to
  7068. %% memory, which is the primary factor that determines execution time on
  7069. %% modern computer architectures.
  7070. \begin{exercise}\normalfont\normalsize
  7071. %
  7072. Implement the pass \code{shrink} to remove \key{and} and \key{or} from
  7073. the language by translating them to \code{if} expressions in \LangIf{}.
  7074. %
  7075. Create four test programs that involve these operators.
  7076. %
  7077. {\if\edition\racketEd
  7078. In the \code{run-tests.rkt} script, add the following entry for
  7079. \code{shrink} to the list of passes (it should be the only pass at
  7080. this point).
  7081. \begin{lstlisting}
  7082. (list "shrink" shrink interp_Lif type-check-Lif)
  7083. \end{lstlisting}
  7084. This instructs \code{interp-tests} to run the intepreter
  7085. \code{interp\_Lif} and the type checker \code{type-check-Lif} on the
  7086. output of \code{shrink}.
  7087. \fi}
  7088. %
  7089. Run the script to test your compiler on all the test programs.
  7090. \end{exercise}
  7091. {\if\edition\racketEd
  7092. \section{Uniquify Variables}
  7093. \label{sec:uniquify-Lif}
  7094. Add cases to \code{uniquify\_exp} to handle Boolean constants and
  7095. \code{if} expressions.
  7096. \begin{exercise}\normalfont\normalsize
  7097. Update the \code{uniquify\_exp} for \LangIf{} and add the following
  7098. entry to the list of \code{passes} in the \code{run-tests.rkt} script.
  7099. \begin{lstlisting}
  7100. (list "uniquify" uniquify interp_Lif type_check_Lif)
  7101. \end{lstlisting}
  7102. Run the script to test your compiler.
  7103. \end{exercise}
  7104. \fi}
  7105. \section{Remove Complex Operands}
  7106. \label{sec:remove-complex-opera-Lif}
  7107. The output language of \code{remove\_complex\_operands} is
  7108. \LangIfANF{} (Figure~\ref{fig:Lif-anf-syntax}), the administrative
  7109. normal form of \LangIf{}. A Boolean constant is an atomic expressions
  7110. but the \code{if} expression is not. All three sub-expressions of an
  7111. \code{if} are allowed to be complex expressions but the operands of
  7112. \code{not} and the comparisons must be atomic.
  7113. %
  7114. \python{We add a new language form, the \code{Begin} expression, to aid
  7115. in the translation of \code{if} expressions. When we recursively
  7116. process the two branches of the \code{if}, we generate temporary
  7117. variables and their initializing expressions. However, these
  7118. expressions may contain side effects and should only be executed
  7119. when the condition of the \code{if} is true (for the ``then''
  7120. branch) or false (for the ``else'' branch). The \code{Begin} provides
  7121. a way to initialize the temporary variables within the two branches
  7122. of the \code{if} expression. In general, the $\BEGIN{ss}{e}$
  7123. form execute the statements $ss$ and then returns the result of
  7124. expression $e$.}
  7125. Add cases for Boolean constants, \python{comparisons,} and \code{if}
  7126. expressions to the \code{rco\_exp} and \code{rco\_atom} functions
  7127. according to whether the output needs to be \Exp{} or \Atm{} as
  7128. specified in the grammar for \LangIfANF{}. Regarding \code{if}, it is
  7129. particularly important to \textbf{not} replace its condition with a
  7130. temporary variable because that would interfere with the generation of
  7131. high-quality output in the \code{explicate\_control} pass.
  7132. \newcommand{\LifMonadASTPython}{
  7133. \begin{array}{rcl}
  7134. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  7135. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  7136. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  7137. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  7138. \Atm &::=& \BOOL{\itm{bool}}\\
  7139. \Exp &::=& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7140. &\MID& \BEGIN{\Stmt^{*}}{\Exp}\\
  7141. \Stmt{} &::=& \IFSTMT{\Exp}{\Stmt^{*}}{\Stmt^{*}}
  7142. \end{array}
  7143. }
  7144. \begin{figure}[tp]
  7145. \centering
  7146. \fbox{
  7147. \begin{minipage}{0.96\textwidth}
  7148. {\if\edition\racketEd
  7149. \[
  7150. \begin{array}{rcl}
  7151. Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} } \MID \BOOL{\itm{bool}}\\
  7152. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  7153. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  7154. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  7155. &\MID& \UNIOP{\key{not}}{\Atm} \\
  7156. &\MID& \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  7157. \LangIfANF &::=& \PROGRAM{\code{()}}{\Exp}
  7158. \end{array}
  7159. \]
  7160. \fi}
  7161. {\if\edition\pythonEd
  7162. \[
  7163. \begin{array}{l}
  7164. \gray{\LvarMonadASTPython} \\ \hline
  7165. \LifMonadASTPython \\
  7166. \begin{array}{rcl}
  7167. \LangIfANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  7168. \end{array}
  7169. \end{array}
  7170. \]
  7171. \fi}
  7172. \end{minipage}
  7173. }
  7174. \caption{\LangIfANF{} is \LangIf{} in monadic normal form.}
  7175. \label{fig:Lif-anf-syntax}
  7176. \end{figure}
  7177. \begin{exercise}\normalfont\normalsize
  7178. %
  7179. Add cases for Boolean constants and \code{if} to the \code{rco\_atom}
  7180. and \code{rco\_exp} functions in \code{compiler.rkt}.
  7181. %
  7182. Create three new \LangIf{} programs that exercise the interesting
  7183. code in this pass.
  7184. %
  7185. {\if\edition\racketEd
  7186. In the \code{run-tests.rkt} script, add the following entry to the
  7187. list of \code{passes} and then run the script to test your compiler.
  7188. \begin{lstlisting}
  7189. (list "remove-complex" remove_complex_operands interp-Lif type-check-Lif)
  7190. \end{lstlisting}
  7191. \fi}
  7192. \end{exercise}
  7193. \section{Explicate Control}
  7194. \label{sec:explicate-control-Lif}
  7195. \racket{Recall that the purpose of \code{explicate\_control} is to
  7196. make the order of evaluation explicit in the syntax of the program.
  7197. With the addition of \key{if} this get more interesting.}
  7198. %
  7199. The \code{explicate\_control} pass translates from \LangIf{} to \LangCIf{}.
  7200. %
  7201. The main challenge to overcome is that the condition of an \key{if}
  7202. can be an arbitrary expression in \LangIf{} whereas in \LangCIf{} the
  7203. condition must be a comparison.
  7204. As a motivating example, consider the following program that has an
  7205. \key{if} expression nested in the condition of another \key{if}.%
  7206. \python{\footnote{Programmers rarely write nested \code{if}
  7207. expressions, but it is not uncommon for the condition of an
  7208. \code{if} statement to be a call of a function that also contains an
  7209. \code{if} statement. When such a function is inlined, the result is
  7210. a nested \code{if} that requires the techniques discussed in this
  7211. section.}}
  7212. % cond_test_41.rkt, if_lt_eq.py
  7213. \begin{center}
  7214. \begin{minipage}{0.96\textwidth}
  7215. {\if\edition\racketEd
  7216. \begin{lstlisting}
  7217. (let ([x (read)])
  7218. (let ([y (read)])
  7219. (if (if (< x 1) (eq? x 0) (eq? x 2))
  7220. (+ y 2)
  7221. (+ y 10))))
  7222. \end{lstlisting}
  7223. \fi}
  7224. {\if\edition\pythonEd
  7225. \begin{lstlisting}
  7226. x = input_int()
  7227. y = input_int()
  7228. print(y + 2 if (x == 0 if x < 1 else x == 2) else y + 10)
  7229. \end{lstlisting}
  7230. \fi}
  7231. \end{minipage}
  7232. \end{center}
  7233. %
  7234. The naive way to compile \key{if} and the comparison operations would
  7235. be to handle each of them in isolation, regardless of their context.
  7236. Each comparison would be translated into a \key{cmpq} instruction
  7237. followed by several instructions to move the result from the EFLAGS
  7238. register into a general purpose register or stack location. Each
  7239. \key{if} would be translated into a \key{cmpq} instruction followed by
  7240. a conditional jump. The generated code for the inner \key{if} in the
  7241. above example would be as follows.
  7242. \begin{center}
  7243. \begin{minipage}{0.96\textwidth}
  7244. \begin{lstlisting}
  7245. cmpq $1, x
  7246. setl %al
  7247. movzbq %al, tmp
  7248. cmpq $1, tmp
  7249. je then_branch_1
  7250. jmp else_branch_1
  7251. \end{lstlisting}
  7252. \end{minipage}
  7253. \end{center}
  7254. However, if we take context into account we can do better and reduce
  7255. the use of \key{cmpq} instructions for accessing the EFLAG register.
  7256. Our goal will be to compile \key{if} expressions so that the relevant
  7257. comparison instruction appears directly before the conditional jump.
  7258. For example, we want to generate the following code for the inner
  7259. \code{if}.
  7260. \begin{center}
  7261. \begin{minipage}{0.96\textwidth}
  7262. \begin{lstlisting}
  7263. cmpq $1, x
  7264. jl then_branch_1
  7265. jmp else_branch_1
  7266. \end{lstlisting}
  7267. \end{minipage}
  7268. \end{center}
  7269. One way to achieve this goal is to reorganize the code at the level of
  7270. \LangIf{}, pushing the outer \key{if} inside the inner one, yielding
  7271. the following code.
  7272. \begin{center}
  7273. \begin{minipage}{0.96\textwidth}
  7274. {\if\edition\racketEd
  7275. \begin{lstlisting}
  7276. (let ([x (read)])
  7277. (let ([y (read)])
  7278. (if (< x 1)
  7279. (if (eq? x 0)
  7280. (+ y 2)
  7281. (+ y 10))
  7282. (if (eq? x 2)
  7283. (+ y 2)
  7284. (+ y 10)))))
  7285. \end{lstlisting}
  7286. \fi}
  7287. {\if\edition\pythonEd
  7288. \begin{lstlisting}
  7289. x = input_int()
  7290. y = intput_int()
  7291. print(((y + 2) if x == 0 else (y + 10)) \
  7292. if (x < 1) \
  7293. else ((y + 2) if (x == 2) else (y + 10)))
  7294. \end{lstlisting}
  7295. \fi}
  7296. \end{minipage}
  7297. \end{center}
  7298. Unfortunately, this approach duplicates the two branches from the
  7299. outer \code{if} and a compiler must never duplicate code! After all,
  7300. the two branches could have been very large expressions.
  7301. We need a way to perform the above transformation but without
  7302. duplicating code. That is, we need a way for different parts of a
  7303. program to refer to the same piece of code.
  7304. %
  7305. Put another way, we need to move away from abstract syntax
  7306. \emph{trees} and instead use \emph{graphs}.
  7307. %
  7308. At the level of x86 assembly this is straightforward because we can
  7309. label the code for each branch and insert jumps in all the places that
  7310. need to execute the branch.
  7311. %
  7312. Likewise, our language \LangCIf{} provides the ability to label a
  7313. sequence of code and to jump to a label via \code{goto}.
  7314. %
  7315. %% In particular, we use a standard program representation called a
  7316. %% \emph{control flow graph} (CFG), due to Frances Elizabeth
  7317. %% \citet{Allen:1970uq}. \index{subject}{control-flow graph} Each vertex
  7318. %% is a labeled sequence of code, called a \emph{basic block}, and each
  7319. %% edge represents a jump to another block.
  7320. %
  7321. %% The nice thing about the output of \code{explicate\_control} is that
  7322. %% there are no unnecessary comparisons and every comparison is part of a
  7323. %% conditional jump.
  7324. %% The down-side of this output is that it includes
  7325. %% trivial blocks, such as the blocks labeled \code{block92} through
  7326. %% \code{block95}, that only jump to another block. We discuss a solution
  7327. %% to this problem in Section~\ref{sec:opt-jumps}.
  7328. {\if\edition\racketEd
  7329. %
  7330. Recall that in Section~\ref{sec:explicate-control-Lvar} we implement
  7331. \code{explicate\_control} for \LangVar{} using two mutually recursive
  7332. functions, \code{explicate\_tail} and \code{explicate\_assign}. The
  7333. former function translates expressions in tail position whereas the
  7334. later function translates expressions on the right-hand-side of a
  7335. \key{let}. With the addition of \key{if} expression in \LangIf{} we
  7336. have a new kind of position to deal with: the predicate position of
  7337. the \key{if}. We need another function, \code{explicate\_pred}, that
  7338. decides how to compile an \key{if} by analyzing its predicate. So
  7339. \code{explicate\_pred} takes an \LangIf{} expression and two \LangCIf{}
  7340. tails for the then-branch and else-branch and outputs a tail. In the
  7341. following paragraphs we discuss specific cases in the
  7342. \code{explicate\_tail}, \code{explicate\_assign}, and
  7343. \code{explicate\_pred} functions.
  7344. %
  7345. \fi}
  7346. %
  7347. {\if\edition\pythonEd
  7348. %
  7349. We recommend implementing \code{explicate\_control} using the
  7350. following four auxiliary functions.
  7351. \begin{description}
  7352. \item[\code{explicate\_effect}] generates code for expressions as
  7353. statements, so their result is ignored and only their side effects
  7354. matter.
  7355. \item[\code{explicate\_assign}] generates code for expressions
  7356. on the right-hand side of an assignment.
  7357. \item[\code{explicate\_pred}] generates code for an \code{if}
  7358. expression or statement by analyzing the condition expression.
  7359. \item[\code{explicate\_stmt}] generates code for statements.
  7360. \end{description}
  7361. These four functions should build the dictionary of basic blocks. The
  7362. following auxiliary function can be used to create a new basic block
  7363. from a list of statements. It returns a \code{goto} statement that
  7364. jumps to the new basic block.
  7365. \begin{center}
  7366. \begin{minipage}{\textwidth}
  7367. \begin{lstlisting}
  7368. def create_block(stmts, basic_blocks):
  7369. label = label_name(generate_name('block'))
  7370. basic_blocks[label] = stmts
  7371. return Goto(label)
  7372. \end{lstlisting}
  7373. \end{minipage}
  7374. \end{center}
  7375. Figure~\ref{fig:explicate-control-Lif} provides a skeleton for the
  7376. \code{explicate\_control} pass.
  7377. The \code{explicate\_effect} function has three parameters: 1) the
  7378. expression to be compiled, 2) the already-compiled code for this
  7379. expression's \emph{continuation}, that is, the list of statements that
  7380. should execute after this expression, and 3) the dictionary of
  7381. generated basic blocks. The \code{explicate\_effect} function returns
  7382. a list of \LangCIf{} statements and it may add to the dictionary of
  7383. basic blocks.
  7384. %
  7385. Let's consider a few of the cases for the expression to be compiled.
  7386. If the expression to be compiled is a constant, then it can be
  7387. discarded because it has no side effects. If it's a \CREAD{}, then it
  7388. has a side-effect and should be preserved. So the expression should be
  7389. translated into a statement using the \code{Expr} AST class. If the
  7390. expression to be compiled is an \code{if} expression, we translate the
  7391. two branches using \code{explicate\_effect} and then translate the
  7392. condition expression using \code{explicate\_pred}, which generates
  7393. code for the entire \code{if}.
  7394. The \code{explicate\_assign} function has four parameters: 1) the
  7395. right-hand-side of the assignment, 2) the left-hand-side of the
  7396. assignment (the variable), 3) the continuation, and 4) the dictionary
  7397. of basic blocks. The \code{explicate\_assign} function returns a list
  7398. of \LangCIf{} statements and it may add to the dictionary of basic
  7399. blocks.
  7400. When the right-hand-side is an \code{if} expression, there is some
  7401. work to do. In particular, the two branches should be translated using
  7402. \code{explicate\_assign} and the condition expression should be
  7403. translated using \code{explicate\_pred}. Otherwise we can simply
  7404. generate an assignment statement, with the given left and right-hand
  7405. sides, concatenated with its continuation.
  7406. \begin{figure}[tbp]
  7407. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  7408. def explicate_effect(e, cont, basic_blocks):
  7409. match e:
  7410. case IfExp(test, body, orelse):
  7411. ...
  7412. case Call(func, args):
  7413. ...
  7414. case Begin(body, result):
  7415. ...
  7416. case _:
  7417. ...
  7418. def explicate_assign(rhs, lhs, cont, basic_blocks):
  7419. match rhs:
  7420. case IfExp(test, body, orelse):
  7421. ...
  7422. case Begin(body, result):
  7423. ...
  7424. case _:
  7425. return [Assign([lhs], rhs)] + cont
  7426. def explicate_pred(cnd, thn, els, basic_blocks):
  7427. match cnd:
  7428. case Compare(left, [op], [right]):
  7429. goto_thn = create_block(thn, basic_blocks)
  7430. goto_els = create_block(els, basic_blocks)
  7431. return [If(cnd, [goto_thn], [goto_els])]
  7432. case Constant(True):
  7433. return thn;
  7434. case Constant(False):
  7435. return els;
  7436. case UnaryOp(Not(), operand):
  7437. ...
  7438. case IfExp(test, body, orelse):
  7439. ...
  7440. case Begin(body, result):
  7441. ...
  7442. case _:
  7443. return [If(Compare(cnd, [Eq()], [Constant(False)]),
  7444. [create_block(els, basic_blocks)],
  7445. [create_block(thn, basic_blocks)])]
  7446. def explicate_stmt(s, cont, basic_blocks):
  7447. match s:
  7448. case Assign([lhs], rhs):
  7449. return explicate_assign(rhs, lhs, cont, basic_blocks)
  7450. case Expr(value):
  7451. return explicate_effect(value, cont, basic_blocks)
  7452. case If(test, body, orelse):
  7453. ...
  7454. def explicate_control(p):
  7455. match p:
  7456. case Module(body):
  7457. new_body = [Return(Constant(0))]
  7458. basic_blocks = {}
  7459. for s in reversed(body):
  7460. new_body = explicate_stmt(s, new_body, basic_blocks)
  7461. basic_blocks[label_name('start')] = new_body
  7462. return CProgram(basic_blocks)
  7463. \end{lstlisting}
  7464. \caption{Skeleton for the \code{explicate\_control} pass.}
  7465. \label{fig:explicate-control-Lif}
  7466. \end{figure}
  7467. \fi}
  7468. {\if\edition\racketEd
  7469. %
  7470. The \code{explicate\_tail} and \code{explicate\_assign} functions need
  7471. additional cases for Boolean constants and \key{if}. The cases for
  7472. \code{if} should recursively compile the two branches using either
  7473. \code{explicate\_tail} or \code{explicate\_assign}, respectively. The
  7474. cases should then invoke \code{explicate\_pred} on the condition
  7475. expression, passing in the generated code for the two branches. For
  7476. example, consider the following program with an \code{if} in tail
  7477. position.
  7478. \begin{lstlisting}
  7479. (let ([x (read)])
  7480. (if (eq? x 0) 42 777))
  7481. \end{lstlisting}
  7482. The two branches are recursively compiled to \code{return 42;} and
  7483. \code{return 777;}. We then delegate to \code{explicate\_pred},
  7484. passing the condition \code{(eq? x 0)} and the two return statements, which is
  7485. used as the result for \code{explicate\_tail}.
  7486. Next let us consider a program with an \code{if} on the right-hand
  7487. side of a \code{let}.
  7488. \begin{lstlisting}
  7489. (let ([y (read)])
  7490. (let ([x (if (eq? y 0) 40 777)])
  7491. (+ x 2)))
  7492. \end{lstlisting}
  7493. Note that the body of the inner \code{let} will have already been
  7494. compiled to \code{return (+ x 2);} and passed as the \code{cont}
  7495. parameter of \code{explicate\_assign}. We'll need to use \code{cont}
  7496. to recursively process both branches of the \code{if}, so we generate
  7497. the following block using an auxiliary function named \code{create\_block}.
  7498. \begin{lstlisting}
  7499. block_6:
  7500. return (+ x 2)
  7501. \end{lstlisting}
  7502. and use \code{goto block\_6;} as the \code{cont} argument for
  7503. compiling the branches. So the two branches compile to
  7504. \begin{lstlisting}
  7505. x = 40;
  7506. goto block_6;
  7507. \end{lstlisting}
  7508. and
  7509. \begin{lstlisting}
  7510. x = 777;
  7511. goto block_6;
  7512. \end{lstlisting}
  7513. We then delegate to \code{explicate\_pred}, passing the condition \code{(eq? y
  7514. 0)} and the above code for the branches.
  7515. \fi}
  7516. {\if\edition\racketEd
  7517. \begin{figure}[tbp]
  7518. \begin{lstlisting}
  7519. (define (explicate_pred cnd thn els)
  7520. (match cnd
  7521. [(Var x) ___]
  7522. [(Let x rhs body) ___]
  7523. [(Prim 'not (list e)) ___]
  7524. [(Prim op es) #:when (or (eq? op 'eq?) (eq? op '<))
  7525. (IfStmt (Prim op es) (create_block thn)
  7526. (create_block els))]
  7527. [(Bool b) (if b thn els)]
  7528. [(If cnd^ thn^ els^) ___]
  7529. [else (error "explicate_pred unhandled case" cnd)]))
  7530. \end{lstlisting}
  7531. \caption{Skeleton for the \key{explicate\_pred} auxiliary function.}
  7532. \label{fig:explicate-pred}
  7533. \end{figure}
  7534. \fi}
  7535. \racket{The skeleton for the \code{explicate\_pred} function is given
  7536. in Figure~\ref{fig:explicate-pred}. It takes three parameters:
  7537. 1) \code{cnd}, the condition expression of the \code{if},
  7538. 2) \code{thn}, the code generated by explicate for the ``then'' branch,
  7539. and 3) \code{els}, the code generated by
  7540. explicate for the ``else'' branch. The \code{explicate\_pred}
  7541. function should match on \code{cnd} with a case for
  7542. every kind of expression that can have type \code{Boolean}.}
  7543. %
  7544. \python{The \code{explicate\_pred} function has four parameters: 1)
  7545. the condition expression, 2) the generated statements for the
  7546. ``then'' branch, 3) the generated statements for the ``else''
  7547. branch, and 4) the dictionary of basic blocks. The
  7548. \code{explicate\_pred} function returns a list of \LangCIf{}
  7549. statements and it may add to the dictionary of basic blocks.}
  7550. Consider the case for comparison operators. We translate the
  7551. comparison to an \code{if} statement whose branches are \code{goto}
  7552. statements created by applying \code{create\_block} to the code
  7553. generated for the \code{thn} and \code{els} branches. Let us
  7554. illustrate this translation with an example. Returning
  7555. to the program with an \code{if} expression in tail position,
  7556. we invoke \code{explicate\_pred} on its condition
  7557. \racket{\code{(eq? x 0)}}
  7558. \python{\code{x == 0}}
  7559. which happens to be a comparison operator.
  7560. {\if\edition\racketEd
  7561. \begin{lstlisting}
  7562. (let ([x (read)])
  7563. (if (eq? x 0) 42 777))
  7564. \end{lstlisting}
  7565. \fi}
  7566. {\if\edition\pythonEd
  7567. \begin{lstlisting}
  7568. x = input_int()
  7569. 42 if x == 0 else 777
  7570. \end{lstlisting}
  7571. \fi}
  7572. The two branches \code{42} and \code{777} were already compiled to \code{return}
  7573. statements, from which we now create the following blocks.
  7574. \begin{center}
  7575. \begin{minipage}{\textwidth}
  7576. \begin{lstlisting}
  7577. block_1:
  7578. return 42;
  7579. block_2:
  7580. return 777;
  7581. \end{lstlisting}
  7582. \end{minipage}
  7583. \end{center}
  7584. %
  7585. So \code{explicate\_pred} compiles the comparison
  7586. \racket{\code{(eq? x 0)}}
  7587. \python{\code{x == 0}}
  7588. to the following \code{if} statement.
  7589. %
  7590. {\if\edition\racketEd
  7591. \begin{center}
  7592. \begin{minipage}{\textwidth}
  7593. \begin{lstlisting}
  7594. if (eq? x 0)
  7595. goto block_1;
  7596. else
  7597. goto block_2;
  7598. \end{lstlisting}
  7599. \end{minipage}
  7600. \end{center}
  7601. \fi}
  7602. {\if\edition\pythonEd
  7603. \begin{center}
  7604. \begin{minipage}{\textwidth}
  7605. \begin{lstlisting}
  7606. if x == 0:
  7607. goto block_1;
  7608. else
  7609. goto block_2;
  7610. \end{lstlisting}
  7611. \end{minipage}
  7612. \end{center}
  7613. \fi}
  7614. Next consider the case for Boolean constants. We perform a kind of
  7615. partial evaluation\index{subject}{partial evaluation} and output
  7616. either the \code{thn} or \code{els} branch depending on whether the
  7617. constant is \TRUE{} or \FALSE{}. Let us illustrate this with the
  7618. following program.
  7619. {\if\edition\racketEd
  7620. \begin{center}
  7621. \begin{minipage}{\textwidth}
  7622. \begin{lstlisting}
  7623. (if #t 42 777)
  7624. \end{lstlisting}
  7625. \end{minipage}
  7626. \end{center}
  7627. \fi}
  7628. {\if\edition\pythonEd
  7629. \begin{center}
  7630. \begin{minipage}{\textwidth}
  7631. \begin{lstlisting}
  7632. 42 if True else 777
  7633. \end{lstlisting}
  7634. \end{minipage}
  7635. \end{center}
  7636. \fi}
  7637. %
  7638. Again, the two branches \code{42} and \code{777} were compiled to
  7639. \code{return} statements, so \code{explicate\_pred} compiles the
  7640. constant
  7641. \racket{\code{\#t}}
  7642. \python{\code{True}}
  7643. to the code for the ``then'' branch.
  7644. \begin{center}
  7645. \begin{minipage}{\textwidth}
  7646. \begin{lstlisting}
  7647. return 42;
  7648. \end{lstlisting}
  7649. \end{minipage}
  7650. \end{center}
  7651. %
  7652. This case demonstrates that we sometimes discard the \code{thn} or
  7653. \code{els} blocks that are input to \code{explicate\_pred}.
  7654. The case for \key{if} expressions in \code{explicate\_pred} is
  7655. particularly illuminating because it deals with the challenges we
  7656. discussed above regarding nested \key{if} expressions
  7657. (Figure~\ref{fig:explicate-control-s1-38}). The
  7658. \racket{\lstinline{thn^}}\python{\code{body}} and
  7659. \racket{\lstinline{els^}}\python{\code{orelse}} branches of the
  7660. \key{if} inherit their context from the current one, that is,
  7661. predicate context. So you should recursively apply
  7662. \code{explicate\_pred} to the
  7663. \racket{\lstinline{thn^}}\python{\code{body}} and
  7664. \racket{\lstinline{els^}}\python{\code{orelse}} branches. For both of
  7665. those recursive calls, pass \code{thn} and \code{els} as the extra
  7666. parameters. Thus, \code{thn} and \code{els} may get used twice, once
  7667. inside each recursive call. As discussed above, to avoid duplicating
  7668. code, we need to add them to the dictionary of basic blocks so that we
  7669. can instead refer to them by name and execute them with a \key{goto}.
  7670. {\if\edition\pythonEd
  7671. %
  7672. The last of the auxiliary functions is \code{explicate\_stmt}. It has
  7673. three parameters: 1) the statement to be compiled, 2) the code for its
  7674. continuation, and 3) the dictionary of basic blocks. The
  7675. \code{explicate\_stmt} returns a list of statements and it may add to
  7676. the dictionary of basic blocks. The cases for assignment and an
  7677. expression-statement are given in full in the skeleton code: they
  7678. simply dispatch to \code{explicate\_assign} and
  7679. \code{explicate\_effect}, respectively. The case for \code{if}
  7680. statements is not given, and is similar to the case for \code{if}
  7681. expressions.
  7682. The \code{explicate\_control} function itself is given in
  7683. Figure~\ref{fig:explicate-control-Lif}. It applies
  7684. \code{explicate\_stmt} to each statement in the program, from back to
  7685. front. Thus, the result so-far, stored in \code{new\_body}, can be
  7686. used as the continuation parameter in the next call to
  7687. \code{explicate\_stmt}. The \code{new\_body} is initialized to a
  7688. \code{Return} statement. Once complete, we add the \code{new\_body} to
  7689. the dictionary of basic blocks, labeling it as the ``start'' block.
  7690. %
  7691. \fi}
  7692. %% Getting back to the case for \code{if} in \code{explicate\_pred}, we
  7693. %% make the recursive calls to \code{explicate\_pred} on the ``then'' and
  7694. %% ``else'' branches with the arguments \code{(create_block} $B_1$\code{)}
  7695. %% and \code{(create_block} $B_2$\code{)}. Let $B_3$ and $B_4$ be the
  7696. %% results from the two recursive calls. We complete the case for
  7697. %% \code{if} by recursively apply \code{explicate\_pred} to the condition
  7698. %% of the \code{if} with the promised blocks $B_3$ and $B_4$ to obtain
  7699. %% the result $B_5$.
  7700. %% \[
  7701. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els})
  7702. %% \quad\Rightarrow\quad
  7703. %% B_5
  7704. %% \]
  7705. %% In the case for \code{if} in \code{explicate\_tail}, the two branches
  7706. %% inherit the current context, so they are in tail position. Thus, the
  7707. %% recursive calls on the ``then'' and ``else'' branch should be calls to
  7708. %% \code{explicate\_tail}.
  7709. %% %
  7710. %% We need to pass $B_0$ as the accumulator argument for both of these
  7711. %% recursive calls, but we need to be careful not to duplicate $B_0$.
  7712. %% Thus, we first apply \code{create_block} to $B_0$ so that it gets added
  7713. %% to the control-flow graph and obtain a promised goto $G_0$.
  7714. %% %
  7715. %% Let $B_1$ be the result of \code{explicate\_tail} on the ``then''
  7716. %% branch and $G_0$ and let $B_2$ be the result of \code{explicate\_tail}
  7717. %% on the ``else'' branch and $G_0$. Let $B_3$ be the result of applying
  7718. %% \code{explicate\_pred} to the condition of the \key{if}, $B_1$, and
  7719. %% $B_2$. Then the \key{if} as a whole translates to promise $B_3$.
  7720. %% \[
  7721. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_3
  7722. %% \]
  7723. %% In the above discussion, we use the metavariables $B_1$, $B_2$, and
  7724. %% $B_3$ to refer to blocks for the purposes of our discussion, but they
  7725. %% should not be confused with the labels for the blocks that appear in
  7726. %% the generated code. We initially construct unlabeled blocks; we only
  7727. %% attach labels to blocks when we add them to the control-flow graph, as
  7728. %% we see in the next case.
  7729. %% Next consider the case for \key{if} in the \code{explicate\_assign}
  7730. %% function. The context of the \key{if} is an assignment to some
  7731. %% variable $x$ and then the control continues to some promised block
  7732. %% $B_1$. The code that we generate for both the ``then'' and ``else''
  7733. %% branches needs to continue to $B_1$, so to avoid duplicating $B_1$ we
  7734. %% apply \code{create_block} to it and obtain a promised goto $G_1$. The
  7735. %% branches of the \key{if} inherit the current context, so they are in
  7736. %% assignment positions. Let $B_2$ be the result of applying
  7737. %% \code{explicate\_assign} to the ``then'' branch, variable $x$, and
  7738. %% $G_1$. Let $B_3$ be the result of applying \code{explicate\_assign} to
  7739. %% the ``else'' branch, variable $x$, and $G_1$. Finally, let $B_4$ be
  7740. %% the result of applying \code{explicate\_pred} to the predicate
  7741. %% $\itm{cnd}$ and the promises $B_2$ and $B_3$. The \key{if} as a whole
  7742. %% translates to the promise $B_4$.
  7743. %% \[
  7744. %% (\key{if}\; \itm{cnd}\; \itm{thn}\; \itm{els}) \quad\Rightarrow\quad B_4
  7745. %% \]
  7746. %% This completes the description of \code{explicate\_control} for \LangIf{}.
  7747. Figure~\ref{fig:explicate-control-s1-38} shows the output of the
  7748. \code{remove\_complex\_operands} pass and then the
  7749. \code{explicate\_control} pass on the example program. We walk through
  7750. the output program.
  7751. %
  7752. Following the order of evaluation in the output of
  7753. \code{remove\_complex\_operands}, we first have two calls to \CREAD{}
  7754. and then the comparison \racket{\code{(< x 1)}}\python{\code{x < 1}}
  7755. in the predicate of the inner \key{if}. In the output of
  7756. \code{explicate\_control}, in the
  7757. block labeled \code{start}, are two assignment statements followed by a
  7758. \code{if} statement that branches to \code{block\_8} or
  7759. \code{block\_9}. The blocks associated with those labels contain the
  7760. translations of the code
  7761. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7762. and
  7763. \racket{\code{(eq? x 2)}}\python{\code{x == 2}},
  7764. respectively. In particular, we start \code{block\_8} with the
  7765. comparison
  7766. \racket{\code{(eq? x 0)}}\python{\code{x == 0}}
  7767. and then branch to \code{block\_4} or \code{block\_5}.
  7768. Here was see that our algorithm sometimes inserts unnecessary blocks:
  7769. \code{block\_4} is just a \code{goto} to \code{block\_2}
  7770. and \code{block\_5} is just a \code{goto} to \code{block\_3}.
  7771. It would be better to skip blocks \code{block\_4} and \code{block\_5}
  7772. and go directly to \code{block\_2} and \code{block\_3},
  7773. which we investigate in Section~\ref{sec:opt-jumps}.
  7774. Getting back to the example, \code{block\_2} and \code{block\_3},
  7775. corresponds to the two branches of the outer \key{if}, i.e.,
  7776. \racket{\code{(+ y 2)}}\python{\code{y + 2}} and
  7777. \racket{\code{(+ y 10)}}\python{\code{y + 10}}.
  7778. %
  7779. The story for \code{block\_9} is similar to that of \code{block\_8}.
  7780. %
  7781. \python{The \code{block\_1} corresponds to the \code{print} statment
  7782. at the end of the program.}
  7783. \begin{figure}[tbp]
  7784. {\if\edition\racketEd
  7785. \begin{tabular}{lll}
  7786. \begin{minipage}{0.4\textwidth}
  7787. % cond_test_41.rkt
  7788. \begin{lstlisting}
  7789. (let ([x (read)])
  7790. (let ([y (read)])
  7791. (if (if (< x 1)
  7792. (eq? x 0)
  7793. (eq? x 2))
  7794. (+ y 2)
  7795. (+ y 10))))
  7796. \end{lstlisting}
  7797. \end{minipage}
  7798. &
  7799. $\Rightarrow$
  7800. &
  7801. \begin{minipage}{0.55\textwidth}
  7802. \begin{lstlisting}
  7803. start:
  7804. x = (read);
  7805. y = (read);
  7806. if (< x 1)
  7807. goto block_8;
  7808. else
  7809. goto block_9;
  7810. block_8:
  7811. if (eq? x 0)
  7812. goto block_4;
  7813. else
  7814. goto block_5;
  7815. block_9:
  7816. if (eq? x 2)
  7817. goto block_6;
  7818. else
  7819. goto block_7;
  7820. block_4:
  7821. goto block_2;
  7822. block_5:
  7823. goto block_3;
  7824. block_6:
  7825. goto block_2;
  7826. block_7:
  7827. goto block_3;
  7828. block_2:
  7829. return (+ y 2);
  7830. block_3:
  7831. return (+ y 10);
  7832. \end{lstlisting}
  7833. \end{minipage}
  7834. \end{tabular}
  7835. \fi}
  7836. {\if\edition\pythonEd
  7837. \begin{tabular}{lll}
  7838. \begin{minipage}{0.4\textwidth}
  7839. % cond_test_41.rkt
  7840. \begin{lstlisting}
  7841. x = input_int()
  7842. y = input_int()
  7843. print(y + 2 \
  7844. if (x == 0 \
  7845. if x < 1 \
  7846. else x == 2) \
  7847. else y + 10)
  7848. \end{lstlisting}
  7849. \end{minipage}
  7850. &
  7851. $\Rightarrow$
  7852. &
  7853. \begin{minipage}{0.55\textwidth}
  7854. \begin{lstlisting}
  7855. start:
  7856. x = input_int()
  7857. y = input_int()
  7858. if x < 1:
  7859. goto block_8
  7860. else:
  7861. goto block_9
  7862. block_8:
  7863. if x == 0:
  7864. goto block_4
  7865. else:
  7866. goto block_5
  7867. block_9:
  7868. if x == 2:
  7869. goto block_6
  7870. else:
  7871. goto block_7
  7872. block_4:
  7873. goto block_2
  7874. block_5:
  7875. goto block_3
  7876. block_6:
  7877. goto block_2
  7878. block_7:
  7879. goto block_3
  7880. block_2:
  7881. tmp_0 = y + 2
  7882. goto block_1
  7883. block_3:
  7884. tmp_0 = y + 10
  7885. goto block_1
  7886. block_1:
  7887. print(tmp_0)
  7888. return 0
  7889. \end{lstlisting}
  7890. \end{minipage}
  7891. \end{tabular}
  7892. \fi}
  7893. \caption{Translation from \LangIf{} to \LangCIf{}
  7894. via the \code{explicate\_control}.}
  7895. \label{fig:explicate-control-s1-38}
  7896. \end{figure}
  7897. {\if\edition\racketEd
  7898. The way in which the \code{shrink} pass transforms logical operations
  7899. such as \code{and} and \code{or} can impact the quality of code
  7900. generated by \code{explicate\_control}. For example, consider the
  7901. following program.
  7902. % cond_test_21.rkt, and_eq_input.py
  7903. \begin{lstlisting}
  7904. (if (and (eq? (read) 0) (eq? (read) 1))
  7905. 0
  7906. 42)
  7907. \end{lstlisting}
  7908. The \code{and} operation should transform into something that the
  7909. \code{explicate\_pred} function can still analyze and descend through to
  7910. reach the underlying \code{eq?} conditions. Ideally, your
  7911. \code{explicate\_control} pass should generate code similar to the
  7912. following for the above program.
  7913. \begin{center}
  7914. \begin{lstlisting}
  7915. start:
  7916. tmp1 = (read);
  7917. if (eq? tmp1 0) goto block40;
  7918. else goto block39;
  7919. block40:
  7920. tmp2 = (read);
  7921. if (eq? tmp2 1) goto block38;
  7922. else goto block39;
  7923. block38:
  7924. return 0;
  7925. block39:
  7926. return 42;
  7927. \end{lstlisting}
  7928. \end{center}
  7929. \fi}
  7930. \begin{exercise}\normalfont\normalsize
  7931. \racket{
  7932. Implement the pass \code{explicate\_control} by adding the cases for
  7933. Boolean constants and \key{if} to the \code{explicate\_tail} and
  7934. \code{explicate\_assign} functions. Implement the auxiliary function
  7935. \code{explicate\_pred} for predicate contexts.}
  7936. \python{Implement \code{explicate\_control} pass with its
  7937. four auxiliary functions.}
  7938. %
  7939. Create test cases that exercise all of the new cases in the code for
  7940. this pass.
  7941. %
  7942. {\if\edition\racketEd
  7943. Add the following entry to the list of \code{passes} in
  7944. \code{run-tests.rkt} and then run this script to test your compiler.
  7945. \begin{lstlisting}
  7946. (list "explicate_control" explicate_control interp-Cif type-check-Cif)
  7947. \end{lstlisting}
  7948. \fi}
  7949. \end{exercise}
  7950. \clearpage
  7951. \section{Select Instructions}
  7952. \label{sec:select-Lif}
  7953. \index{subject}{instruction selection}
  7954. The \code{select\_instructions} pass translates \LangCIf{} to
  7955. \LangXIfVar{}.
  7956. %
  7957. \racket{Recall that we implement this pass using three auxiliary
  7958. functions, one for each of the non-terminals $\Atm$, $\Stmt$, and
  7959. $\Tail$.}
  7960. %
  7961. \racket{For $\Atm$, we have new cases for the Booleans.}
  7962. %
  7963. \python{We begin with the Boolean constants.}
  7964. We take the usual approach of encoding them as integers.
  7965. \[
  7966. \TRUE{} \quad\Rightarrow\quad \key{1}
  7967. \qquad\qquad
  7968. \FALSE{} \quad\Rightarrow\quad \key{0}
  7969. \]
  7970. For translating statements, we discuss a selection of cases. The \code{not}
  7971. operation can be implemented in terms of \code{xorq} as we discussed
  7972. at the beginning of this section. Given an assignment, if the
  7973. left-hand side variable is the same as the argument of \code{not},
  7974. then just the \code{xorq} instruction suffices.
  7975. \[
  7976. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Var} }
  7977. \quad\Rightarrow\quad
  7978. \key{xorq}~\key{\$}1\key{,}~\Var
  7979. \]
  7980. Otherwise, a \key{movq} is needed to adapt to the update-in-place
  7981. semantics of x86. In the following translation, let $\Arg$ be the
  7982. result of translating $\Atm$ to x86.
  7983. \[
  7984. \CASSIGN{\Var}{ \CUNIOP{\key{not}}{\Atm} }
  7985. \quad\Rightarrow\quad
  7986. \begin{array}{l}
  7987. \key{movq}~\Arg\key{,}~\Var\\
  7988. \key{xorq}~\key{\$}1\key{,}~\Var
  7989. \end{array}
  7990. \]
  7991. Next consider the cases for equality. Translating this operation to
  7992. x86 is slightly involved due to the unusual nature of the \key{cmpq}
  7993. instruction discussed above. We recommend translating an assignment
  7994. with an equality on the right-hand side into a sequence of three
  7995. instructions. \\
  7996. \begin{tabular}{lll}
  7997. \begin{minipage}{0.4\textwidth}
  7998. \begin{lstlisting}
  7999. |$\CASSIGN{\Var}{ \LP\CEQ{\Atm_1}{\Atm_2} \RP }$|
  8000. \end{lstlisting}
  8001. \end{minipage}
  8002. &
  8003. $\Rightarrow$
  8004. &
  8005. \begin{minipage}{0.4\textwidth}
  8006. \begin{lstlisting}
  8007. cmpq |$\Arg_2$|, |$\Arg_1$|
  8008. sete %al
  8009. movzbq %al, |$\Var$|
  8010. \end{lstlisting}
  8011. \end{minipage}
  8012. \end{tabular} \\
  8013. The translations for the other comparison operators are similar to the
  8014. above but use different suffixes for the \code{set} instruction.
  8015. \racket{Regarding the $\Tail$ non-terminal, we have two new cases:
  8016. \key{goto} and \key{if} statements. Both are straightforward to
  8017. translate to x86.}
  8018. %
  8019. A \key{goto} statement becomes a jump instruction.
  8020. \[
  8021. \key{goto}\; \ell\racket{\key{;}} \quad \Rightarrow \quad \key{jmp}\;\ell
  8022. \]
  8023. %
  8024. An \key{if} statement becomes a compare instruction followed by a
  8025. conditional jump (for the ``then'' branch) and the fall-through is to
  8026. a regular jump (for the ``else'' branch).\\
  8027. \begin{tabular}{lll}
  8028. \begin{minipage}{0.4\textwidth}
  8029. \begin{lstlisting}
  8030. if |$\CEQ{\Atm_1}{\Atm_2}$||$\python{\key{:}}$|
  8031. goto |$\ell_1$||$\racket{\key{;}}$|
  8032. else|$\python{\key{:}}$|
  8033. goto |$\ell_2$||$\racket{\key{;}}$|
  8034. \end{lstlisting}
  8035. \end{minipage}
  8036. &
  8037. $\Rightarrow$
  8038. &
  8039. \begin{minipage}{0.4\textwidth}
  8040. \begin{lstlisting}
  8041. cmpq |$\Arg_2$|, |$\Arg_1$|
  8042. je |$\ell_1$|
  8043. jmp |$\ell_2$|
  8044. \end{lstlisting}
  8045. \end{minipage}
  8046. \end{tabular} \\
  8047. Again, the translations for the other comparison operators are similar to the
  8048. above but use different suffixes for the conditional jump instruction.
  8049. \python{Regarding the \key{return} statement, we recommend treating it
  8050. as an assignment to the \key{rax} register followed by a jump to the
  8051. conclusion of the \code{main} function.}
  8052. \begin{exercise}\normalfont\normalsize
  8053. Expand your \code{select\_instructions} pass to handle the new
  8054. features of the \LangIf{} language.
  8055. %
  8056. {\if\edition\racketEd
  8057. Add the following entry to the list of \code{passes} in
  8058. \code{run-tests.rkt}
  8059. \begin{lstlisting}
  8060. (list "select_instructions" select_instructions interp-pseudo-x86-1)
  8061. \end{lstlisting}
  8062. \fi}
  8063. %
  8064. Run the script to test your compiler on all the test programs.
  8065. \end{exercise}
  8066. \section{Register Allocation}
  8067. \label{sec:register-allocation-Lif}
  8068. \index{subject}{register allocation}
  8069. The changes required for \LangIf{} affect liveness analysis, building the
  8070. interference graph, and assigning homes, but the graph coloring
  8071. algorithm itself does not change.
  8072. \subsection{Liveness Analysis}
  8073. \label{sec:liveness-analysis-Lif}
  8074. \index{subject}{liveness analysis}
  8075. Recall that for \LangVar{} we implemented liveness analysis for a
  8076. single basic block (Section~\ref{sec:liveness-analysis-Lvar}). With
  8077. the addition of \key{if} expressions to \LangIf{},
  8078. \code{explicate\_control} produces many basic blocks.
  8079. %% We recommend that you create a new auxiliary function named
  8080. %% \code{uncover\_live\_CFG} that applies liveness analysis to a
  8081. %% control-flow graph.
  8082. The first question is: in what order should we process the basic blocks?
  8083. Recall that to perform liveness analysis on a basic block we need to
  8084. know the live-after set for the last instruction in the block. If a
  8085. basic block has no successors (i.e. contains no jumps to other
  8086. blocks), then it has an empty live-after set and we can immediately
  8087. apply liveness analysis to it. If a basic block has some successors,
  8088. then we need to complete liveness analysis on those blocks
  8089. first. These ordering contraints are the reverse of a
  8090. \emph{topological order}\index{subject}{topological order} on a graph
  8091. representation of the program. In particular, the \emph{control flow
  8092. graph} (CFG)\index{subject}{control-flow graph}~\citep{Allen:1970uq}
  8093. of a program has a node for each basic block and an edge for each jump
  8094. from one block to another. It is straightforward to generate a CFG
  8095. from the dictionary of basic blocks. One then transposes the CFG and
  8096. applies the topological sort algorithm.
  8097. %
  8098. %
  8099. \racket{We recommend using the \code{tsort} and \code{transpose}
  8100. functions of the Racket \code{graph} package to accomplish this.}
  8101. %
  8102. \python{We provide implementations of \code{topological\_sort} and
  8103. \code{transpose} in the file \code{graph.py} of the support code.}
  8104. %
  8105. As an aside, a topological ordering is only guaranteed to exist if the
  8106. graph does not contain any cycles. This is the case for the
  8107. control-flow graphs that we generate from \LangIf{} programs.
  8108. However, in Chapter~\ref{ch:Lwhile} we add loops to create \LangLoop{}
  8109. and learn how to handle cycles in the control-flow graph.
  8110. \racket{You'll need to construct a directed graph to represent the
  8111. control-flow graph. Do not use the \code{directed-graph} of the
  8112. \code{graph} package because that only allows at most one edge
  8113. between each pair of vertices, but a control-flow graph may have
  8114. multiple edges between a pair of vertices. The \code{multigraph.rkt}
  8115. file in the support code implements a graph representation that
  8116. allows multiple edges between a pair of vertices.}
  8117. {\if\edition\racketEd
  8118. The next question is how to analyze jump instructions. Recall that in
  8119. Section~\ref{sec:liveness-analysis-Lvar} we maintain an alist named
  8120. \code{label->live} that maps each label to the set of live locations
  8121. at the beginning of its block. We use \code{label->live} to determine
  8122. the live-before set for each $\JMP{\itm{label}}$ instruction. Now
  8123. that we have many basic blocks, \code{label->live} needs to be updated
  8124. as we process the blocks. In particular, after performing liveness
  8125. analysis on a block, we take the live-before set of its first
  8126. instruction and associate that with the block's label in the
  8127. \code{label->live}.
  8128. \fi}
  8129. %
  8130. {\if\edition\pythonEd
  8131. %
  8132. The next question is how to analyze jump instructions. The locations
  8133. that are live before a \code{jmp} should be the locations in
  8134. $L_{\mathtt{before}}$ at the target of the jump. So we recommend
  8135. maintaining a dictionary named \code{live\_before\_block} that maps each
  8136. label to the $L_{\mathtt{before}}$ for the first instruction in its
  8137. block. After performing liveness analysis on each block, we take the
  8138. live-before set of its first instruction and associate that with the
  8139. block's label in the \code{live\_before\_block} dictionary.
  8140. %
  8141. \fi}
  8142. In \LangXIfVar{} we also have the conditional jump
  8143. $\JMPIF{\itm{cc}}{\itm{label}}$ to deal with. Liveness analysis for
  8144. this instruction is particularly interesting because, during
  8145. compilation, we do not know which way a conditional jump will go. So
  8146. we do not know whether to use the live-before set for the following
  8147. instruction or the live-before set for the block associated with the
  8148. $\itm{label}$. However, there is no harm to the correctness of the
  8149. generated code if we classify more locations as live than the ones
  8150. that are truly live during one particular execution of the
  8151. instruction. Thus, we can take the union of the live-before sets from
  8152. the following instruction and from the mapping for $\itm{label}$ in
  8153. \racket{\code{label->live}}\python{\code{live\_before\_block}}.
  8154. The auxiliary functions for computing the variables in an
  8155. instruction's argument and for computing the variables read-from ($R$)
  8156. or written-to ($W$) by an instruction need to be updated to handle the
  8157. new kinds of arguments and instructions in \LangXIfVar{}.
  8158. \begin{exercise}\normalfont\normalsize
  8159. {\if\edition\racketEd
  8160. %
  8161. Update the \code{uncover\_live} pass to apply liveness analysis to
  8162. every basic block in the program.
  8163. %
  8164. Add the following entry to the list of \code{passes} in the
  8165. \code{run-tests.rkt} script.
  8166. \begin{lstlisting}
  8167. (list "uncover_live" uncover_live interp-pseudo-x86-1)
  8168. \end{lstlisting}
  8169. \fi}
  8170. {\if\edition\pythonEd
  8171. %
  8172. Update the \code{uncover\_live} function to perform liveness analysis,
  8173. in reverse topological order, on all of the basic blocks in the
  8174. program.
  8175. %
  8176. \fi}
  8177. % Check that the live-after sets that you generate for
  8178. % example X matches the following... -Jeremy
  8179. \end{exercise}
  8180. \subsection{Build the Interference Graph}
  8181. \label{sec:build-interference-Lif}
  8182. Many of the new instructions in \LangXIfVar{} can be handled in the
  8183. same way as the instructions in \LangXVar{}.
  8184. % Thus, if your code was
  8185. % already quite general, it will not need to be changed to handle the
  8186. % new instructions. If your code is not general enough, we recommend that
  8187. % you change your code to be more general. For example, you can factor
  8188. % out the computing of the the read and write sets for each kind of
  8189. % instruction into auxiliary functions.
  8190. %
  8191. Some instructions, e.g., the \key{movzbq} instruction, require special care,
  8192. similar to the \key{movq} instruction. See rule number 1 in
  8193. Section~\ref{sec:build-interference}.
  8194. \begin{exercise}\normalfont\normalsize
  8195. Update the \code{build\_interference} pass for \LangXIfVar{}.
  8196. {\if\edition\racketEd
  8197. Add the following entries to the list of \code{passes} in the
  8198. \code{run-tests.rkt} script.
  8199. \begin{lstlisting}
  8200. (list "build_interference" build_interference interp-pseudo-x86-1)
  8201. (list "allocate_registers" allocate_registers interp-x86-1)
  8202. \end{lstlisting}
  8203. \fi}
  8204. % Check that the interference graph that you generate for
  8205. % example X matches the following graph G... -Jeremy
  8206. \end{exercise}
  8207. \section{Patch Instructions}
  8208. The new instructions \key{cmpq} and \key{movzbq} have some special
  8209. restrictions that need to be handled in the \code{patch\_instructions}
  8210. pass.
  8211. %
  8212. The second argument of the \key{cmpq} instruction must not be an
  8213. immediate value (such as an integer). So if you are comparing two
  8214. immediates, we recommend inserting a \key{movq} instruction to put the
  8215. second argument in \key{rax}. As usual, \key{cmpq} may have at most
  8216. one memory reference.
  8217. %
  8218. The second argument of the \key{movzbq} must be a register.
  8219. \begin{exercise}\normalfont\normalsize
  8220. %
  8221. Update \code{patch\_instructions} pass for \LangXIfVar{}.
  8222. %
  8223. {\if\edition\racketEd
  8224. Add the following entry to the list of \code{passes} in
  8225. \code{run-tests.rkt} and then run this script to test your compiler.
  8226. \begin{lstlisting}
  8227. (list "patch_instructions" patch_instructions interp-x86-1)
  8228. \end{lstlisting}
  8229. \fi}
  8230. \end{exercise}
  8231. {\if\edition\pythonEd
  8232. \section{Prelude and Conclusion}
  8233. \label{sec:prelude-conclusion-cond}
  8234. The generation of the \code{main} function with its prelude and
  8235. conclusion must change to accomodate how the program now consists of
  8236. one or more basic blocks. After the prelude in \code{main}, jump to
  8237. the \code{start} block. Place the conclusion in a basic block labelled
  8238. with \code{conclusion}.
  8239. \fi}
  8240. Figure~\ref{fig:if-example-x86} shows a simple example program in
  8241. \LangIf{} translated to x86, showing the results of
  8242. \code{explicate\_control}, \code{select\_instructions}, and the final
  8243. x86 assembly.
  8244. \begin{figure}[tbp]
  8245. {\if\edition\racketEd
  8246. \begin{tabular}{lll}
  8247. \begin{minipage}{0.4\textwidth}
  8248. % cond_test_20.rkt, eq_input.py
  8249. \begin{lstlisting}
  8250. (if (eq? (read) 1) 42 0)
  8251. \end{lstlisting}
  8252. $\Downarrow$
  8253. \begin{lstlisting}
  8254. start:
  8255. tmp7951 = (read);
  8256. if (eq? tmp7951 1)
  8257. goto block7952;
  8258. else
  8259. goto block7953;
  8260. block7952:
  8261. return 42;
  8262. block7953:
  8263. return 0;
  8264. \end{lstlisting}
  8265. $\Downarrow$
  8266. \begin{lstlisting}
  8267. start:
  8268. callq read_int
  8269. movq %rax, tmp7951
  8270. cmpq $1, tmp7951
  8271. je block7952
  8272. jmp block7953
  8273. block7953:
  8274. movq $0, %rax
  8275. jmp conclusion
  8276. block7952:
  8277. movq $42, %rax
  8278. jmp conclusion
  8279. \end{lstlisting}
  8280. \end{minipage}
  8281. &
  8282. $\Rightarrow\qquad$
  8283. \begin{minipage}{0.4\textwidth}
  8284. \begin{lstlisting}
  8285. start:
  8286. callq read_int
  8287. movq %rax, %rcx
  8288. cmpq $1, %rcx
  8289. je block7952
  8290. jmp block7953
  8291. block7953:
  8292. movq $0, %rax
  8293. jmp conclusion
  8294. block7952:
  8295. movq $42, %rax
  8296. jmp conclusion
  8297. .globl main
  8298. main:
  8299. pushq %rbp
  8300. movq %rsp, %rbp
  8301. pushq %r13
  8302. pushq %r12
  8303. pushq %rbx
  8304. pushq %r14
  8305. subq $0, %rsp
  8306. jmp start
  8307. conclusion:
  8308. addq $0, %rsp
  8309. popq %r14
  8310. popq %rbx
  8311. popq %r12
  8312. popq %r13
  8313. popq %rbp
  8314. retq
  8315. \end{lstlisting}
  8316. \end{minipage}
  8317. \end{tabular}
  8318. \fi}
  8319. {\if\edition\pythonEd
  8320. \begin{tabular}{lll}
  8321. \begin{minipage}{0.4\textwidth}
  8322. % cond_test_20.rkt, eq_input.py
  8323. \begin{lstlisting}
  8324. print(42 if input_int() == 1 else 0)
  8325. \end{lstlisting}
  8326. $\Downarrow$
  8327. \begin{lstlisting}
  8328. start:
  8329. tmp_0 = input_int()
  8330. if tmp_0 == 1:
  8331. goto block_3
  8332. else:
  8333. goto block_4
  8334. block_3:
  8335. tmp_1 = 42
  8336. goto block_2
  8337. block_4:
  8338. tmp_1 = 0
  8339. goto block_2
  8340. block_2:
  8341. print(tmp_1)
  8342. return 0
  8343. \end{lstlisting}
  8344. $\Downarrow$
  8345. \begin{lstlisting}
  8346. start:
  8347. callq read_int
  8348. movq %rax, tmp_0
  8349. cmpq 1, tmp_0
  8350. je block_3
  8351. jmp block_4
  8352. block_3:
  8353. movq 42, tmp_1
  8354. jmp block_2
  8355. block_4:
  8356. movq 0, tmp_1
  8357. jmp block_2
  8358. block_2:
  8359. movq tmp_1, %rdi
  8360. callq print_int
  8361. movq 0, %rax
  8362. jmp conclusion
  8363. \end{lstlisting}
  8364. \end{minipage}
  8365. &
  8366. $\Rightarrow\qquad$
  8367. \begin{minipage}{0.4\textwidth}
  8368. \begin{lstlisting}
  8369. .globl main
  8370. main:
  8371. pushq %rbp
  8372. movq %rsp, %rbp
  8373. subq $0, %rsp
  8374. jmp start
  8375. start:
  8376. callq read_int
  8377. movq %rax, %rcx
  8378. cmpq $1, %rcx
  8379. je block_3
  8380. jmp block_4
  8381. block_3:
  8382. movq $42, %rcx
  8383. jmp block_2
  8384. block_4:
  8385. movq $0, %rcx
  8386. jmp block_2
  8387. block_2:
  8388. movq %rcx, %rdi
  8389. callq print_int
  8390. movq $0, %rax
  8391. jmp conclusion
  8392. conclusion:
  8393. addq $0, %rsp
  8394. popq %rbp
  8395. retq
  8396. \end{lstlisting}
  8397. \end{minipage}
  8398. \end{tabular}
  8399. \fi}
  8400. \caption{Example compilation of an \key{if} expression to x86, showing
  8401. the results of \code{explicate\_control},
  8402. \code{select\_instructions}, and the final x86 assembly code. }
  8403. \label{fig:if-example-x86}
  8404. \end{figure}
  8405. \begin{figure}[tbp]
  8406. {\if\edition\racketEd
  8407. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8408. \node (Lif) at (0,2) {\large \LangIf{}};
  8409. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8410. \node (Lif-3) at (6,2) {\large \LangIf{}};
  8411. \node (Lif-4) at (9,2) {\large \LangIf{}};
  8412. \node (Lif-5) at (12,2) {\large \LangIfANF{}};
  8413. \node (C1-1) at (3,0) {\large \LangCIf{}};
  8414. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  8415. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  8416. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  8417. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  8418. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  8419. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  8420. \path[->,bend left=15] (Lif) edge [above] node {\ttfamily\footnotesize type\_check} (Lif-2);
  8421. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize shrink} (Lif-3);
  8422. \path[->,bend left=15] (Lif-3) edge [above] node {\ttfamily\footnotesize uniquify} (Lif-4);
  8423. \path[->,bend left=15] (Lif-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-5);
  8424. \path[->,bend left=15] (Lif-5) edge [left] node {\ttfamily\footnotesize explicate\_control} (C1-1);
  8425. \path[->,bend right=15] (C1-1) edge [left] node {\ttfamily\footnotesize select\_instructions} (x86-2);
  8426. \path[->,bend left=15] (x86-2) edge [right] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  8427. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  8428. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  8429. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  8430. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86 } (x86-5);
  8431. \end{tikzpicture}
  8432. \fi}
  8433. {\if\edition\pythonEd
  8434. \begin{tikzpicture}[baseline=(current bounding box.center)]
  8435. \node (Lif-1) at (0,2) {\large \LangIf{}};
  8436. \node (Lif-2) at (3,2) {\large \LangIf{}};
  8437. \node (Lif-3) at (6,2) {\large \LangIfANF{}};
  8438. \node (C-1) at (3,0) {\large \LangCIf{}};
  8439. \node (x86-1) at (3,-2) {\large \LangXIfVar{}};
  8440. \node (x86-2) at (6,-2) {\large \LangXIfVar{}};
  8441. \node (x86-3) at (9,-2) {\large \LangXIf{}};
  8442. \node (x86-4) at (12,-2) {\large \LangXIf{}};
  8443. \path[->,bend left=15] (Lif-1) edge [above] node {\ttfamily\footnotesize shrink} (Lif-2);
  8444. \path[->,bend left=15] (Lif-2) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lif-3);
  8445. \path[->,bend left=15] (Lif-3) edge [right] node {\ttfamily\footnotesize explicate\_control} (C-1);
  8446. \path[->,bend right=15] (C-1) edge [left] node {\ttfamily\footnotesize select\_instr.} (x86-1);
  8447. \path[->,bend right=15] (x86-1) edge [below] node {\ttfamily\footnotesize assign\_homes} (x86-2);
  8448. \path[->,bend left=15] (x86-2) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-3);
  8449. \path[->,bend right=15] (x86-3) edge [below] node {\ttfamily\footnotesize prelude\_and\_concl. } (x86-4);
  8450. \end{tikzpicture}
  8451. \fi}
  8452. \caption{Diagram of the passes for \LangIf{}, a language with conditionals.}
  8453. \label{fig:Lif-passes}
  8454. \end{figure}
  8455. Figure~\ref{fig:Lif-passes} lists all the passes needed for the
  8456. compilation of \LangIf{}.
  8457. \section{Challenge: Optimize Blocks and Remove Jumps}
  8458. \label{sec:opt-jumps}
  8459. We discuss two optional challenges that involve optimizing the
  8460. control-flow of the program.
  8461. \subsection{Optimize Blocks}
  8462. The algorithm for \code{explicate\_control} that we discussed in
  8463. Section~\ref{sec:explicate-control-Lif} sometimes generates too many
  8464. blocks. It does so in two different ways.
  8465. %
  8466. First, recall how in Figure~\ref{fig:explicate-control-s1-38},
  8467. \code{block\_4} consists of just a jump to \code{block\_2}. We created
  8468. a new basic block from a single \code{goto} statement, whereas we
  8469. could have simply returned the \code{goto} statement. We can solve
  8470. this problem by modifying the \code{create\_block} function to
  8471. recognize this situation.
  8472. Second, \code{explicate\_control} creates a basic block whenever a
  8473. continuation \emph{might} get used more than once (whenever a
  8474. continuation is passed into two or more recursive calls). However,
  8475. some continuation parameters may not be used at all. For example, consider the
  8476. case for the constant \TRUE{} in \code{explicate\_pred}, where we
  8477. discard the \code{els} branch. So the question is how can we decide
  8478. whether to create a basic block?
  8479. The solution to this conundrum is to use \emph{lazy
  8480. evaluation}\index{subject}{lazy evaluation}~\citep{Friedman:1976aa}
  8481. to delay creating a basic block until the point in time where we know
  8482. it will be used.
  8483. %
  8484. {\if\edition\racketEd
  8485. %
  8486. Racket provides support for
  8487. lazy evaluation with the
  8488. \href{https://docs.racket-lang.org/reference/Delayed_Evaluation.html}{\code{racket/promise}}
  8489. package. The expression \key{(delay} $e_1 \ldots e_n$\key{)}
  8490. \index{subject}{delay} creates a
  8491. \emph{promise}\index{subject}{promise} in which the evaluation of the
  8492. expressions is postponed. When \key{(force}
  8493. $p$\key{)}\index{subject}{force} is applied to a promise $p$ for the
  8494. first time, the expressions $e_1 \ldots e_n$ are evaluated and the
  8495. result of $e_n$ is cached in the promise and returned. If \code{force}
  8496. is applied again to the same promise, then the cached result is
  8497. returned. If \code{force} is applied to an argument that is not a
  8498. promise, \code{force} simply returns the argument.
  8499. %
  8500. \fi}
  8501. %
  8502. {\if\edition\pythonEd
  8503. %
  8504. While Python does not provide direct support for lazy evaluation, it
  8505. is easy to mimic. We can \emph{delay} the evaluation of a computation
  8506. by wrapping it inside a function with no parameters. We can
  8507. \emph{force} its evaluation by calling the function. However, in some
  8508. cases of \code{explicate\_pred}, etc., we will return a list of
  8509. statements and in other cases we will return a function that computes
  8510. a list of statements. We use the term \emph{promise} to refer to a
  8511. value that may be delayed. To uniformly deal with
  8512. promises, we define the following \code{force} function that checks
  8513. whether its input is delayed (i.e., whether it is a function) and then
  8514. either 1) calls the function, or 2) returns the input.
  8515. \begin{lstlisting}
  8516. def force(promise):
  8517. if isinstance(promise, types.FunctionType):
  8518. return promise()
  8519. else:
  8520. return promise
  8521. \end{lstlisting}
  8522. %
  8523. \fi}
  8524. We use promises for the input and output of the functions
  8525. \code{explicate\_pred}, \code{explicate\_assign},
  8526. %
  8527. \racket{ and \code{explicate\_tail}}\python{ \code{explicate\_effect}, and \code{explicate\_stmt}}.
  8528. %
  8529. So instead of taking and returning lists of statments, they take and
  8530. return promises. Furthermore, when we come to a situation in which a
  8531. continuation might be used more than once, as in the case for
  8532. \code{if} in \code{explicate\_pred}, we create a delayed computation
  8533. that creates a basic block for each continuation (if there is not
  8534. already one) and then returns a \code{goto} statement to that basic
  8535. block.
  8536. %
  8537. {\if\edition\racketEd
  8538. %
  8539. The following auxiliary function named \code{create\_block} accomplishes
  8540. this task. It begins with \code{delay} to create a promise. When
  8541. forced, this promise will force the original promise. If that returns
  8542. a \code{goto} (because the block was already added to the control-flow
  8543. graph), then we return the \code{goto}. Otherwise we add the block to
  8544. the control-flow graph with another auxiliary function named
  8545. \code{add-node}. That function returns the label for the new block,
  8546. which we use to create a \code{goto}.
  8547. \begin{lstlisting}
  8548. (define (create_block tail)
  8549. (delay
  8550. (define t (force tail))
  8551. (match t
  8552. [(Goto label) (Goto label)]
  8553. [else (Goto (add-node t))])))
  8554. \end{lstlisting}
  8555. \fi}
  8556. {\if\edition\pythonEd
  8557. %
  8558. Here is the new version of the \code{create\_block} auxiliary function
  8559. that works on promises and that checks whether the block consists of a
  8560. solitary \code{goto} statement.\\
  8561. \begin{minipage}{\textwidth}
  8562. \begin{lstlisting}
  8563. def create_block(promise, basic_blocks):
  8564. stmts = force(promise)
  8565. match stmts:
  8566. case [Goto(l)]:
  8567. return Goto(l)
  8568. case _:
  8569. label = label_name(generate_name('block'))
  8570. basic_blocks[label] = stmts
  8571. return Goto(label)
  8572. \end{lstlisting}
  8573. \end{minipage}
  8574. \fi}
  8575. Figure~\ref{fig:explicate-control-challenge} shows the output of
  8576. \code{explicate\_control} on the example of the nested \code{if}
  8577. expressions with the two improvements discussed above. As you can
  8578. see, the number of basic blocks has been reduced from 10 blocks (see
  8579. Figure~\ref{fig:explicate-control-s1-38}) down to 6 blocks.
  8580. \begin{figure}[tbp]
  8581. {\if\edition\racketEd
  8582. \begin{tabular}{lll}
  8583. \begin{minipage}{0.4\textwidth}
  8584. % cond_test_41.rkt
  8585. \begin{lstlisting}
  8586. (let ([x (read)])
  8587. (let ([y (read)])
  8588. (if (if (< x 1)
  8589. (eq? x 0)
  8590. (eq? x 2))
  8591. (+ y 2)
  8592. (+ y 10))))
  8593. \end{lstlisting}
  8594. \end{minipage}
  8595. &
  8596. $\Rightarrow$
  8597. &
  8598. \begin{minipage}{0.55\textwidth}
  8599. \begin{lstlisting}
  8600. start:
  8601. x = (read);
  8602. y = (read);
  8603. if (< x 1) goto block40;
  8604. else goto block41;
  8605. block40:
  8606. if (eq? x 0) goto block38;
  8607. else goto block39;
  8608. block41:
  8609. if (eq? x 2) goto block38;
  8610. else goto block39;
  8611. block38:
  8612. return (+ y 2);
  8613. block39:
  8614. return (+ y 10);
  8615. \end{lstlisting}
  8616. \end{minipage}
  8617. \end{tabular}
  8618. \fi}
  8619. {\if\edition\pythonEd
  8620. \begin{tabular}{lll}
  8621. \begin{minipage}{0.4\textwidth}
  8622. % cond_test_41.rkt
  8623. \begin{lstlisting}
  8624. x = input_int()
  8625. y = input_int()
  8626. print(y + 2 \
  8627. if (x == 0 \
  8628. if x < 1 \
  8629. else x == 2) \
  8630. else y + 10)
  8631. \end{lstlisting}
  8632. \end{minipage}
  8633. &
  8634. $\Rightarrow$
  8635. &
  8636. \begin{minipage}{0.55\textwidth}
  8637. \begin{lstlisting}
  8638. start:
  8639. x = input_int()
  8640. y = input_int()
  8641. if x < 1:
  8642. goto block_4
  8643. else:
  8644. goto block_5
  8645. block_4:
  8646. if x == 0:
  8647. goto block_2
  8648. else:
  8649. goto block_3
  8650. block_5:
  8651. if x == 2:
  8652. goto block_2
  8653. else:
  8654. goto block_3
  8655. block_2:
  8656. tmp_0 = y + 2
  8657. goto block_1
  8658. block_3:
  8659. tmp_0 = y + 10
  8660. goto block_1
  8661. block_1:
  8662. print(tmp_0)
  8663. return 0
  8664. \end{lstlisting}
  8665. \end{minipage}
  8666. \end{tabular}
  8667. \fi}
  8668. \caption{Translation from \LangIf{} to \LangCIf{}
  8669. via the improved \code{explicate\_control}.}
  8670. \label{fig:explicate-control-challenge}
  8671. \end{figure}
  8672. %% Recall that in the example output of \code{explicate\_control} in
  8673. %% Figure~\ref{fig:explicate-control-s1-38}, \code{block57} through
  8674. %% \code{block60} are trivial blocks, they do nothing but jump to another
  8675. %% block. The first goal of this challenge assignment is to remove those
  8676. %% blocks. Figure~\ref{fig:optimize-jumps} repeats the result of
  8677. %% \code{explicate\_control} on the left and shows the result of bypassing
  8678. %% the trivial blocks on the right. Let us focus on \code{block61}. The
  8679. %% \code{then} branch jumps to \code{block57}, which in turn jumps to
  8680. %% \code{block55}. The optimized code on the right of
  8681. %% Figure~\ref{fig:optimize-jumps} bypasses \code{block57}, with the
  8682. %% \code{then} branch jumping directly to \code{block55}. The story is
  8683. %% similar for the \code{else} branch, as well as for the two branches in
  8684. %% \code{block62}. After the jumps in \code{block61} and \code{block62}
  8685. %% have been optimized in this way, there are no longer any jumps to
  8686. %% blocks \code{block57} through \code{block60}, so they can be removed.
  8687. %% \begin{figure}[tbp]
  8688. %% \begin{tabular}{lll}
  8689. %% \begin{minipage}{0.4\textwidth}
  8690. %% \begin{lstlisting}
  8691. %% block62:
  8692. %% tmp54 = (read);
  8693. %% if (eq? tmp54 2) then
  8694. %% goto block59;
  8695. %% else
  8696. %% goto block60;
  8697. %% block61:
  8698. %% tmp53 = (read);
  8699. %% if (eq? tmp53 0) then
  8700. %% goto block57;
  8701. %% else
  8702. %% goto block58;
  8703. %% block60:
  8704. %% goto block56;
  8705. %% block59:
  8706. %% goto block55;
  8707. %% block58:
  8708. %% goto block56;
  8709. %% block57:
  8710. %% goto block55;
  8711. %% block56:
  8712. %% return (+ 700 77);
  8713. %% block55:
  8714. %% return (+ 10 32);
  8715. %% start:
  8716. %% tmp52 = (read);
  8717. %% if (eq? tmp52 1) then
  8718. %% goto block61;
  8719. %% else
  8720. %% goto block62;
  8721. %% \end{lstlisting}
  8722. %% \end{minipage}
  8723. %% &
  8724. %% $\Rightarrow$
  8725. %% &
  8726. %% \begin{minipage}{0.55\textwidth}
  8727. %% \begin{lstlisting}
  8728. %% block62:
  8729. %% tmp54 = (read);
  8730. %% if (eq? tmp54 2) then
  8731. %% goto block55;
  8732. %% else
  8733. %% goto block56;
  8734. %% block61:
  8735. %% tmp53 = (read);
  8736. %% if (eq? tmp53 0) then
  8737. %% goto block55;
  8738. %% else
  8739. %% goto block56;
  8740. %% block56:
  8741. %% return (+ 700 77);
  8742. %% block55:
  8743. %% return (+ 10 32);
  8744. %% start:
  8745. %% tmp52 = (read);
  8746. %% if (eq? tmp52 1) then
  8747. %% goto block61;
  8748. %% else
  8749. %% goto block62;
  8750. %% \end{lstlisting}
  8751. %% \end{minipage}
  8752. %% \end{tabular}
  8753. %% \caption{Optimize jumps by removing trivial blocks.}
  8754. %% \label{fig:optimize-jumps}
  8755. %% \end{figure}
  8756. %% The name of this pass is \code{optimize-jumps}. We recommend
  8757. %% implementing this pass in two phases. The first phrase builds a hash
  8758. %% table that maps labels to possibly improved labels. The second phase
  8759. %% changes the target of each \code{goto} to use the improved label. If
  8760. %% the label is for a trivial block, then the hash table should map the
  8761. %% label to the first non-trivial block that can be reached from this
  8762. %% label by jumping through trivial blocks. If the label is for a
  8763. %% non-trivial block, then the hash table should map the label to itself;
  8764. %% we do not want to change jumps to non-trivial blocks.
  8765. %% The first phase can be accomplished by constructing an empty hash
  8766. %% table, call it \code{short-cut}, and then iterating over the control
  8767. %% flow graph. Each time you encouter a block that is just a \code{goto},
  8768. %% then update the hash table, mapping the block's source to the target
  8769. %% of the \code{goto}. Also, the hash table may already have mapped some
  8770. %% labels to the block's source, to you must iterate through the hash
  8771. %% table and update all of those so that they instead map to the target
  8772. %% of the \code{goto}.
  8773. %% For the second phase, we recommend iterating through the $\Tail$ of
  8774. %% each block in the program, updating the target of every \code{goto}
  8775. %% according to the mapping in \code{short-cut}.
  8776. \begin{exercise}\normalfont\normalsize
  8777. Implement the improvements to the \code{explicate\_control} pass.
  8778. Check that it removes trivial blocks in a few example programs. Then
  8779. check that your compiler still passes all of your tests.
  8780. \end{exercise}
  8781. \subsection{Remove Jumps}
  8782. There is an opportunity for removing jumps that is apparent in the
  8783. example of Figure~\ref{fig:if-example-x86}. The \code{start} block
  8784. ends with a jump to \code{block7953} and there are no other jumps to
  8785. \code{block7953} in the rest of the program. In this situation we can
  8786. avoid the runtime overhead of this jump by merging \code{block7953}
  8787. into the preceding block, in this case the \code{start} block.
  8788. Figure~\ref{fig:remove-jumps} shows the output of
  8789. \code{select\_instructions} on the left and the result of this
  8790. optimization on the right.
  8791. \begin{figure}[tbp]
  8792. {\if\edition\racketEd
  8793. \begin{tabular}{lll}
  8794. \begin{minipage}{0.5\textwidth}
  8795. % cond_test_20.rkt
  8796. \begin{lstlisting}
  8797. start:
  8798. callq read_int
  8799. movq %rax, tmp7951
  8800. cmpq $1, tmp7951
  8801. je block7952
  8802. jmp block7953
  8803. block7953:
  8804. movq $0, %rax
  8805. jmp conclusion
  8806. block7952:
  8807. movq $42, %rax
  8808. jmp conclusion
  8809. \end{lstlisting}
  8810. \end{minipage}
  8811. &
  8812. $\Rightarrow\qquad$
  8813. \begin{minipage}{0.4\textwidth}
  8814. \begin{lstlisting}
  8815. start:
  8816. callq read_int
  8817. movq %rax, tmp7951
  8818. cmpq $1, tmp7951
  8819. je block7952
  8820. movq $0, %rax
  8821. jmp conclusion
  8822. block7952:
  8823. movq $42, %rax
  8824. jmp conclusion
  8825. \end{lstlisting}
  8826. \end{minipage}
  8827. \end{tabular}
  8828. \fi}
  8829. {\if\edition\pythonEd
  8830. \begin{tabular}{lll}
  8831. \begin{minipage}{0.5\textwidth}
  8832. % cond_test_20.rkt
  8833. \begin{lstlisting}
  8834. start:
  8835. callq read_int
  8836. movq %rax, tmp_0
  8837. cmpq 1, tmp_0
  8838. je block_3
  8839. jmp block_4
  8840. block_3:
  8841. movq 42, tmp_1
  8842. jmp block_2
  8843. block_4:
  8844. movq 0, tmp_1
  8845. jmp block_2
  8846. block_2:
  8847. movq tmp_1, %rdi
  8848. callq print_int
  8849. movq 0, %rax
  8850. jmp conclusion
  8851. \end{lstlisting}
  8852. \end{minipage}
  8853. &
  8854. $\Rightarrow\qquad$
  8855. \begin{minipage}{0.4\textwidth}
  8856. \begin{lstlisting}
  8857. start:
  8858. callq read_int
  8859. movq %rax, tmp_0
  8860. cmpq 1, tmp_0
  8861. je block_3
  8862. movq 0, tmp_1
  8863. jmp block_2
  8864. block_3:
  8865. movq 42, tmp_1
  8866. jmp block_2
  8867. block_2:
  8868. movq tmp_1, %rdi
  8869. callq print_int
  8870. movq 0, %rax
  8871. jmp conclusion
  8872. \end{lstlisting}
  8873. \end{minipage}
  8874. \end{tabular}
  8875. \fi}
  8876. \caption{Merging basic blocks by removing unnecessary jumps.}
  8877. \label{fig:remove-jumps}
  8878. \end{figure}
  8879. \begin{exercise}\normalfont\normalsize
  8880. %
  8881. Implement a pass named \code{remove\_jumps} that merges basic blocks
  8882. into their preceding basic block, when there is only one preceding
  8883. block. The pass should translate from \LangXIfVar{} to \LangXIfVar{}.
  8884. %
  8885. {\if\edition\racketEd
  8886. In the \code{run-tests.rkt} script, add the following entry to the
  8887. list of \code{passes} between \code{allocate\_registers}
  8888. and \code{patch\_instructions}.
  8889. \begin{lstlisting}
  8890. (list "remove-jumps" remove-jumps interp-pseudo-x86-1)
  8891. \end{lstlisting}
  8892. \fi}
  8893. %
  8894. Run the script to test your compiler.
  8895. %
  8896. Check that \code{remove\_jumps} accomplishes the goal of merging basic
  8897. blocks on several test programs.
  8898. \end{exercise}
  8899. \section{Further Reading}
  8900. \label{sec:cond-further-reading}
  8901. The algorithm for the \code{explicate\_control} pass is based on the
  8902. \code{explose-basic-blocks} pass in the course notes of
  8903. \citet{Dybvig:2010aa}.
  8904. %
  8905. It has similarities to the algorithms of \citet{Danvy:2003fk} and
  8906. \citet{Appel:2003fk}, and is related to translations into continuation
  8907. passing
  8908. style~\citep{Wijngaarden:1966,Fischer:1972,reynolds72:_def_interp,Plotkin:1975,Friedman:2001}.
  8909. %
  8910. The treatment of conditionals in the \code{explicate\_control} pass is
  8911. similar to short-cut boolean
  8912. evaluation~\citep{Logothetis:1981,Aho:2006wb,Clarke:1989,Danvy:2003fk}
  8913. and the case-of-case transformation of \citet{PeytonJones:1998}.
  8914. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  8915. \chapter{Loops and Dataflow Analysis}
  8916. \label{ch:Lwhile}
  8917. % TODO: define R'_8
  8918. % TODO: multi-graph
  8919. {\if\edition\racketEd
  8920. %
  8921. In this chapter we study two features that are the hallmarks of
  8922. imperative programming languages: loops and assignments to local
  8923. variables. The following example demonstrates these new features by
  8924. computing the sum of the first five positive integers.
  8925. % similar to loop_test_1.rkt
  8926. \begin{lstlisting}
  8927. (let ([sum 0])
  8928. (let ([i 5])
  8929. (begin
  8930. (while (> i 0)
  8931. (begin
  8932. (set! sum (+ sum i))
  8933. (set! i (- i 1))))
  8934. sum)))
  8935. \end{lstlisting}
  8936. The \code{while} loop consists of a condition and a
  8937. body\footnote{The \code{while} loop in particular is not a built-in
  8938. feature of the Racket language, but Racket includes many looping
  8939. constructs and it is straightforward to define \code{while} as a
  8940. macro.}. The body is evaluated repeatedly so long as the condition
  8941. remains true.
  8942. %
  8943. The \code{set!} consists of a variable and a right-hand-side
  8944. expression. The \code{set!} updates value of the variable to the
  8945. value of the right-hand-side.
  8946. %
  8947. The primary purpose of both the \code{while} loop and \code{set!} is
  8948. to cause side effects, so they do not have a meaningful result
  8949. value. Instead their result is the \code{\#<void>} value. The
  8950. expression \code{(void)} is an explicit way to create the
  8951. \code{\#<void>} value and it has type \code{Void}. The
  8952. \code{\#<void>} value can be passed around just like other values
  8953. inside an \LangLoop{} program and a \code{\#<void>} value can be
  8954. compared for equality with another \code{\#<void>} value. However,
  8955. there are no other operations specific to the the \code{\#<void>}
  8956. value in \LangLoop{}. In contrast, Racket defines the \code{void?}
  8957. predicate that returns \code{\#t} when applied to \code{\#<void>} and
  8958. \code{\#f} otherwise.
  8959. %
  8960. \footnote{Racket's \code{Void} type corresponds to what is called the
  8961. \code{Unit} type in the programming languages literature. Racket's
  8962. \code{Void} type is inhabited by a single value \code{\#<void>}
  8963. which corresponds to \code{unit} or \code{()} in the
  8964. literature~\citep{Pierce:2002hj}.}.
  8965. %
  8966. With the addition of side-effecting features such as \code{while} loop
  8967. and \code{set!}, it is helpful to also include in a language feature
  8968. for sequencing side effects: the \code{begin} expression. It consists
  8969. of one or more subexpressions that are evaluated left-to-right.
  8970. %
  8971. \fi}
  8972. {\if\edition\pythonEd
  8973. %
  8974. In this chapter we study loops, one of the hallmarks of imperative
  8975. programming languages. The following example demonstrates the
  8976. \code{while} loop by computing the sum of the first five positive
  8977. integers.
  8978. \begin{lstlisting}
  8979. sum = 0
  8980. i = 5
  8981. while i > 0:
  8982. sum = sum + i
  8983. i = i - 1
  8984. print(sum)
  8985. \end{lstlisting}
  8986. The \code{while} loop consists of a condition expression and a body (a
  8987. sequence of statements). The body is evaluated repeatedly so long as
  8988. the condition remains true.
  8989. %
  8990. \fi}
  8991. \section{The \LangLoop{} Language}
  8992. \newcommand{\LwhileGrammarRacket}{
  8993. \begin{array}{lcl}
  8994. \Type &::=& \key{Void}\\
  8995. \Exp &::=& \CSETBANG{\Var}{\Exp}
  8996. \MID \CBEGIN{\Exp\ldots}{\Exp}
  8997. \MID \CWHILE{\Exp}{\Exp} \MID \LP\key{void}\RP
  8998. \end{array}
  8999. }
  9000. \newcommand{\LwhileASTRacket}{
  9001. \begin{array}{lcl}
  9002. \Type &::=& \key{Void}\\
  9003. \Exp &::=& \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp}\\
  9004. &\MID& \WHILE{\Exp}{\Exp} \MID \VOID{}
  9005. \end{array}
  9006. }
  9007. \newcommand{\LwhileGrammarPython}{
  9008. \begin{array}{rcl}
  9009. \Stmt &::=& \key{while}~ \Exp \key{:}~ \Stmt^{+}
  9010. \end{array}
  9011. }
  9012. \newcommand{\LwhileASTPython}{
  9013. \begin{array}{lcl}
  9014. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9015. \end{array}
  9016. }
  9017. \begin{figure}[tp]
  9018. \centering
  9019. \fbox{
  9020. \begin{minipage}{0.96\textwidth}
  9021. \small
  9022. {\if\edition\racketEd
  9023. \[
  9024. \begin{array}{l}
  9025. \gray{\LintGrammarRacket{}} \\ \hline
  9026. \gray{\LvarGrammarRacket{}} \\ \hline
  9027. \gray{\LifGrammarRacket{}} \\ \hline
  9028. \LwhileGrammarRacket \\
  9029. \begin{array}{lcl}
  9030. \LangLoopM{} &::=& \Exp
  9031. \end{array}
  9032. \end{array}
  9033. \]
  9034. \fi}
  9035. {\if\edition\pythonEd
  9036. \[
  9037. \begin{array}{l}
  9038. \gray{\LintGrammarPython} \\ \hline
  9039. \gray{\LvarGrammarPython} \\ \hline
  9040. \gray{\LifGrammarPython} \\ \hline
  9041. \LwhileGrammarPython \\
  9042. \begin{array}{rcl}
  9043. \LangLoopM{} &::=& \Stmt^{*}
  9044. \end{array}
  9045. \end{array}
  9046. \]
  9047. \fi}
  9048. \end{minipage}
  9049. }
  9050. \caption{The concrete syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-concrete-syntax}).}
  9051. \label{fig:Lwhile-concrete-syntax}
  9052. \end{figure}
  9053. \begin{figure}[tp]
  9054. \centering
  9055. \fbox{
  9056. \begin{minipage}{0.96\textwidth}
  9057. \small
  9058. {\if\edition\racketEd
  9059. \[
  9060. \begin{array}{l}
  9061. \gray{\LintOpAST} \\ \hline
  9062. \gray{\LvarASTRacket{}} \\ \hline
  9063. \gray{\LifASTRacket{}} \\ \hline
  9064. \LwhileASTRacket{} \\
  9065. \begin{array}{lcl}
  9066. \LangLoopM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9067. \end{array}
  9068. \end{array}
  9069. \]
  9070. \fi}
  9071. {\if\edition\pythonEd
  9072. \[
  9073. \begin{array}{l}
  9074. \gray{\LintASTPython} \\ \hline
  9075. \gray{\LvarASTPython} \\ \hline
  9076. \gray{\LifASTPython} \\ \hline
  9077. \LwhileASTPython \\
  9078. \begin{array}{lcl}
  9079. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  9080. \end{array}
  9081. \end{array}
  9082. \]
  9083. \fi}
  9084. \end{minipage}
  9085. }
  9086. \caption{The abstract syntax of \LangLoop{}, extending \LangIf{} (Figure~\ref{fig:Lif-syntax}).}
  9087. \label{fig:Lwhile-syntax}
  9088. \end{figure}
  9089. The concrete syntax of \LangLoop{} is defined in
  9090. Figure~\ref{fig:Lwhile-concrete-syntax} and its abstract syntax is defined
  9091. in Figure~\ref{fig:Lwhile-syntax}.
  9092. %
  9093. The definitional interpreter for \LangLoop{} is shown in
  9094. Figure~\ref{fig:interp-Rwhile}.
  9095. %
  9096. {\if\edition\racketEd
  9097. %
  9098. We add new cases for \code{SetBang}, \code{WhileLoop}, \code{Begin},
  9099. and \code{Void} and we make changes to the cases for \code{Var} and
  9100. \code{Let} regarding variables. To support assignment to variables and
  9101. to make their lifetimes indefinite (see the second example in
  9102. Section~\ref{sec:assignment-scoping}), we box the value that is bound
  9103. to each variable (in \code{Let}). The case for \code{Var} unboxes the
  9104. value.
  9105. %
  9106. Now to discuss the new cases. For \code{SetBang}, we lookup the
  9107. variable in the environment to obtain a boxed value and then we change
  9108. it using \code{set-box!} to the result of evaluating the right-hand
  9109. side. The result value of a \code{SetBang} is \code{void}.
  9110. %
  9111. For the \code{WhileLoop}, we repeatedly 1) evaluate the condition, and
  9112. if the result is true, 2) evaluate the body.
  9113. The result value of a \code{while} loop is also \code{void}.
  9114. %
  9115. The $\BEGIN{\itm{es}}{\itm{body}}$ expression evaluates the
  9116. subexpressions \itm{es} for their effects and then evaluates
  9117. and returns the result from \itm{body}.
  9118. %
  9119. The $\VOID{}$ expression produces the \code{void} value.
  9120. %
  9121. \fi}
  9122. {\if\edition\pythonEd
  9123. %
  9124. We add a new case for \code{While} in the \code{interp\_stmts}
  9125. function, where we repeatedly interpret the \code{body} so long as the
  9126. \code{test} expression remains true.
  9127. %
  9128. \fi}
  9129. \begin{figure}[tbp]
  9130. {\if\edition\racketEd
  9131. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9132. (define interp-Rwhile_class
  9133. (class interp-Rany_class
  9134. (super-new)
  9135. (define/override ((interp-exp env) e)
  9136. (define recur (interp-exp env))
  9137. (match e
  9138. [(SetBang x rhs)
  9139. (set-box! (lookup x env) (recur rhs))]
  9140. [(WhileLoop cnd body)
  9141. (define (loop)
  9142. (cond [(recur cnd) (recur body) (loop)]
  9143. [else (void)]))
  9144. (loop)]
  9145. [(Begin es body)
  9146. (for ([e es]) (recur e))
  9147. (recur body)]
  9148. [(Void) (void)]
  9149. [else ((super interp-exp env) e)]))
  9150. ))
  9151. (define (interp-Rwhile p)
  9152. (send (new interp-Rwhile_class) interp-program p))
  9153. \end{lstlisting}
  9154. \fi}
  9155. {\if\edition\pythonEd
  9156. \begin{lstlisting}
  9157. class InterpLwhile(InterpLif):
  9158. def interp_stmts(self, ss, env):
  9159. if len(ss) == 0:
  9160. return
  9161. match ss[0]:
  9162. case While(test, body, []):
  9163. while self.interp_exp(test, env):
  9164. self.interp_stmts(body, env)
  9165. return self.interp_stmts(ss[1:], env)
  9166. case _:
  9167. return super().interp_stmts(ss, env)
  9168. \end{lstlisting}
  9169. \fi}
  9170. \caption{Interpreter for \LangLoop{}.}
  9171. \label{fig:interp-Rwhile}
  9172. \end{figure}
  9173. The type checker for \LangLoop{} is defined in
  9174. Figure~\ref{fig:type-check-Rwhile}.
  9175. %
  9176. {\if\edition\racketEd
  9177. %
  9178. For \LangLoop{} we add a type named \code{Void} and the only value of
  9179. this type is the \code{void} value.
  9180. %
  9181. The type checking of the \code{SetBang} expression requires the type of
  9182. the variable and the right-hand-side to agree. The result type is
  9183. \code{Void}. For \code{while}, the condition must be a
  9184. \code{Boolean}. The result type is also \code{Void}. For
  9185. \code{Begin}, the result type is the type of its last subexpression.
  9186. %
  9187. \fi}
  9188. %
  9189. {\if\edition\pythonEd
  9190. %
  9191. A \code{while} loop is well typed if the type of the \code{test}
  9192. expression is \code{bool} and the statements in the \code{body} are
  9193. well typed.
  9194. %
  9195. \fi}
  9196. \begin{figure}[tbp]
  9197. {\if\edition\racketEd
  9198. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  9199. (define type-check-Rwhile_class
  9200. (class type-check-Rany_class
  9201. (super-new)
  9202. (inherit check-type-equal?)
  9203. (define/override (type-check-exp env)
  9204. (lambda (e)
  9205. (define recur (type-check-exp env))
  9206. (match e
  9207. [(SetBang x rhs)
  9208. (define-values (rhs^ rhsT) (recur rhs))
  9209. (define varT (dict-ref env x))
  9210. (check-type-equal? rhsT varT e)
  9211. (values (SetBang x rhs^) 'Void)]
  9212. [(WhileLoop cnd body)
  9213. (define-values (cnd^ Tc) (recur cnd))
  9214. (check-type-equal? Tc 'Boolean e)
  9215. (define-values (body^ Tbody) ((type-check-exp env) body))
  9216. (values (WhileLoop cnd^ body^) 'Void)]
  9217. [(Begin es body)
  9218. (define-values (es^ ts)
  9219. (for/lists (l1 l2) ([e es]) (recur e)))
  9220. (define-values (body^ Tbody) (recur body))
  9221. (values (Begin es^ body^) Tbody)]
  9222. [else ((super type-check-exp env) e)])))
  9223. ))
  9224. (define (type-check-Rwhile p)
  9225. (send (new type-check-Rwhile_class) type-check-program p))
  9226. \end{lstlisting}
  9227. \fi}
  9228. {\if\edition\pythonEd
  9229. \begin{lstlisting}
  9230. class TypeCheckLwhile(TypeCheckLif):
  9231. def type_check_stmts(self, ss, env):
  9232. if len(ss) == 0:
  9233. return
  9234. match ss[0]:
  9235. case While(test, body, []):
  9236. test_t = self.type_check_exp(test, env)
  9237. check_type_equal(bool, test_t, test)
  9238. body_t = self.type_check_stmts(body, env)
  9239. return self.type_check_stmts(ss[1:], env)
  9240. case _:
  9241. return super().type_check_stmts(ss, env)
  9242. \end{lstlisting}
  9243. \fi}
  9244. \caption{Type checker for the \LangLoop{} language.}
  9245. \label{fig:type-check-Rwhile}
  9246. \end{figure}
  9247. {\if\edition\racketEd
  9248. %
  9249. At first glance, the translation of these language features to x86
  9250. seems straightforward because the \LangCIf{} intermediate language
  9251. already supports all of the ingredients that we need: assignment,
  9252. \code{goto}, conditional branching, and sequencing. However, there are
  9253. complications that arise which we discuss in the next section. After
  9254. that we introduce the changes necessary to the existing passes.
  9255. %
  9256. \fi}
  9257. {\if\edition\pythonEd
  9258. %
  9259. At first glance, the translation of \code{while} loops to x86 seems
  9260. straightforward because the \LangCIf{} intermediate language already
  9261. supports \code{goto} and conditional branching. However, there are
  9262. complications that arise which we discuss in the next section. After
  9263. that we introduce the changes necessary to the existing passes.
  9264. %
  9265. \fi}
  9266. \section{Cyclic Control Flow and Dataflow Analysis}
  9267. \label{sec:dataflow-analysis}
  9268. Up until this point the control-flow graphs of the programs generated
  9269. in \code{explicate\_control} were guaranteed to be acyclic. However,
  9270. each \code{while} loop introduces a cycle in the control-flow graph.
  9271. But does that matter?
  9272. %
  9273. Indeed it does. Recall that for register allocation, the compiler
  9274. performs liveness analysis to determine which variables can share the
  9275. same register. To accomplish this we analyzed the control-flow graph
  9276. in reverse topological order
  9277. (Section~\ref{sec:liveness-analysis-Lif}), but topological order is
  9278. only well-defined for acyclic graphs.
  9279. Let us return to the example of computing the sum of the first five
  9280. positive integers. Here is the program after instruction selection but
  9281. before register allocation.
  9282. \begin{center}
  9283. {\if\edition\racketEd
  9284. \begin{minipage}{0.45\textwidth}
  9285. \begin{lstlisting}
  9286. (define (main) : Integer
  9287. mainstart:
  9288. movq $0, sum
  9289. movq $5, i
  9290. jmp block5
  9291. block5:
  9292. movq i, tmp3
  9293. cmpq tmp3, $0
  9294. jl block7
  9295. jmp block8
  9296. \end{lstlisting}
  9297. \end{minipage}
  9298. \begin{minipage}{0.45\textwidth}
  9299. \begin{lstlisting}
  9300. block7:
  9301. addq i, sum
  9302. movq $1, tmp4
  9303. negq tmp4
  9304. addq tmp4, i
  9305. jmp block5
  9306. block8:
  9307. movq $27, %rax
  9308. addq sum, %rax
  9309. jmp mainconclusion
  9310. )
  9311. \end{lstlisting}
  9312. \end{minipage}
  9313. \fi}
  9314. {\if\edition\pythonEd
  9315. \begin{minipage}{0.45\textwidth}
  9316. \begin{lstlisting}
  9317. mainstart:
  9318. movq $0, sum
  9319. movq $5, i
  9320. jmp block5
  9321. block5:
  9322. cmpq $0, i
  9323. jg block7
  9324. jmp block8
  9325. \end{lstlisting}
  9326. \end{minipage}
  9327. \begin{minipage}{0.45\textwidth}
  9328. \begin{lstlisting}
  9329. block7:
  9330. addq i, sum
  9331. subq $1, i
  9332. jmp block5
  9333. block8:
  9334. movq sum, %rdi
  9335. callq print_int
  9336. movq $0, %rax
  9337. jmp mainconclusion
  9338. \end{lstlisting}
  9339. \end{minipage}
  9340. \fi}
  9341. \end{center}
  9342. Recall that liveness analysis works backwards, starting at the end
  9343. of each function. For this example we could start with \code{block8}
  9344. because we know what is live at the beginning of the conclusion,
  9345. just \code{rax} and \code{rsp}. So the live-before set
  9346. for \code{block8} is $\{\ttm{rsp},\ttm{sum}\}$.
  9347. %
  9348. Next we might try to analyze \code{block5} or \code{block7}, but
  9349. \code{block5} jumps to \code{block7} and vice versa, so it seems that
  9350. we are stuck.
  9351. The way out of this impasse is to realize that we can compute an
  9352. under-approximation of the live-before set by starting with empty
  9353. live-after sets. By \emph{under-approximation}, we mean that the set
  9354. only contains variables that are live for some execution of the
  9355. program, but the set may be missing some variables. Next, the
  9356. under-approximations for each block can be improved by 1) updating the
  9357. live-after set for each block using the approximate live-before sets
  9358. from the other blocks and 2) perform liveness analysis again on each
  9359. block. In fact, by iterating this process, the under-approximations
  9360. eventually become the correct solutions!
  9361. %
  9362. This approach of iteratively analyzing a control-flow graph is
  9363. applicable to many static analysis problems and goes by the name
  9364. \emph{dataflow analysis}\index{subject}{dataflow analysis}. It was invented by
  9365. \citet{Kildall:1973vn} in his Ph.D. thesis at the University of
  9366. Washington.
  9367. Let us apply this approach to the above example. We use the empty set
  9368. for the initial live-before set for each block. Let $m_0$ be the
  9369. following mapping from label names to sets of locations (variables and
  9370. registers).
  9371. \begin{center}
  9372. \begin{lstlisting}
  9373. mainstart: {}, block5: {}, block7: {}, block8: {}
  9374. \end{lstlisting}
  9375. \end{center}
  9376. Using the above live-before approximations, we determine the
  9377. live-after for each block and then apply liveness analysis to each
  9378. block. This produces our next approximation $m_1$ of the live-before
  9379. sets.
  9380. \begin{center}
  9381. \begin{lstlisting}
  9382. mainstart: {}, block5: {i}, block7: {i, sum}, block8: {rsp, sum}
  9383. \end{lstlisting}
  9384. \end{center}
  9385. For the second round, the live-after for \code{mainstart} is the
  9386. current live-before for \code{block5}, which is \code{\{i\}}. So the
  9387. liveness analysis for \code{mainstart} computes the empty set. The
  9388. live-after for \code{block5} is the union of the live-before sets for
  9389. \code{block7} and \code{block8}, which is \code{\{i , rsp, sum\}}.
  9390. So the liveness analysis for \code{block5} computes \code{\{i , rsp,
  9391. sum\}}. The live-after for \code{block7} is the live-before for
  9392. \code{block5} (from the previous iteration), which is \code{\{i\}}.
  9393. So the liveness analysis for \code{block7} remains \code{\{i,
  9394. sum\}}. Together these yield the following approximation $m_2$ of
  9395. the live-before sets.
  9396. \begin{center}
  9397. \begin{lstlisting}
  9398. mainstart: {}, block5: {i, rsp, sum}, block7: {i, sum}, block8: {rsp, sum}
  9399. \end{lstlisting}
  9400. \end{center}
  9401. In the preceding iteration, only \code{block5} changed, so we can
  9402. limit our attention to \code{mainstart} and \code{block7}, the two
  9403. blocks that jump to \code{block5}. As a result, the live-before sets
  9404. for \code{mainstart} and \code{block7} are updated to include
  9405. \code{rsp}, yielding the following approximation $m_3$.
  9406. \begin{center}
  9407. \begin{lstlisting}
  9408. mainstart: {rsp}, block5: {i,rsp,sum}, block7: {i,rsp,sum}, block8: {rsp,sum}
  9409. \end{lstlisting}
  9410. \end{center}
  9411. Because \code{block7} changed, we analyze \code{block5} once more, but
  9412. its live-before set remains \code{\{i,rsp,sum\}}. At this point
  9413. our approximations have converged, so $m_3$ is the solution.
  9414. This iteration process is guaranteed to converge to a solution by the
  9415. Kleene Fixed-Point Theorem, a general theorem about functions on
  9416. lattices~\citep{Kleene:1952aa}. Roughly speaking, a \emph{lattice} is
  9417. any collection that comes with a partial ordering $\sqsubseteq$ on its
  9418. elements, a least element $\bot$ (pronounced bottom), and a join
  9419. operator $\sqcup$.\index{subject}{lattice}\index{subject}{bottom}\index{subject}{partial
  9420. ordering}\index{subject}{join}\footnote{Technically speaking, we will be
  9421. working with join semi-lattices.} When two elements are ordered $m_i
  9422. \sqsubseteq m_j$, it means that $m_j$ contains at least as much
  9423. information as $m_i$, so we can think of $m_j$ as a better-or-equal
  9424. approximation than $m_i$. The bottom element $\bot$ represents the
  9425. complete lack of information, i.e., the worst approximation. The join
  9426. operator takes two lattice elements and combines their information,
  9427. i.e., it produces the least upper bound of the two.\index{subject}{least upper
  9428. bound}
  9429. A dataflow analysis typically involves two lattices: one lattice to
  9430. represent abstract states and another lattice that aggregates the
  9431. abstract states of all the blocks in the control-flow graph. For
  9432. liveness analysis, an abstract state is a set of locations. We form
  9433. the lattice $L$ by taking its elements to be sets of locations, the
  9434. ordering to be set inclusion ($\subseteq$), the bottom to be the empty
  9435. set, and the join operator to be set union.
  9436. %
  9437. We form a second lattice $M$ by taking its elements to be mappings
  9438. from the block labels to sets of locations (elements of $L$). We
  9439. order the mappings point-wise, using the ordering of $L$. So given any
  9440. two mappings $m_i$ and $m_j$, $m_i \sqsubseteq_M m_j$ when $m_i(\ell)
  9441. \subseteq m_j(\ell)$ for every block label $\ell$ in the program. The
  9442. bottom element of $M$ is the mapping $\bot_M$ that sends every label
  9443. to the empty set, i.e., $\bot_M(\ell) = \emptyset$.
  9444. We can think of one iteration of liveness analysis applied to the
  9445. whole program as being a function $f$ on the lattice $M$. It takes a
  9446. mapping as input and computes a new mapping.
  9447. \[
  9448. f(m_i) = m_{i+1}
  9449. \]
  9450. Next let us think for a moment about what a final solution $m_s$
  9451. should look like. If we perform liveness analysis using the solution
  9452. $m_s$ as input, we should get $m_s$ again as the output. That is, the
  9453. solution should be a \emph{fixed point} of the function $f$.\index{subject}{fixed point}
  9454. \[
  9455. f(m_s) = m_s
  9456. \]
  9457. Furthermore, the solution should only include locations that are
  9458. forced to be there by performing liveness analysis on the program, so
  9459. the solution should be the \emph{least} fixed point.\index{subject}{least fixed point}
  9460. The Kleene Fixed-Point Theorem states that if a function $f$ is
  9461. monotone (better inputs produce better outputs), then the least fixed
  9462. point of $f$ is the least upper bound of the \emph{ascending Kleene
  9463. chain} obtained by starting at $\bot$ and iterating $f$ as
  9464. follows.\index{subject}{Kleene Fixed-Point Theorem}
  9465. \[
  9466. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9467. \sqsubseteq f^n(\bot) \sqsubseteq \cdots
  9468. \]
  9469. When a lattice contains only finitely-long ascending chains, then
  9470. every Kleene chain tops out at some fixed point after some number of
  9471. iterations of $f$.
  9472. \[
  9473. \bot \sqsubseteq f(\bot) \sqsubseteq f(f(\bot)) \sqsubseteq \cdots
  9474. \sqsubseteq f^k(\bot) = f^{k+1}(\bot) = m_s
  9475. \]
  9476. The liveness analysis is indeed a monotone function and the lattice
  9477. $M$ only has finitely-long ascending chains because there are only a
  9478. finite number of variables and blocks in the program. Thus we are
  9479. guaranteed that iteratively applying liveness analysis to all blocks
  9480. in the program will eventually produce the least fixed point solution.
  9481. Next let us consider dataflow analysis in general and discuss the
  9482. generic work list algorithm (Figure~\ref{fig:generic-dataflow}).
  9483. %
  9484. The algorithm has four parameters: the control-flow graph \code{G}, a
  9485. function \code{transfer} that applies the analysis to one block, the
  9486. \code{bottom} and \code{join} operator for the lattice of abstract
  9487. states. The \code{analyze\_dataflow} function is formulated as a
  9488. \emph{forward} dataflow analysis, that is, the inputs to the transfer
  9489. function come from the predecessor nodes in the control-flow
  9490. graph. However, liveness analysis is a \emph{backward} dataflow
  9491. analysis, so in that case one must supply the \code{analyze\_dataflow}
  9492. function with the transpose of the control-flow graph.
  9493. The algorithm begins by creating the bottom mapping, represented by a
  9494. hash table. It then pushes all of the nodes in the control-flow graph
  9495. onto the work list (a queue). The algorithm repeats the \code{while}
  9496. loop as long as there are items in the work list. In each iteration, a
  9497. node is popped from the work list and processed. The \code{input} for
  9498. the node is computed by taking the join of the abstract states of all
  9499. the predecessor nodes. The \code{transfer} function is then applied to
  9500. obtain the \code{output} abstract state. If the output differs from
  9501. the previous state for this block, the mapping for this block is
  9502. updated and its successor nodes are pushed onto the work list.
  9503. \begin{figure}[tb]
  9504. {\if\edition\racketEd
  9505. \begin{lstlisting}
  9506. (define (analyze_dataflow G transfer bottom join)
  9507. (define mapping (make-hash))
  9508. (for ([v (in-vertices G)])
  9509. (dict-set! mapping v bottom))
  9510. (define worklist (make-queue))
  9511. (for ([v (in-vertices G)])
  9512. (enqueue! worklist v))
  9513. (define trans-G (transpose G))
  9514. (while (not (queue-empty? worklist))
  9515. (define node (dequeue! worklist))
  9516. (define input (for/fold ([state bottom])
  9517. ([pred (in-neighbors trans-G node)])
  9518. (join state (dict-ref mapping pred))))
  9519. (define output (transfer node input))
  9520. (cond [(not (equal? output (dict-ref mapping node)))
  9521. (dict-set! mapping node output)
  9522. (for ([v (in-neighbors G node)])
  9523. (enqueue! worklist v))]))
  9524. mapping)
  9525. \end{lstlisting}
  9526. \fi}
  9527. {\if\edition\pythonEd
  9528. \begin{lstlisting}
  9529. def analyze_dataflow(G, transfer, bottom, join):
  9530. trans_G = transpose(G)
  9531. mapping = dict((v, bottom) for v in G.vertices())
  9532. worklist = deque(G.vertices)
  9533. while worklist:
  9534. node = worklist.pop()
  9535. input = reduce(join, [mapping[v] for v in trans_G.adjacent(node)], bottom)
  9536. output = transfer(node, input)
  9537. if output != mapping[node]:
  9538. mapping[node] = output
  9539. worklist.extend(G.adjacent(node))
  9540. \end{lstlisting}
  9541. \fi}
  9542. \caption{Generic work list algorithm for dataflow analysis}
  9543. \label{fig:generic-dataflow}
  9544. \end{figure}
  9545. {\if\edition\racketEd
  9546. \section{Mutable Variables \& Remove Complex Operands}
  9547. There is a subtle interaction between the addition of \code{set!}, the
  9548. \code{remove\_complex\_operands} pass, and the left-to-right order of
  9549. evaluation of Racket. Consider the following example.
  9550. \begin{lstlisting}
  9551. (let ([x 2])
  9552. (+ x (begin (set! x 40) x)))
  9553. \end{lstlisting}
  9554. The result of this program is \code{42} because the first read from
  9555. \code{x} produces \code{2} and the second produces \code{40}. However,
  9556. if we naively apply the \code{remove\_complex\_operands} pass to this
  9557. example we obtain the following program whose result is \code{80}!
  9558. \begin{lstlisting}
  9559. (let ([x 2])
  9560. (let ([tmp (begin (set! x 40) x)])
  9561. (+ x tmp)))
  9562. \end{lstlisting}
  9563. The problem is that, with mutable variables, the ordering between
  9564. reads and writes is important, and the
  9565. \code{remove\_complex\_operands} pass moved the \code{set!} to happen
  9566. before the first read of \code{x}.
  9567. We recommend solving this problem by giving special treatment to reads
  9568. from mutable variables, that is, variables that occur on the left-hand
  9569. side of a \code{set!}. We mark each read from a mutable variable with
  9570. the form \code{get!} (\code{GetBang} in abstract syntax) to indicate
  9571. that the read operation is effectful in that it can produce different
  9572. results at different points in time. Let's apply this idea to the
  9573. following variation that also involves a variable that is not mutated.
  9574. % loop_test_24.rkt
  9575. \begin{lstlisting}
  9576. (let ([x 2])
  9577. (let ([y 0])
  9578. (+ y (+ x (begin (set! x 40) x)))))
  9579. \end{lstlisting}
  9580. We analyze the above program to discover that variable \code{x} is
  9581. mutable but \code{y} is not. We then transform the program as follows,
  9582. replacing each occurence of \code{x} with \code{(get! x)}.
  9583. \begin{lstlisting}
  9584. (let ([x 2])
  9585. (let ([y 0])
  9586. (+ y (+ (get! x) (begin (set! x 40) (get! x))))))
  9587. \end{lstlisting}
  9588. Now that we have a clear distinction between reads from mutable and
  9589. immutable variables, we can apply the \code{remove\_complex\_operands}
  9590. pass, where reads from immutable variables are still classified as
  9591. atomic expressions but reads from mutable variables are classified as
  9592. complex. Thus, \code{remove\_complex\_operands} yields the following
  9593. program.
  9594. \begin{lstlisting}
  9595. (let ([x 2])
  9596. (let ([y 0])
  9597. (+ y (let ([t1 (get! x)])
  9598. (let ([t2 (begin (set! x 40) (get! x))])
  9599. (+ t1 t2))))))
  9600. \end{lstlisting}
  9601. The temporary variable \code{t1} gets the value of \code{x} before the
  9602. \code{set!}, so it is \code{2}. The temporary variable \code{t2} gets
  9603. the value of \code{x} after the \code{set!}, so it is \code{40}. We
  9604. do not generate a temporary variable for the occurence of \code{y}
  9605. because it's an immutable variable. We want to avoid such unnecessary
  9606. extra temporaries because they would needless increase the number of
  9607. variables, making it more likely for some of them to be spilled. The
  9608. result of this program is \code{42}, the same as the result prior to
  9609. \code{remove\_complex\_operands}.
  9610. The approach that we've sketched above requires only a small
  9611. modification to \code{remove\_complex\_operands} to handle
  9612. \code{get!}. However, it requires a new pass, called
  9613. \code{uncover-get!}, that we discuss in
  9614. Section~\ref{sec:uncover-get-bang}.
  9615. As an aside, this problematic interaction between \code{set!} and the
  9616. pass \code{remove\_complex\_operands} is particular to Racket and not
  9617. its predecessor, the Scheme language. The key difference is that
  9618. Scheme does not specify an order of evaluation for the arguments of an
  9619. operator or function call~\citep{SPERBER:2009aa}. Thus, a compiler for
  9620. Scheme is free to choose any ordering: both \code{42} and \code{80}
  9621. would be correct results for the example program. Interestingly,
  9622. Racket is implemented on top of the Chez Scheme
  9623. compiler~\citep{Dybvig:2006aa} and an approach similar to the one
  9624. presented in this section (using extra \code{let} bindings to control
  9625. the order of evaluation) is used in the translation from Racket to
  9626. Scheme~\citep{Flatt:2019tb}.
  9627. \fi} % racket
  9628. Having discussed the complications that arise from adding support for
  9629. assignment and loops, we turn to discussing the individual compilation
  9630. passes.
  9631. {\if\edition\racketEd
  9632. \section{Uncover \texttt{get!}}
  9633. \label{sec:uncover-get-bang}
  9634. The goal of this pass it to mark uses of mutable variables so that
  9635. \code{remove\_complex\_operands} can treat them as complex expressions
  9636. and thereby preserve their ordering relative to the side-effects in
  9637. other operands. So the first step is to collect all the mutable
  9638. variables. We recommend creating an auxilliary function for this,
  9639. named \code{collect-set!}, that recursively traverses expressions,
  9640. returning a set of all variables that occur on the left-hand side of a
  9641. \code{set!}. Here's an exerpt of its implementation.
  9642. \begin{center}
  9643. \begin{minipage}{\textwidth}
  9644. \begin{lstlisting}
  9645. (define (collect-set! e)
  9646. (match e
  9647. [(Var x) (set)]
  9648. [(Int n) (set)]
  9649. [(Let x rhs body)
  9650. (set-union (collect-set! rhs) (collect-set! body))]
  9651. [(SetBang var rhs)
  9652. (set-union (set var) (collect-set! rhs))]
  9653. ...))
  9654. \end{lstlisting}
  9655. \end{minipage}
  9656. \end{center}
  9657. By placing this pass after \code{uniquify}, we need not worry about
  9658. variable shadowing and our logic for \code{let} can remain simple, as
  9659. in the exerpt above.
  9660. The second step is to mark the occurences of the mutable variables
  9661. with the new \code{GetBang} AST node (\code{get!} in concrete
  9662. syntax). The following is an exerpt of the \code{uncover-get!-exp}
  9663. function, which takes two parameters: the set of mutable varaibles
  9664. \code{set!-vars}, and the expression \code{e} to be processed. The
  9665. case for \code{(Var x)} replaces it with \code{(GetBang x)} if it is a
  9666. mutable variable or leaves it alone if not.
  9667. \begin{center}
  9668. \begin{minipage}{\textwidth}
  9669. \begin{lstlisting}
  9670. (define ((uncover-get!-exp set!-vars) e)
  9671. (match e
  9672. [(Var x)
  9673. (if (set-member? set!-vars x)
  9674. (GetBang x)
  9675. (Var x))]
  9676. ...))
  9677. \end{lstlisting}
  9678. \end{minipage}
  9679. \end{center}
  9680. To wrap things up, define the \code{uncover-get!} function for
  9681. processing a whole program, using \code{collect-set!} to obtain the
  9682. set of mutable variables and then \code{uncover-get!-exp} to replace
  9683. their occurences with \code{GetBang}.
  9684. \fi}
  9685. \section{Remove Complex Operands}
  9686. \label{sec:rco-loop}
  9687. {\if\edition\racketEd
  9688. %
  9689. The new language forms, \code{get!}, \code{set!}, \code{begin}, and
  9690. \code{while} are all complex expressions. The subexpressions of
  9691. \code{set!}, \code{begin}, and \code{while} are allowed to be complex.
  9692. %
  9693. \fi}
  9694. {\if\edition\pythonEd
  9695. %
  9696. The change needed for this pass is to add a case for the \code{while}
  9697. statement. The condition of a \code{while} loop is allowed to be a
  9698. complex expression, just like the condition of the \code{if}
  9699. statement.
  9700. %
  9701. \fi}
  9702. %
  9703. Figure~\ref{fig:Rwhile-anf-syntax} defines the output language
  9704. \LangLoopANF{} of this pass.
  9705. \newcommand{\LwhileMonadASTPython}{
  9706. \begin{array}{rcl}
  9707. \Stmt{} &::=& \WHILESTMT{\Exp}{\Stmt^{+}}
  9708. \end{array}
  9709. }
  9710. \begin{figure}[tp]
  9711. \centering
  9712. \fbox{
  9713. \begin{minipage}{0.96\textwidth}
  9714. \small
  9715. {\if\edition\racketEd
  9716. \[
  9717. \begin{array}{rcl}
  9718. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} } \MID \VOID{} \\
  9719. \Exp &::=& \ldots \MID \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  9720. &\MID& \GETBANG{\Var}
  9721. \MID \SETBANG{\Var}{\Exp} \\
  9722. &\MID& \BEGIN{\LP\Exp\ldots\RP}{\Exp}
  9723. \MID \WHILE{\Exp}{\Exp} \\
  9724. \LangLoopANF &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  9725. \end{array}
  9726. \]
  9727. \fi}
  9728. {\if\edition\pythonEd
  9729. \[
  9730. \begin{array}{l}
  9731. \gray{\LvarMonadASTPython} \\ \hline
  9732. \gray{\LifMonadASTPython} \\ \hline
  9733. \LwhileMonadASTPython \\
  9734. \begin{array}{rcl}
  9735. \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9736. \end{array}
  9737. \end{array}
  9738. %% \begin{array}{rcl}
  9739. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}\\
  9740. %% \Exp &::=& \Atm \MID \READ{} \\
  9741. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm} \MID \UNIOP{\itm{unaryop}}{\Atm} \\
  9742. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} \\
  9743. %% % &\MID& \LET{\Var}{\Exp}{\Exp}\\ % Why?
  9744. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  9745. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \MID \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  9746. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}} \\
  9747. %% \LangLoopANF &::=& \PROGRAM{\code{()}}{\Stmt^{*}}
  9748. %% \end{array}
  9749. \]
  9750. \fi}
  9751. \end{minipage}
  9752. }
  9753. \caption{\LangLoopANF{} is \LangLoop{} in monadic normal form.}
  9754. \label{fig:Rwhile-anf-syntax}
  9755. \end{figure}
  9756. {\if\edition\racketEd
  9757. As usual, when a complex expression appears in a grammar position that
  9758. needs to be atomic, such as the argument of a primitive operator, we
  9759. must introduce a temporary variable and bind it to the complex
  9760. expression. This approach applies, unchanged, to handle the new
  9761. language forms. For example, in the following code there are two
  9762. \code{begin} expressions appearing as arguments to \code{+}. The
  9763. output of \code{rco\_exp} is shown below, in which the \code{begin}
  9764. expressions have been bound to temporary variables. Recall that
  9765. \code{let} expressions in \LangLoopANF{} are allowed to have
  9766. arbitrary expressions in their right-hand-side expression, so it is
  9767. fine to place \code{begin} there.
  9768. \begin{center}
  9769. \begin{minipage}{\textwidth}
  9770. \begin{lstlisting}
  9771. (let ([x0 10])
  9772. (let ([y1 0])
  9773. (+ (+ (begin (set! y1 (read)) x0)
  9774. (begin (set! x0 (read)) y1))
  9775. x0)))
  9776. |$\Rightarrow$|
  9777. (let ([x0 10])
  9778. (let ([y1 0])
  9779. (let ([tmp2 (begin (set! y1 (read)) x0)])
  9780. (let ([tmp3 (begin (set! x0 (read)) y1)])
  9781. (let ([tmp4 (+ tmp2 tmp3)])
  9782. (+ tmp4 x0))))))
  9783. \end{lstlisting}
  9784. \end{minipage}
  9785. \end{center}
  9786. \fi}
  9787. \section{Explicate Control \racket{and \LangCLoop{}}}
  9788. \label{sec:explicate-loop}
  9789. \newcommand{\CloopASTRacket}{
  9790. \begin{array}{lcl}
  9791. \Atm &::=& \VOID \\
  9792. \Stmt &::=& \READ{}
  9793. \end{array}
  9794. }
  9795. {\if\edition\racketEd
  9796. Recall that in the \code{explicate\_control} pass we define one helper
  9797. function for each kind of position in the program. For the \LangVar{}
  9798. language of integers and variables we needed kinds of positions:
  9799. assignment and tail. The \code{if} expressions of \LangIf{} introduced
  9800. predicate positions. For \LangLoop{}, the \code{begin} expression introduces
  9801. yet another kind of position: effect position. Except for the last
  9802. subexpression, the subexpressions inside a \code{begin} are evaluated
  9803. only for their effect. Their result values are discarded. We can
  9804. generate better code by taking this fact into account.
  9805. The output language of \code{explicate\_control} is \LangCLoop{}
  9806. (Figure~\ref{fig:c7-syntax}), which is nearly identical to
  9807. \LangCIf{}. The only syntactic difference is that \code{read} may also
  9808. appear as a statement. The most significant difference between the
  9809. programs generated by \code{explicate\_control} in
  9810. Chapter~\ref{ch:Lif} versus \code{explicate\_control} in this chapter
  9811. is that the control-flow graphs of the later may contain cycles.
  9812. \begin{figure}[tp]
  9813. \fbox{
  9814. \begin{minipage}{0.96\textwidth}
  9815. \small
  9816. \[
  9817. \begin{array}{l}
  9818. \gray{\CvarASTRacket} \\ \hline
  9819. \gray{\CifASTRacket} \\ \hline
  9820. \CloopASTRacket \\
  9821. \begin{array}{lcl}
  9822. \LangCLoopM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  9823. \end{array}
  9824. \end{array}
  9825. \]
  9826. \end{minipage}
  9827. }
  9828. \caption{The abstract syntax of \LangCLoop{}, extending \LangCIf{} (Figure~\ref{fig:c1-syntax}).}
  9829. \label{fig:c7-syntax}
  9830. \end{figure}
  9831. The new auxiliary function \code{explicate\_effect} takes an
  9832. expression (in an effect position) and a continuation. The function
  9833. returns a $\Tail$ that includes the generated code for the input
  9834. expression followed by the continuation. If the expression is
  9835. obviously pure, that is, never causes side effects, then the
  9836. expression can be removed, so the result is just the continuation.
  9837. %
  9838. The $\WHILE{\itm{cnd}}{\itm{body}}$ expression is the most interesting
  9839. case. First, you will need a fresh label $\itm{loop}$ for the top of
  9840. the loop. Recursively process the \itm{body} (in effect position)
  9841. with the a \code{goto} to $\itm{loop}$ as the continuation, producing
  9842. \itm{body'}. Next, process the \itm{cnd} (in predicate position) with
  9843. \itm{body'} as the then-branch and the continuation block as the
  9844. else-branch. The result should be added to the control-flow graph with
  9845. the label \itm{loop}. The result for the whole \code{while} loop is a
  9846. \code{goto} to the \itm{loop} label.
  9847. The auxiliary functions for tail, assignment, and predicate positions
  9848. need to be updated. The three new language forms, \code{while},
  9849. \code{set!}, and \code{begin}, can appear in assignment and tail
  9850. positions. Only \code{begin} may appear in predicate positions; the
  9851. other two have result type \code{Void}.
  9852. \fi}
  9853. %
  9854. {\if\edition\pythonEd
  9855. %
  9856. The output of this pass is the language \LangCIf{}. No new language
  9857. features are needed in the output because a \code{while} loop can be
  9858. expressed in terms of \code{goto} and \code{if} statements, which are
  9859. already in \LangCIf{}.
  9860. %
  9861. Add a case for the \code{while} statement to the
  9862. \code{explicate\_stmt} method, using \code{explicate\_pred} to process
  9863. the condition expression.
  9864. %
  9865. \fi}
  9866. {\if\edition\racketEd
  9867. \section{Select Instructions}
  9868. \label{sec:select-instructions-loop}
  9869. Only three small additions are needed in the
  9870. \code{select\_instructions} pass to handle the changes to
  9871. \LangCLoop{}. That is, a call to
  9872. \racket{\code{read}}\python{\code{input\_int}} may appear as a
  9873. stand-alone statement instead of only appearing on the right-hand side
  9874. of an assignment statement. The code generation is nearly identical;
  9875. just leave off the instruction for moving the result into the
  9876. left-hand side.
  9877. \fi}
  9878. \section{Register Allocation}
  9879. \label{sec:register-allocation-loop}
  9880. As discussed in Section~\ref{sec:dataflow-analysis}, the presence of
  9881. loops in \LangLoop{} means that the control-flow graphs may contain cycles,
  9882. which complicates the liveness analysis needed for register
  9883. allocation.
  9884. \subsection{Liveness Analysis}
  9885. \label{sec:liveness-analysis-r8}
  9886. We recommend using the generic \code{analyze\_dataflow} function that
  9887. was presented at the end of Section~\ref{sec:dataflow-analysis} to
  9888. perform liveness analysis, replacing the code in
  9889. \code{uncover\_live} that processed the basic blocks in topological
  9890. order (Section~\ref{sec:liveness-analysis-Lif}).
  9891. The \code{analyze\_dataflow} function has four parameters.
  9892. \begin{enumerate}
  9893. \item The first parameter \code{G} should be a directed graph from the
  9894. \racket{
  9895. \code{racket/graph} package (see the sidebar in
  9896. Section~\ref{sec:build-interference})}
  9897. \python{\code{graph.py} file in the support code}
  9898. that represents the
  9899. control-flow graph.
  9900. \item The second parameter \code{transfer} is a function that applies
  9901. liveness analysis to a basic block. It takes two parameters: the
  9902. label for the block to analyze and the live-after set for that
  9903. block. The transfer function should return the live-before set for
  9904. the block.
  9905. %
  9906. \racket{Also, as a side-effect, it should update the block's
  9907. $\itm{info}$ with the liveness information for each instruction.}
  9908. %
  9909. \python{Also, as a side-effect, it should update the live-before and
  9910. live-after sets for each instruction.}
  9911. %
  9912. To implement the \code{transfer} function, you should be able to
  9913. reuse the code you already have for analyzing basic blocks.
  9914. \item The third and fourth parameters of \code{analyze\_dataflow} are
  9915. \code{bottom} and \code{join} for the lattice of abstract states,
  9916. i.e. sets of locations. The bottom of the lattice is the empty set
  9917. and the join operator is set union.
  9918. \end{enumerate}
  9919. \begin{figure}[p]
  9920. \begin{tikzpicture}[baseline=(current bounding box.center)]
  9921. \node (Rfun) at (0,2) {\large \LangLoop{}};
  9922. \node (Rfun-2) at (3,2) {\large \LangLoop{}};
  9923. %\node (Rfun-3) at (6,2) {\large \LangLoop{}};
  9924. %\node (Rfun-4) at (9,2) {\large \LangLoopFunRef{}};
  9925. %\node (F1-1) at (12,0) {\large \LangLoopFunRef{}};
  9926. %\node (F1-2) at (9,0) {\large \LangLoopFunRef{}};
  9927. %\node (F1-3) at (6,0) {\large \LangLoopFunRef{}};
  9928. \node (F1-4) at (6,2) {\large \LangLoop{}};
  9929. \node (F1-5) at (9,2) {\large \LangLoopANF{}};
  9930. \node (C3-2) at (3,0) {\large \racket{\LangCLoop{}}\python{\LangCIf{}}};
  9931. \node (x86-2) at (3,-2) {\large \LangXIfVar{}};
  9932. \node (x86-2-1) at (3,-4) {\large \LangXIfVar{}};
  9933. \node (x86-2-2) at (6,-4) {\large \LangXIfVar{}};
  9934. \node (x86-3) at (6,-2) {\large \LangXIfVar{}};
  9935. \node (x86-4) at (9,-2) {\large \LangXIf{}};
  9936. \node (x86-5) at (9,-4) {\large \LangXIf{}};
  9937. %% \path[->,bend left=15] (Rfun) edge [above] node
  9938. %% {\ttfamily\footnotesize type-check} (Rfun-2);
  9939. \path[->,bend left=15] (Rfun) edge [above] node
  9940. {\ttfamily\footnotesize shrink} (Rfun-2);
  9941. \path[->,bend left=15] (Rfun-2) edge [above] node
  9942. {\ttfamily\footnotesize uniquify} (F1-4);
  9943. %% \path[->,bend left=15] (Rfun-3) edge [above] node
  9944. %% {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  9945. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9946. %% {\ttfamily\footnotesize convert\_assignments} (F1-1);
  9947. %% \path[->,bend left=15] (Rfun-4) edge [right] node
  9948. %% {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  9949. %% \path[->,bend right=15] (F1-2) edge [above] node
  9950. %% {\ttfamily\footnotesize limit\_fun.} (F1-3);
  9951. %% \path[->,bend right=15] (F1-3) edge [above] node
  9952. %% {\ttfamily\footnotesize expose-alloc.} (F1-4);
  9953. \path[->,bend left=15] (F1-4) edge [above] node
  9954. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  9955. \path[->,bend left=15] (F1-5) edge [right] node
  9956. {\ttfamily\footnotesize explicate\_control} (C3-2);
  9957. \path[->,bend left=15] (C3-2) edge [left] node
  9958. {\ttfamily\footnotesize select\_instr.} (x86-2);
  9959. \path[->,bend right=15] (x86-2) edge [left] node
  9960. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  9961. \path[->,bend right=15] (x86-2-1) edge [below] node
  9962. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  9963. \path[->,bend right=15] (x86-2-2) edge [left] node
  9964. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  9965. \path[->,bend left=15] (x86-3) edge [above] node
  9966. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  9967. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize prelude\_and\_concl.} (x86-5);
  9968. \end{tikzpicture}
  9969. \caption{Diagram of the passes for \LangLoop{}.}
  9970. \label{fig:Rwhile-passes}
  9971. \end{figure}
  9972. Figure~\ref{fig:Rwhile-passes} provides an overview of all the passes needed
  9973. for the compilation of \LangLoop{}.
  9974. % Further Reading: dataflow analysis
  9975. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  9976. \chapter{Tuples and Garbage Collection}
  9977. \label{ch:Lvec}
  9978. \index{subject}{tuple}
  9979. \index{subject}{vector}
  9980. \index{subject}{allocate}
  9981. \index{subject}{heap allocate}
  9982. %% \margincomment{\scriptsize To do: Flesh out this chapter, e.g., make sure
  9983. %% all the IR grammars are spelled out! \\ --Jeremy}
  9984. %% \margincomment{\scriptsize Be more explicit about how to deal with
  9985. %% the root stack. \\ --Jeremy}
  9986. In this chapter we study the implementation of
  9987. tuples\racket{, called vectors in Racket}.
  9988. %
  9989. This language feature is the first to use the computer's
  9990. \emph{heap}\index{subject}{heap} because the lifetime of a tuple is
  9991. indefinite, that is, a tuple lives forever from the programmer's
  9992. viewpoint. Of course, from an implementer's viewpoint, it is important
  9993. to reclaim the space associated with a tuple when it is no longer
  9994. needed, which is why we also study \emph{garbage collection}
  9995. \index{garbage collection} techniques in this chapter.
  9996. Section~\ref{sec:r3} introduces the \LangVec{} language including its
  9997. interpreter and type checker. The \LangVec{} language extends the \LangLoop{}
  9998. language of Chapter~\ref{ch:Lwhile} with tuples.
  9999. Section~\ref{sec:GC} describes a garbage collection algorithm based on
  10000. copying live tuples back and forth between two halves of the heap. The
  10001. garbage collector requires coordination with the compiler so that it
  10002. can find all of the live tuples.
  10003. Sections~\ref{sec:expose-allocation} through \ref{sec:print-x86-gc}
  10004. discuss the necessary changes and additions to the compiler passes,
  10005. including a new compiler pass named \code{expose\_allocation}.
  10006. \section{The \LangVec{} Language}
  10007. \label{sec:r3}
  10008. Figure~\ref{fig:Lvec-concrete-syntax} defines the concrete syntax for
  10009. \LangVec{} and Figure~\ref{fig:Lvec-syntax} defines the abstract syntax.
  10010. %
  10011. \racket{The \LangVec{} language includes the forms: \code{vector} for
  10012. creating a tuple, \code{vector-ref} for reading an element of a
  10013. tuple, \code{vector-set!} for writing to an element of a tuple, and
  10014. \code{vector-length} for obtaining the number of elements of a
  10015. tuple.}
  10016. %
  10017. \python{The \LangVec{} language adds 1) tuple creation via a
  10018. comma-separated list of expressions, 2) accessing an element of a
  10019. tuple with the square bracket notation, i.e., \code{t[n]} returns
  10020. the element at index \code{n} of tuple \code{t}, 3) the \code{is} comparison
  10021. operator, and 4) obtaining the number of elements (the length) of a
  10022. tuple. In this chapter, we restrict access indices to constant
  10023. integers.}
  10024. %
  10025. The program below shows an example use of tuples. It creates a tuple
  10026. \code{t} containing the elements \code{40},
  10027. \racket{\code{\#t}}\python{\code{True}}, and another tuple that
  10028. contains just \code{2}. The element at index $1$ of \code{t} is
  10029. \racket{\code{\#t}}\python{\code{True}}, so the ``then'' branch of the
  10030. \key{if} is taken. The element at index $0$ of \code{t} is \code{40},
  10031. to which we add \code{2}, the element at index $0$ of the tuple. So
  10032. the result of the program is \code{42}.
  10033. %
  10034. {\if\edition\racketEd
  10035. \begin{lstlisting}
  10036. (let ([t (vector 40 #t (vector 2))])
  10037. (if (vector-ref t 1)
  10038. (+ (vector-ref t 0)
  10039. (vector-ref (vector-ref t 2) 0))
  10040. 44))
  10041. \end{lstlisting}
  10042. \fi}
  10043. {\if\edition\pythonEd
  10044. \begin{lstlisting}
  10045. t = 40, True, (2,)
  10046. print( t[0] + t[2][0] if t[1] else 44 )
  10047. \end{lstlisting}
  10048. \fi}
  10049. \newcommand{\LtupGrammarRacket}{
  10050. \begin{array}{lcl}
  10051. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10052. \Exp &::=& \LP\key{vector}\;\Exp\ldots\RP
  10053. \MID \LP\key{vector-length}\;\Exp\RP \\
  10054. &\MID& \LP\key{vector-ref}\;\Exp\;\Int\RP
  10055. \MID \LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP
  10056. \end{array}
  10057. }
  10058. \newcommand{\LtupASTRacket}{
  10059. \begin{array}{lcl}
  10060. \Type &::=& \LP\key{Vector}\;\Type\ldots\RP \\
  10061. \itm{op} &::=& \code{vector} \MID \code{vector-length} \\
  10062. \Exp &::=& \VECREF{\Exp}{\INT{\Int}} \\
  10063. &\MID& \VECSET{\Exp}{\INT{\Int}}{\Exp} \\
  10064. &\MID& \LP\key{HasType}~\Exp~\Type \RP
  10065. \end{array}
  10066. }
  10067. \newcommand{\LtupGrammarPython}{
  10068. \begin{array}{rcl}
  10069. \itm{cmp} &::= & \key{is} \\
  10070. \Exp &::=& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Int} \MID \CLEN{\Exp}
  10071. \end{array}
  10072. }
  10073. \newcommand{\LtupASTPython}{
  10074. \begin{array}{lcl}
  10075. \itm{cmp} &::= & \code{Is()} \\
  10076. \Exp &::=& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\INT{\Int}} \\
  10077. &\MID& \LEN{\Exp}
  10078. \end{array}
  10079. }
  10080. \begin{figure}[tbp]
  10081. \centering
  10082. \fbox{
  10083. \begin{minipage}{0.96\textwidth}
  10084. {\if\edition\racketEd
  10085. \[
  10086. \begin{array}{l}
  10087. \gray{\LintGrammarRacket{}} \\ \hline
  10088. \gray{\LvarGrammarRacket{}} \\ \hline
  10089. \gray{\LifGrammarRacket{}} \\ \hline
  10090. \gray{\LwhileGrammarRacket} \\ \hline
  10091. \LtupGrammarRacket \\
  10092. \begin{array}{lcl}
  10093. \LangVecM{} &::=& \Exp
  10094. \end{array}
  10095. \end{array}
  10096. \]
  10097. \fi}
  10098. {\if\edition\pythonEd
  10099. \[
  10100. \begin{array}{l}
  10101. \gray{\LintGrammarPython{}} \\ \hline
  10102. \gray{\LvarGrammarPython{}} \\ \hline
  10103. \gray{\LifGrammarPython{}} \\ \hline
  10104. \gray{\LwhileGrammarPython} \\ \hline
  10105. \LtupGrammarPython \\
  10106. \begin{array}{rcl}
  10107. \LangVecM{} &::=& \Stmt^{*}
  10108. \end{array}
  10109. \end{array}
  10110. \]
  10111. \fi}
  10112. \end{minipage}
  10113. }
  10114. \caption{The concrete syntax of \LangVec{}, extending \LangLoop{}
  10115. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  10116. \label{fig:Lvec-concrete-syntax}
  10117. \end{figure}
  10118. \begin{figure}[tp]
  10119. \centering
  10120. \fbox{
  10121. \begin{minipage}{0.96\textwidth}
  10122. {\if\edition\racketEd
  10123. \[
  10124. \begin{array}{l}
  10125. \gray{\LintOpAST} \\ \hline
  10126. \gray{\LvarASTRacket{}} \\ \hline
  10127. \gray{\LifASTRacket{}} \\ \hline
  10128. \gray{\LwhileASTRacket{}} \\ \hline
  10129. \LtupASTRacket{} \\
  10130. \begin{array}{lcl}
  10131. \LangVecM{} &::=& \PROGRAM{\key{'()}}{\Exp}
  10132. \end{array}
  10133. \end{array}
  10134. \]
  10135. \fi}
  10136. {\if\edition\pythonEd
  10137. \[
  10138. \begin{array}{l}
  10139. \gray{\LintASTPython} \\ \hline
  10140. \gray{\LvarASTPython} \\ \hline
  10141. \gray{\LifASTPython} \\ \hline
  10142. \gray{\LwhileASTPython} \\ \hline
  10143. \LtupASTPython \\
  10144. \begin{array}{lcl}
  10145. \LangLoopM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10146. \end{array}
  10147. \end{array}
  10148. \]
  10149. \fi}
  10150. \end{minipage}
  10151. }
  10152. \caption{The abstract syntax of \LangVec{}.}
  10153. \label{fig:Lvec-syntax}
  10154. \end{figure}
  10155. Tuples raise several interesting new issues. First, variable binding
  10156. performs a shallow-copy when dealing with tuples, which means that
  10157. different variables can refer to the same tuple, that is, two
  10158. variables can be \emph{aliases}\index{subject}{alias} for the same
  10159. entity. Consider the following example in which both \code{t1} and
  10160. \code{t2} refer to the same tuple value but \code{t3} refers to a
  10161. different tuple value but with equal elements. The result of the
  10162. program is \code{42}.
  10163. \begin{center}
  10164. \begin{minipage}{0.96\textwidth}
  10165. {\if\edition\racketEd
  10166. \begin{lstlisting}
  10167. (let ([t1 (vector 3 7)])
  10168. (let ([t2 t1])
  10169. (let ([t3 (vector 3 7)])
  10170. (if (and (eq? t1 t2) (not (eq? t1 t3)))
  10171. 42
  10172. 0))))
  10173. \end{lstlisting}
  10174. \fi}
  10175. {\if\edition\pythonEd
  10176. \begin{lstlisting}
  10177. t1 = 3, 7
  10178. t2 = t1
  10179. t3 = 3, 7
  10180. print( 42 if (t1 is t2) and not (t1 is t3) else 0 )
  10181. \end{lstlisting}
  10182. \fi}
  10183. \end{minipage}
  10184. \end{center}
  10185. {\if\edition\racketEd
  10186. Whether two variables are aliased or not affects what happens
  10187. when the underlying tuple is mutated\index{subject}{mutation}.
  10188. Consider the following example in which \code{t1} and \code{t2}
  10189. again refer to the same tuple value.
  10190. \begin{center}
  10191. \begin{minipage}{0.96\textwidth}
  10192. \begin{lstlisting}
  10193. (let ([t1 (vector 3 7)])
  10194. (let ([t2 t1])
  10195. (let ([_ (vector-set! t2 0 42)])
  10196. (vector-ref t1 0))))
  10197. \end{lstlisting}
  10198. \end{minipage}
  10199. \end{center}
  10200. The mutation through \code{t2} is visible when referencing the tuple
  10201. from \code{t1}, so the result of this program is \code{42}.
  10202. \fi}
  10203. The next issue concerns the lifetime of tuples. When does their
  10204. lifetime end? Notice that \LangVec{} does not include an operation
  10205. for deleting tuples. Furthermore, the lifetime of a tuple is not tied
  10206. to any notion of static scoping.
  10207. %
  10208. {\if\edition\racketEd
  10209. %
  10210. For example, the following program returns \code{42} even though the
  10211. variable \code{w} goes out of scope prior to the \code{vector-ref}
  10212. that reads from the vector it was bound to.
  10213. \begin{center}
  10214. \begin{minipage}{0.96\textwidth}
  10215. \begin{lstlisting}
  10216. (let ([v (vector (vector 44))])
  10217. (let ([x (let ([w (vector 42)])
  10218. (let ([_ (vector-set! v 0 w)])
  10219. 0))])
  10220. (+ x (vector-ref (vector-ref v 0) 0))))
  10221. \end{lstlisting}
  10222. \end{minipage}
  10223. \end{center}
  10224. \fi}
  10225. %
  10226. {\if\edition\pythonEd
  10227. %
  10228. For example, the following program returns \code{42} even though the
  10229. variable \code{x} goes out of scope when the function returns, prior
  10230. to reading the tuple element at index zero. (We study the compilation
  10231. of functions in Chapter~\ref{ch:Lfun}.)
  10232. %
  10233. \begin{center}
  10234. \begin{minipage}{0.96\textwidth}
  10235. \begin{lstlisting}
  10236. def f():
  10237. x = 42, 43
  10238. return x
  10239. t = f()
  10240. print( t[0] )
  10241. \end{lstlisting}
  10242. \end{minipage}
  10243. \end{center}
  10244. \fi}
  10245. %
  10246. From the perspective of programmer-observable behavior, tuples live
  10247. forever. However, if they really lived forever then many long-running
  10248. programs would run out of memory. To solve this problem, the
  10249. language's runtime system performs automatic garbage collection.
  10250. Figure~\ref{fig:interp-Lvec} shows the definitional interpreter for the
  10251. \LangVec{} language.
  10252. %
  10253. \racket{We define the \code{vector}, \code{vector-ref},
  10254. \code{vector-set!}, and \code{vector-length} operations for
  10255. \LangVec{} in terms of the corresponding operations in Racket. One
  10256. subtle point is that the \code{vector-set!} operation returns the
  10257. \code{\#<void>} value.}
  10258. %
  10259. \python{We represent tuples with Python lists in the interpreter
  10260. because we need to write to them
  10261. (Section~\ref{sec:expose-allocation}). (Python tuples are
  10262. immutable.) We define element access, the \code{is} operator, and
  10263. the \code{len} operator for \LangVec{} in terms of the corresponding
  10264. operations in Python.}
  10265. \begin{figure}[tbp]
  10266. {\if\edition\racketEd
  10267. \begin{lstlisting}
  10268. (define interp-Lvec_class
  10269. (class interp-Lif_class
  10270. (super-new)
  10271. (define/override (interp-op op)
  10272. (match op
  10273. ['eq? (lambda (v1 v2)
  10274. (cond [(or (and (fixnum? v1) (fixnum? v2))
  10275. (and (boolean? v1) (boolean? v2))
  10276. (and (vector? v1) (vector? v2))
  10277. (and (void? v1) (void? v2)))
  10278. (eq? v1 v2)]))]
  10279. ['vector vector]
  10280. ['vector-length vector-length]
  10281. ['vector-ref vector-ref]
  10282. ['vector-set! vector-set!]
  10283. [else (super interp-op op)]
  10284. ))
  10285. (define/override ((interp-exp env) e)
  10286. (define recur (interp-exp env))
  10287. (match e
  10288. [(HasType e t) (recur e)]
  10289. [(Void) (void)]
  10290. [else ((super interp-exp env) e)]
  10291. ))
  10292. ))
  10293. (define (interp-Lvec p)
  10294. (send (new interp-Lvec_class) interp-program p))
  10295. \end{lstlisting}
  10296. \fi}
  10297. %
  10298. {\if\edition\pythonEd
  10299. \begin{lstlisting}
  10300. class InterpLtup(InterpLwhile):
  10301. def interp_cmp(self, cmp):
  10302. match cmp:
  10303. case Is():
  10304. return lambda x, y: x is y
  10305. case _:
  10306. return super().interp_cmp(cmp)
  10307. def interp_exp(self, e, env):
  10308. match e:
  10309. case Tuple(es, Load()):
  10310. return tuple([self.interp_exp(e, env) for e in es])
  10311. case Subscript(tup, index, Load()):
  10312. t = self.interp_exp(tup, env)
  10313. n = self.interp_exp(index, env)
  10314. return t[n]
  10315. case _:
  10316. return super().interp_exp(e, env)
  10317. \end{lstlisting}
  10318. \fi}
  10319. \caption{Interpreter for the \LangVec{} language.}
  10320. \label{fig:interp-Lvec}
  10321. \end{figure}
  10322. Figure~\ref{fig:type-check-Lvec} shows the type checker for
  10323. \LangVec{}, which deserves some explanation. When allocating a tuple,
  10324. we need to know which elements of the tuple are themselves tuples for
  10325. the purposes of garbage collection. We can obtain this information
  10326. during type checking. The type checker in
  10327. Figure~\ref{fig:type-check-Lvec} not only computes the type of an
  10328. expression, it also
  10329. %
  10330. \racket{wraps every tuple creation with the form $(\key{HasType}~e~T)$,
  10331. where $T$ is the vector's type.
  10332. To create the s-expression for the \code{Vector} type in
  10333. Figure~\ref{fig:type-check-Lvec}, we use the
  10334. \href{https://docs.racket-lang.org/reference/quasiquote.html}{unquote-splicing
  10335. operator} \code{,@} to insert the list \code{t*} without its usual
  10336. start and end parentheses. \index{subject}{unquote-slicing}}
  10337. %
  10338. \python{records the type of each tuple expression in a new field
  10339. named \code{has\_type}. Because the type checker has to compute the type
  10340. of each tuple access, the index must be a constant.}
  10341. \begin{figure}[tp]
  10342. {\if\edition\racketEd
  10343. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  10344. (define type-check-Lvec_class
  10345. (class type-check-Lif_class
  10346. (super-new)
  10347. (inherit check-type-equal?)
  10348. (define/override (type-check-exp env)
  10349. (lambda (e)
  10350. (define recur (type-check-exp env))
  10351. (match e
  10352. [(Void) (values (Void) 'Void)]
  10353. [(Prim 'vector es)
  10354. (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e)))
  10355. (define t `(Vector ,@t*))
  10356. (values (HasType (Prim 'vector e*) t) t)]
  10357. [(Prim 'vector-ref (list e1 (Int i)))
  10358. (define-values (e1^ t) (recur e1))
  10359. (match t
  10360. [`(Vector ,ts ...)
  10361. (unless (and (0 . <= . i) (i . < . (length ts)))
  10362. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10363. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  10364. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10365. [(Prim 'vector-set! (list e1 (Int i) arg) )
  10366. (define-values (e-vec t-vec) (recur e1))
  10367. (define-values (e-arg^ t-arg) (recur arg))
  10368. (match t-vec
  10369. [`(Vector ,ts ...)
  10370. (unless (and (0 . <= . i) (i . < . (length ts)))
  10371. (error 'type-check "index ~a out of bounds\nin ~v" i e))
  10372. (check-type-equal? (list-ref ts i) t-arg e)
  10373. (values (Prim 'vector-set! (list e-vec (Int i) e-arg^)) 'Void)]
  10374. [else (error 'type-check "expect Vector, not ~a\nin ~v" t-vec e)])]
  10375. [(Prim 'vector-length (list e))
  10376. (define-values (e^ t) (recur e))
  10377. (match t
  10378. [`(Vector ,ts ...)
  10379. (values (Prim 'vector-length (list e^)) 'Integer)]
  10380. [else (error 'type-check "expect Vector, not ~a\nin ~v" t e)])]
  10381. [(Prim 'eq? (list arg1 arg2))
  10382. (define-values (e1 t1) (recur arg1))
  10383. (define-values (e2 t2) (recur arg2))
  10384. (match* (t1 t2)
  10385. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  10386. [(other wise) (check-type-equal? t1 t2 e)])
  10387. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  10388. [(HasType (Prim 'vector es) t)
  10389. ((type-check-exp env) (Prim 'vector es))]
  10390. [(HasType e1 t)
  10391. (define-values (e1^ t^) (recur e1))
  10392. (check-type-equal? t t^ e)
  10393. (values (HasType e1^ t) t)]
  10394. [else ((super type-check-exp env) e)]
  10395. )))
  10396. ))
  10397. (define (type-check-Lvec p)
  10398. (send (new type-check-Lvec_class) type-check-program p))
  10399. \end{lstlisting}
  10400. \fi}
  10401. {\if\edition\pythonEd
  10402. \begin{lstlisting}
  10403. class TypeCheckLtup(TypeCheckLwhile):
  10404. def type_check_exp(self, e, env):
  10405. match e:
  10406. case Compare(left, [cmp], [right]) if isinstance(cmp, Is):
  10407. l = self.type_check_exp(left, env)
  10408. r = self.type_check_exp(right, env)
  10409. check_type_equal(l, r, e)
  10410. return bool
  10411. case Tuple(es, Load()):
  10412. ts = [self.type_check_exp(e, env) for e in es]
  10413. e.has_type = tuple(ts)
  10414. return e.has_type
  10415. case Subscript(tup, Constant(index), Load()):
  10416. tup_ty = self.type_check_exp(tup, env)
  10417. index_ty = self.type_check_exp(Constant(index), env)
  10418. check_type_equal(index_ty, int, index)
  10419. match tup_ty:
  10420. case tuple(ts):
  10421. return ts[index]
  10422. case _:
  10423. raise Exception('error: expected a tuple, not ' + repr(tup_ty))
  10424. case _:
  10425. return super().type_check_exp(e, env)
  10426. \end{lstlisting}
  10427. \fi}
  10428. \caption{Type checker for the \LangVec{} language.}
  10429. \label{fig:type-check-Lvec}
  10430. \end{figure}
  10431. \section{Garbage Collection}
  10432. \label{sec:GC}
  10433. Garbage collection is a runtime technique for reclaiming space on the
  10434. heap that will not be used in the future of the running program. We
  10435. use the term \emph{object}\index{subject}{object} to refer to any
  10436. value that is stored in the heap, which for now only includes
  10437. tuples.%
  10438. %
  10439. \footnote{The term ``object'' as used in the context of
  10440. object-oriented programming has a more specific meaning than how we
  10441. are using the term here.}
  10442. %
  10443. Unfortunately, it is impossible to know precisely which objects will
  10444. be accessed in the future and which will not. Instead, garbage
  10445. collectors overapproximate the set of objects that will be accessed by
  10446. identifying which objects can possibly be accessed. The running
  10447. program can directly access objects that are in registers and on the
  10448. procedure call stack. It can also transitively access the elements of
  10449. tuples, starting with a tuple whose address is in a register or on the
  10450. procedure call stack. We define the \emph{root
  10451. set}\index{subject}{root set} to be all the tuple addresses that are
  10452. in registers or on the procedure call stack. We define the \emph{live
  10453. objects}\index{subject}{live objects} to be the objects that are
  10454. reachable from the root set. Garbage collectors reclaim the space that
  10455. is allocated to objects that are no longer live. That means that some
  10456. objects may not get reclaimed as soon as they could be, but at least
  10457. garbage collectors do not reclaim the space dedicated to objects that
  10458. will be accessed in the future! The programmer can influence which
  10459. objects get reclaimed by causing them to become unreachable.
  10460. So the goal of the garbage collector is twofold:
  10461. \begin{enumerate}
  10462. \item preserve all the live objects, and
  10463. \item reclaim the memory of everything else, that is, the \emph{garbage}.
  10464. \end{enumerate}
  10465. \subsection{Two-Space Copying Collector}
  10466. Here we study a relatively simple algorithm for garbage collection
  10467. that is the basis of many state-of-the-art garbage
  10468. collectors~\citep{Lieberman:1983aa,Ungar:1984aa,Jones:1996aa,Detlefs:2004aa,Dybvig:2006aa,Tene:2011kx}. In
  10469. particular, we describe a two-space copying
  10470. collector~\citep{Wilson:1992fk} that uses Cheney's algorithm to
  10471. perform the copy~\citep{Cheney:1970aa}. \index{subject}{copying
  10472. collector} \index{subject}{two-space copying collector}
  10473. Figure~\ref{fig:copying-collector} gives a coarse-grained depiction of
  10474. what happens in a two-space collector, showing two time steps, prior
  10475. to garbage collection (on the top) and after garbage collection (on
  10476. the bottom). In a two-space collector, the heap is divided into two
  10477. parts named the FromSpace\index{subject}{FromSpace} and the
  10478. ToSpace\index{subject}{ToSpace}. Initially, all allocations go to the
  10479. FromSpace until there is not enough room for the next allocation
  10480. request. At that point, the garbage collector goes to work to room for
  10481. the next allocation.
  10482. A copying collector makes more room by copying all of the live objects
  10483. from the FromSpace into the ToSpace and then performs a sleight of
  10484. hand, treating the ToSpace as the new FromSpace and the old FromSpace
  10485. as the new ToSpace. In the example of
  10486. Figure~\ref{fig:copying-collector}, there are three pointers in the
  10487. root set, one in a register and two on the stack. All of the live
  10488. objects have been copied to the ToSpace (the right-hand side of
  10489. Figure~\ref{fig:copying-collector}) in a way that preserves the
  10490. pointer relationships. For example, the pointer in the register still
  10491. points to a tuple that in turn points to two other tuples. There are
  10492. four tuples that are not reachable from the root set and therefore do
  10493. not get copied into the ToSpace.
  10494. The exact situation in Figure~\ref{fig:copying-collector} cannot be
  10495. created by a well-typed program in \LangVec{} because it contains a
  10496. cycle. However, creating cycles will be possible once we get to
  10497. \LangDyn{}. We design the garbage collector to deal with cycles to
  10498. begin with so we will not need to revisit this issue.
  10499. \begin{figure}[tbp]
  10500. \centering
  10501. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-1}}
  10502. \python{\includegraphics[width=\textwidth]{figs/copy-collect-1-python}}
  10503. \\[5ex]
  10504. \racket{\includegraphics[width=\textwidth]{figs/copy-collect-2}}
  10505. \python{\includegraphics[width=\textwidth]{figs/copy-collect-2-python}}
  10506. \caption{A copying collector in action.}
  10507. \label{fig:copying-collector}
  10508. \end{figure}
  10509. \subsection{Graph Copying via Cheney's Algorithm}
  10510. \label{sec:cheney}
  10511. \index{subject}{Cheney's algorithm}
  10512. Let us take a closer look at the copying of the live objects. The
  10513. allocated objects and pointers can be viewed as a graph and we need to
  10514. copy the part of the graph that is reachable from the root set. To
  10515. make sure we copy all of the reachable vertices in the graph, we need
  10516. an exhaustive graph traversal algorithm, such as depth-first search or
  10517. breadth-first search~\citep{Moore:1959aa,Cormen:2001uq}. Recall that
  10518. such algorithms take into account the possibility of cycles by marking
  10519. which vertices have already been visited, so as to ensure termination
  10520. of the algorithm. These search algorithms also use a data structure
  10521. such as a stack or queue as a to-do list to keep track of the vertices
  10522. that need to be visited. We use breadth-first search and a trick
  10523. due to \citet{Cheney:1970aa} for simultaneously representing the queue
  10524. and copying tuples into the ToSpace.
  10525. Figure~\ref{fig:cheney} shows several snapshots of the ToSpace as the
  10526. copy progresses. The queue is represented by a chunk of contiguous
  10527. memory at the beginning of the ToSpace, using two pointers to track
  10528. the front and the back of the queue, called the \emph{free pointer}
  10529. and the \emph{scan pointer} respectively. The algorithm starts by
  10530. copying all tuples that are immediately reachable from the root set
  10531. into the ToSpace to form the initial queue. When we copy a tuple, we
  10532. mark the old tuple to indicate that it has been visited. We discuss
  10533. how this marking is accomplish in Section~\ref{sec:data-rep-gc}. Note
  10534. that any pointers inside the copied tuples in the queue still point
  10535. back to the FromSpace. Once the initial queue has been created, the
  10536. algorithm enters a loop in which it repeatedly processes the tuple at
  10537. the front of the queue and pops it off the queue. To process a tuple,
  10538. the algorithm copies all the tuple that are directly reachable from it
  10539. to the ToSpace, placing them at the back of the queue. The algorithm
  10540. then updates the pointers in the popped tuple so they point to the
  10541. newly copied tuples.
  10542. \begin{figure}[tbp]
  10543. \centering
  10544. \racket{\includegraphics[width=0.9\textwidth]{figs/cheney}}
  10545. \python{\includegraphics[width=0.9\textwidth]{figs/cheney-python}}
  10546. \caption{Depiction of the Cheney algorithm copying the live tuples.}
  10547. \label{fig:cheney}
  10548. \end{figure}
  10549. Getting back to Figure~\ref{fig:cheney}, in the first step we copy the
  10550. tuple whose second element is $42$ to the back of the queue. The other
  10551. pointer goes to a tuple that has already been copied, so we do not
  10552. need to copy it again, but we do need to update the pointer to the new
  10553. location. This can be accomplished by storing a \emph{forwarding
  10554. pointer}\index{subect}{forwarding pointer} to the new location in the
  10555. old tuple, back when we initially copied the tuple into the
  10556. ToSpace. This completes one step of the algorithm. The algorithm
  10557. continues in this way until the queue is empty, that is, when the scan
  10558. pointer catches up with the free pointer.
  10559. \subsection{Data Representation}
  10560. \label{sec:data-rep-gc}
  10561. The garbage collector places some requirements on the data
  10562. representations used by our compiler. First, the garbage collector
  10563. needs to distinguish between pointers and other kinds of data such as
  10564. integers. There are several ways to accomplish this.
  10565. \begin{enumerate}
  10566. \item Attached a tag to each object that identifies what type of
  10567. object it is~\citep{McCarthy:1960dz}.
  10568. \item Store different types of objects in different
  10569. regions~\citep{Steele:1977ab}.
  10570. \item Use type information from the program to either generate
  10571. type-specific code for collecting or to generate tables that can
  10572. guide the
  10573. collector~\citep{Appel:1989aa,Goldberg:1991aa,Diwan:1992aa}.
  10574. \end{enumerate}
  10575. Dynamically typed languages, such as \racket{Racket}\python{Python},
  10576. need to tag objects anyways, so option 1 is a natural choice for those
  10577. languages. However, \LangVec{} is a statically typed language, so it
  10578. would be unfortunate to require tags on every object, especially small
  10579. and pervasive objects like integers and Booleans. Option 3 is the
  10580. best-performing choice for statically typed languages, but comes with
  10581. a relatively high implementation complexity. To keep this chapter
  10582. within a reasonable time budget, we recommend a combination of options
  10583. 1 and 2, using separate strategies for the stack and the heap.
  10584. Regarding the stack, we recommend using a separate stack for pointers,
  10585. which we call the \emph{root stack}\index{subject}{root stack}
  10586. (a.k.a. ``shadow
  10587. stack'')~\citep{Siebert:2001aa,Henderson:2002aa,Baker:2009aa}. That
  10588. is, when a local variable needs to be spilled and is of type
  10589. \racket{\code{Vector}}\python{\code{TupleType}}, then we put it on the
  10590. root stack instead of putting it on the procedure call
  10591. stack. Furthermore, we always spill tuple-typed variables if they are
  10592. live during a call to the collector, thereby ensuring that no pointers
  10593. are in registers during a collection. Figure~\ref{fig:shadow-stack}
  10594. reproduces the example from Figure~\ref{fig:copying-collector} and
  10595. contrasts it with the data layout using a root stack. The root stack
  10596. contains the two pointers from the regular stack and also the pointer
  10597. in the second register.
  10598. \begin{figure}[tbp]
  10599. \centering
  10600. \racket{\includegraphics[width=0.60\textwidth]{figs/root-stack}}
  10601. \python{\includegraphics[width=0.60\textwidth]{figs/root-stack-python}}
  10602. \caption{Maintaining a root stack to facilitate garbage collection.}
  10603. \label{fig:shadow-stack}
  10604. \end{figure}
  10605. The problem of distinguishing between pointers and other kinds of data
  10606. also arises inside of each tuple on the heap. We solve this problem by
  10607. attaching a tag, an extra 64-bits, to each
  10608. tuple. Figure~\ref{fig:tuple-rep} zooms in on the tags for two of the
  10609. tuples in the example from Figure~\ref{fig:copying-collector}. Note
  10610. that we have drawn the bits in a big-endian way, from right-to-left,
  10611. with bit location 0 (the least significant bit) on the far right,
  10612. which corresponds to the direction of the x86 shifting instructions
  10613. \key{salq} (shift left) and \key{sarq} (shift right). Part of each tag
  10614. is dedicated to specifying which elements of the tuple are pointers,
  10615. the part labeled ``pointer mask''. Within the pointer mask, a 1 bit
  10616. indicates there is a pointer and a 0 bit indicates some other kind of
  10617. data. The pointer mask starts at bit location 7. We limit tuples to a
  10618. maximum size of 50 elements, so we just need 50 bits for the pointer
  10619. mask.%
  10620. %
  10621. \footnote{A production-quality compiler would handle
  10622. arbitrary-sized tuples and use a more complex approach.}
  10623. %
  10624. The tag also contains two other pieces of information. The length of
  10625. the tuple (number of elements) is stored in bits location 1 through
  10626. 6. Finally, the bit at location 0 indicates whether the tuple has yet
  10627. to be copied to the ToSpace. If the bit has value 1, then this tuple
  10628. has not yet been copied. If the bit has value 0 then the entire tag
  10629. is a forwarding pointer. (The lower 3 bits of a pointer are always
  10630. zero anyways because our tuples are 8-byte aligned.)
  10631. \begin{figure}[tbp]
  10632. \centering \includegraphics[width=0.8\textwidth]{figs/tuple-rep}
  10633. \caption{Representation of tuples in the heap.}
  10634. \label{fig:tuple-rep}
  10635. \end{figure}
  10636. \subsection{Implementation of the Garbage Collector}
  10637. \label{sec:organize-gz}
  10638. \index{subject}{prelude}
  10639. An implementation of the copying collector is provided in the
  10640. \code{runtime.c} file. Figure~\ref{fig:gc-header} defines the
  10641. interface to the garbage collector that is used by the compiler. The
  10642. \code{initialize} function creates the FromSpace, ToSpace, and root
  10643. stack and should be called in the prelude of the \code{main}
  10644. function. The arguments of \code{initialize} are the root stack size
  10645. and the heap size. Both need to be multiples of $64$ and $16384$ is a
  10646. good choice for both. The \code{initialize} function puts the address
  10647. of the beginning of the FromSpace into the global variable
  10648. \code{free\_ptr}. The global variable \code{fromspace\_end} points to
  10649. the address that is 1-past the last element of the FromSpace. (We use
  10650. half-open intervals to represent chunks of
  10651. memory~\citep{Dijkstra:1982aa}.) The \code{rootstack\_begin} variable
  10652. points to the first element of the root stack.
  10653. As long as there is room left in the FromSpace, your generated code
  10654. can allocate tuples simply by moving the \code{free\_ptr} forward.
  10655. %
  10656. The amount of room left in FromSpace is the difference between the
  10657. \code{fromspace\_end} and the \code{free\_ptr}. The \code{collect}
  10658. function should be called when there is not enough room left in the
  10659. FromSpace for the next allocation. The \code{collect} function takes
  10660. a pointer to the current top of the root stack (one past the last item
  10661. that was pushed) and the number of bytes that need to be
  10662. allocated. The \code{collect} function performs the copying collection
  10663. and leaves the heap in a state such that the next allocation will
  10664. succeed.
  10665. \begin{figure}[tbp]
  10666. \begin{lstlisting}
  10667. void initialize(uint64_t rootstack_size, uint64_t heap_size);
  10668. void collect(int64_t** rootstack_ptr, uint64_t bytes_requested);
  10669. int64_t* free_ptr;
  10670. int64_t* fromspace_begin;
  10671. int64_t* fromspace_end;
  10672. int64_t** rootstack_begin;
  10673. \end{lstlisting}
  10674. \caption{The compiler's interface to the garbage collector.}
  10675. \label{fig:gc-header}
  10676. \end{figure}
  10677. %% \begin{exercise}
  10678. %% In the file \code{runtime.c} you will find the implementation of
  10679. %% \code{initialize} and a partial implementation of \code{collect}.
  10680. %% The \code{collect} function calls another function, \code{cheney},
  10681. %% to perform the actual copy, and that function is left to the reader
  10682. %% to implement. The following is the prototype for \code{cheney}.
  10683. %% \begin{lstlisting}
  10684. %% static void cheney(int64_t** rootstack_ptr);
  10685. %% \end{lstlisting}
  10686. %% The parameter \code{rootstack\_ptr} is a pointer to the top of the
  10687. %% rootstack (which is an array of pointers). The \code{cheney} function
  10688. %% also communicates with \code{collect} through the global
  10689. %% variables \code{fromspace\_begin} and \code{fromspace\_end}
  10690. %% mentioned in Figure~\ref{fig:gc-header} as well as the pointers for
  10691. %% the ToSpace:
  10692. %% \begin{lstlisting}
  10693. %% static int64_t* tospace_begin;
  10694. %% static int64_t* tospace_end;
  10695. %% \end{lstlisting}
  10696. %% The job of the \code{cheney} function is to copy all the live
  10697. %% objects (reachable from the root stack) into the ToSpace, update
  10698. %% \code{free\_ptr} to point to the next unused spot in the ToSpace,
  10699. %% update the root stack so that it points to the objects in the
  10700. %% ToSpace, and finally to swap the global pointers for the FromSpace
  10701. %% and ToSpace.
  10702. %% \end{exercise}
  10703. The introduction of garbage collection has a non-trivial impact on our
  10704. compiler passes. We introduce a new compiler pass named
  10705. \code{expose\_allocation}. We make significant changes to
  10706. \code{select\_instructions}, \code{build\_interference},
  10707. \code{allocate\_registers}, and \code{prelude\_and\_conclusion} and
  10708. make minor changes in several more passes. The following program will
  10709. serve as our running example. It creates two tuples, one nested
  10710. inside the other. Both tuples have length one. The program accesses
  10711. the element in the inner tuple.
  10712. % tests/vectors_test_17.rkt
  10713. {\if\edition\racketEd
  10714. \begin{lstlisting}
  10715. (vector-ref (vector-ref (vector (vector 42)) 0) 0)
  10716. \end{lstlisting}
  10717. \fi}
  10718. {\if\edition\pythonEd
  10719. \begin{lstlisting}
  10720. print( ((42,),)[0][0] )
  10721. \end{lstlisting}
  10722. \fi}
  10723. {\if\edition\racketEd
  10724. \section{Shrink}
  10725. \label{sec:shrink-Lvec}
  10726. Recall that the \code{shrink} pass translates the primitives operators
  10727. into a smaller set of primitives.
  10728. %
  10729. This pass comes after type checking and the type checker adds a
  10730. \code{HasType} AST node around each \code{vector} AST node, so you'll
  10731. need to add a case for \code{HasType} to the \code{shrink} pass.
  10732. \fi}
  10733. \section{Expose Allocation}
  10734. \label{sec:expose-allocation}
  10735. The pass \code{expose\_allocation} lowers tuple creation into a
  10736. conditional call to the collector followed by allocating the
  10737. appropriate amount of memory and initializing it. We choose to place
  10738. the \code{expose\_allocation} pass before
  10739. \code{remove\_complex\_operands} because the code generated by
  10740. \code{expose\_allocation} contains complex operands.
  10741. The output of \code{expose\_allocation} is a language \LangAlloc{}
  10742. that extends \LangVec{} with new forms that we use in the translation
  10743. of tuple creation.
  10744. %
  10745. {\if\edition\racketEd
  10746. \[
  10747. \begin{array}{lcl}
  10748. \Exp &::=& \cdots
  10749. \MID (\key{collect} \,\itm{int})
  10750. \MID (\key{allocate} \,\itm{int}\,\itm{type})
  10751. \MID (\key{global-value} \,\itm{name})
  10752. \end{array}
  10753. \]
  10754. \fi}
  10755. {\if\edition\pythonEd
  10756. \[
  10757. \begin{array}{lcl}
  10758. \Exp &::=& \cdots\\
  10759. &\MID& \key{collect}(\itm{int})
  10760. \MID \key{allocate}(\itm{int},\itm{type})
  10761. \MID \key{global\_value}(\itm{name}) \\
  10762. &\MID& \key{begin:} ~ \Stmt^{*} ~ \Exp \\
  10763. \Stmt &::= & \CASSIGN{\CPUT{\Exp}{\itm{int}}}{\Exp}
  10764. \end{array}
  10765. \]
  10766. \fi}
  10767. The \CCOLLECT{$n$} form runs the garbage collector, requesting that it
  10768. make sure that there are $n$ bytes ready to be allocated. During
  10769. instruction selection, the \CCOLLECT{$n$} form will become a call to
  10770. the \code{collect} function in \code{runtime.c}.
  10771. %
  10772. The \CALLOCATE{$n$}{$T$} form obtains memory for $n$ elements (and
  10773. space at the front for the 64 bit tag), but the elements are not
  10774. initialized. \index{subject}{allocate} The $T$ parameter is the type
  10775. of the tuple:
  10776. %
  10777. \VECTY{\racket{$\Type_1 \ldots \Type_n$}\python{$\Type_1, \ldots, \Type_n$}}
  10778. %
  10779. where $\Type_i$ is the type of the $i$th element in the tuple. The
  10780. \CGLOBALVALUE{\itm{name}} form reads the value of a global variable, such
  10781. as \code{free\_ptr}.
  10782. %
  10783. \python{The \code{begin} form is an expression that executes a
  10784. sequence of statements and then produces the value of the expression
  10785. at the end.}
  10786. The following shows the transformation of tuple creation into 1) a
  10787. sequence of temporary variables bindings for the initializing
  10788. expressions, 2) a conditional call to \code{collect}, 3) a call to
  10789. \code{allocate}, and 4) the initialization of the tuple. The
  10790. \itm{len} placeholder refers to the length of the tuple and
  10791. \itm{bytes} is how many total bytes need to be allocated for the
  10792. tuple, which is 8 for the tag plus \itm{len} times 8.
  10793. %
  10794. \python{The \itm{type} needed for the second argument of the
  10795. \code{allocate} form can be obtained from the \code{has\_type} field
  10796. of the tuple AST node, which is stored there by running the type
  10797. checker for \LangVec{} immediately before this pass.}
  10798. %
  10799. \begin{center}
  10800. \begin{minipage}{\textwidth}
  10801. {\if\edition\racketEd
  10802. \begin{lstlisting}
  10803. (has-type (vector |$e_0 \ldots e_{n-1}$|) |\itm{type}|)
  10804. |$\Longrightarrow$|
  10805. (let ([|$x_0$| |$e_0$|]) ... (let ([|$x_{n-1}$| |$e_{n-1}$|])
  10806. (let ([_ (if (< (+ (global-value free_ptr) |\itm{bytes}|)
  10807. (global-value fromspace_end))
  10808. (void)
  10809. (collect |\itm{bytes}|))])
  10810. (let ([|$v$| (allocate |\itm{len}| |\itm{type}|)])
  10811. (let ([_ (vector-set! |$v$| |$0$| |$x_0$|)]) ...
  10812. (let ([_ (vector-set! |$v$| |$n-1$| |$x_{n-1}$|)])
  10813. |$v$|) ... )))) ...)
  10814. \end{lstlisting}
  10815. \fi}
  10816. {\if\edition\pythonEd
  10817. \begin{lstlisting}
  10818. (|$e_0$|, |$\ldots$|, |$e_{n-1}$|)
  10819. |$\Longrightarrow$|
  10820. begin:
  10821. |$x_0$| = |$e_0$|
  10822. |$\vdots$|
  10823. |$x_{n-1}$| = |$e_{n-1}$|
  10824. if global_value(free_ptr) + |\itm{bytes}| < global_value(fromspace_end):
  10825. 0
  10826. else:
  10827. collect(|\itm{bytes}|)
  10828. |$v$| = allocate(|\itm{len}|, |\itm{type}|)
  10829. |$v$|[0] = |$x_0$|
  10830. |$\vdots$|
  10831. |$v$|[|$n-1$|] = |$x_{n-1}$|
  10832. |$v$|
  10833. \end{lstlisting}
  10834. \fi}
  10835. \end{minipage}
  10836. \end{center}
  10837. %
  10838. \noindent The sequencing of the initializing expressions
  10839. $e_0,\ldots,e_{n-1}$ prior to the \code{allocate} is important, as
  10840. they may trigger garbage collection and we cannot have an allocated
  10841. but uninitialized tuple on the heap during a collection.
  10842. Figure~\ref{fig:expose-alloc-output} shows the output of the
  10843. \code{expose\_allocation} pass on our running example.
  10844. \begin{figure}[tbp]
  10845. % tests/s2_17.rkt
  10846. {\if\edition\racketEd
  10847. \begin{lstlisting}
  10848. (vector-ref
  10849. (vector-ref
  10850. (let ([vecinit7976
  10851. (let ([vecinit7972 42])
  10852. (let ([collectret7974
  10853. (if (< (+ (global-value free_ptr) 16)
  10854. (global-value fromspace_end))
  10855. (void)
  10856. (collect 16)
  10857. )])
  10858. (let ([alloc7971 (allocate 1 (Vector Integer))])
  10859. (let ([initret7973 (vector-set! alloc7971 0 vecinit7972)])
  10860. alloc7971))))])
  10861. (let ([collectret7978
  10862. (if (< (+ (global-value free_ptr) 16)
  10863. (global-value fromspace_end))
  10864. (void)
  10865. (collect 16)
  10866. )])
  10867. (let ([alloc7975 (allocate 1 (Vector (Vector Integer)))])
  10868. (let ([initret7977 (vector-set! alloc7975 0 vecinit7976)])
  10869. alloc7975))))
  10870. 0)
  10871. 0)
  10872. \end{lstlisting}
  10873. \fi}
  10874. {\if\edition\pythonEd
  10875. \begin{lstlisting}
  10876. print( |$T_1$|[0][0] )
  10877. \end{lstlisting}
  10878. where $T_1$ is
  10879. \begin{lstlisting}
  10880. begin:
  10881. tmp.1 = |$T_2$|
  10882. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10883. 0
  10884. else:
  10885. collect(16)
  10886. tmp.2 = allocate(1, TupleType(TupleType([int])))
  10887. tmp.2[0] = tmp.1
  10888. tmp.2
  10889. \end{lstlisting}
  10890. and $T_2$ is
  10891. \begin{lstlisting}
  10892. begin:
  10893. tmp.3 = 42
  10894. if global_value(free_ptr) + 16 < global_value(fromspace_end):
  10895. 0
  10896. else:
  10897. collect(16)
  10898. tmp.4 = allocate(1, TupleType([int]))
  10899. tmp.4[0] = tmp.3
  10900. tmp.4
  10901. \end{lstlisting}
  10902. \fi}
  10903. \caption{Output of the \code{expose\_allocation} pass.}
  10904. \label{fig:expose-alloc-output}
  10905. \end{figure}
  10906. \section{Remove Complex Operands}
  10907. \label{sec:remove-complex-opera-Lvec}
  10908. {\if\edition\racketEd
  10909. %
  10910. The forms \code{collect}, \code{allocate}, and \code{global\_value}
  10911. should be treated as complex operands.
  10912. %
  10913. \fi}
  10914. %
  10915. {\if\edition\pythonEd
  10916. %
  10917. The expressions \code{allocate}, \code{global\_value}, \code{begin},
  10918. and tuple access should be treated as complex operands. The
  10919. sub-expressions of tuple access must be atomic.
  10920. %
  10921. \fi}
  10922. %% A new case for
  10923. %% \code{HasType} is needed and the case for \code{Prim} needs to be
  10924. %% handled carefully to prevent the \code{Prim} node from being separated
  10925. %% from its enclosing \code{HasType}.
  10926. Figure~\ref{fig:Lvec-anf-syntax}
  10927. shows the grammar for the output language \LangAllocANF{} of this
  10928. pass, which is \LangAlloc{} in monadic normal form.
  10929. \newcommand{\LtupMonadASTPython}{
  10930. \begin{array}{rcl}
  10931. \Exp &::=& \GET{\Atm}{\Atm} \\
  10932. &\MID& \LEN{\Atm}\\
  10933. &\MID& \ALLOCATE{\Int}{\Type}
  10934. \MID \GLOBALVALUE{\Var} \\
  10935. \Stmt{} &::=& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm} \\
  10936. &\MID& \COLLECT{\Int}
  10937. \end{array}
  10938. }
  10939. \begin{figure}[tp]
  10940. \centering
  10941. \fbox{
  10942. \begin{minipage}{0.96\textwidth}
  10943. \small
  10944. {\if\edition\racketEd
  10945. \[
  10946. \begin{array}{rcl}
  10947. \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  10948. \MID \VOID{} } \\
  10949. \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  10950. &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  10951. &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  10952. &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  10953. &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  10954. &\MID& \COLLECT{\Int} \RP \MID \ALLOCATE{\Int}{\Type}
  10955. \MID \GLOBALVALUE{\Var}\\
  10956. % &\MID& \LP\key{HasType}~\Exp~\Type\RP \\
  10957. \LangAllocANFM{} &::=& \gray{ \PROGRAM{\code{'()}}{\Exp} }
  10958. \end{array}
  10959. \]
  10960. \fi}
  10961. {\if\edition\pythonEd
  10962. \[
  10963. \begin{array}{l}
  10964. \gray{\LvarMonadASTPython} \\ \hline
  10965. \gray{\LifMonadASTPython} \\ \hline
  10966. \gray{\LwhileMonadASTPython} \\ \hline
  10967. \LtupMonadASTPython \\
  10968. \begin{array}{rcl}
  10969. \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10970. \end{array}
  10971. \end{array}
  10972. %% \begin{array}{lcl}
  10973. %% \itm{binaryop} &::=& \code{Add()} \MID \code{Sub()} \\
  10974. %% \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  10975. %% \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()} \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \MID \code{Is()} \\
  10976. %% \itm{unaryop} &::=& \code{USub()} \MID \code{Not()} \\
  10977. %% \itm{bool} &::=& \code{True} \MID \code{False} \\
  10978. %% \Atm &::=& \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}} \\
  10979. %% \Exp &::=& \Atm \MID \READ{} \MID \\
  10980. %% &\MID& \BINOP{\Atm}{\itm{binaryop}}{\Atm}
  10981. %% \MID \UNIOP{\itm{unaryop}}{\Atm}\\
  10982. %% &\MID& \CMP{\Atm}{\itm{cmp}}{\Atm} \\
  10983. %% % \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp} \\ % removed by RCO
  10984. %% &\MID& \IF{\Exp}{\Exp}{\Exp} \\
  10985. %% &\MID& \GET{\Atm}{\Atm} \\
  10986. %% &\MID& \LEN{\Exp}\\
  10987. %% &\MID& \ALLOCATE{\Int}{\Type}
  10988. %% \MID \GLOBALVALUE{\Var}\RP\\
  10989. %% &\MID& \BEGIN{\Stmt^{*}}{\Atm} \\ % can use this in place of \LET;
  10990. %% % why have \LET?
  10991. %% \Stmt{} &::=& \PRINT{\Atm} \MID \EXPR{\Exp} \\
  10992. %% &\MID& \ASSIGN{\VAR{\Var}}{\Exp} \\
  10993. %% &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Exp} \\
  10994. %% &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}\\
  10995. %% &\MID& \WHILESTMT{\Exp}{\Stmt^{+}}
  10996. %% \MID \COLLECT{\Int} \\
  10997. %% \LangAllocANFM{} &::=& \PROGRAM{\code{'()}}{\Stmt^{*}}
  10998. %% \end{array}
  10999. \]
  11000. \fi}
  11001. \end{minipage}
  11002. }
  11003. \caption{\LangAllocANF{} is \LangAlloc{} in monadic normal form.}
  11004. \label{fig:Lvec-anf-syntax}
  11005. \end{figure}
  11006. \section{Explicate Control and the \LangCVec{} language}
  11007. \label{sec:explicate-control-r3}
  11008. \newcommand{\CtupASTRacket}{
  11009. \begin{array}{lcl}
  11010. \Exp &::= & \LP\key{Allocate} \,\itm{int}\,\itm{type}\RP \\
  11011. &\MID& \VECREF{\Atm}{\INT{\Int}} \\
  11012. &\MID& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11013. &\MID& \VECLEN{\Atm} \\
  11014. &\MID& \GLOBALVALUE{\Var} \\
  11015. \Stmt &::=& \VECSET{\Atm}{\INT{\Int}}{\Atm} \\
  11016. &\MID& \LP\key{Collect} \,\itm{int}\RP
  11017. \end{array}
  11018. }
  11019. \newcommand{\CtupASTPython}{
  11020. \begin{array}{lcl}
  11021. \Exp &::= & \GET{\Atm}{\Atm} \MID \ALLOCATE{\Int}{\Type} \\
  11022. &\MID& \GLOBALVALUE{\Var} \MID \LEN{\Atm} \\
  11023. \Stmt &::=& \COLLECT{\Int} \\
  11024. &\MID& \ASSIGN{\PUT{\Atm}{\Atm}}{\Atm}
  11025. \end{array}
  11026. }
  11027. \begin{figure}[tp]
  11028. \fbox{
  11029. \begin{minipage}{0.96\textwidth}
  11030. \small
  11031. {\if\edition\racketEd
  11032. \[
  11033. \begin{array}{l}
  11034. \gray{\CvarASTRacket} \\ \hline
  11035. \gray{\CifASTRacket} \\ \hline
  11036. \gray{\CloopASTRacket} \\ \hline
  11037. \CtupASTRacket \\
  11038. \begin{array}{lcl}
  11039. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  11040. \end{array}
  11041. \end{array}
  11042. \]
  11043. \fi}
  11044. {\if\edition\pythonEd
  11045. \[
  11046. \begin{array}{l}
  11047. \gray{\CifASTPython} \\ \hline
  11048. \CtupASTPython \\
  11049. \begin{array}{lcl}
  11050. \LangCVecM{} & ::= & \CPROGRAM{\itm{info}}{\LC\itm{label}\key{:}\,\Stmt^{*}, \ldots \RC}
  11051. \end{array}
  11052. \end{array}
  11053. \]
  11054. \fi}
  11055. \end{minipage}
  11056. }
  11057. \caption{The abstract syntax of \LangCVec{}, extending
  11058. \racket{\LangCLoop{} (Figure~\ref{fig:c7-syntax})}\python{\LangCIf{}
  11059. (Figure~\ref{fig:c1-syntax})}.}
  11060. \label{fig:c2-syntax}
  11061. \end{figure}
  11062. The output of \code{explicate\_control} is a program in the
  11063. intermediate language \LangCVec{}, whose abstract syntax is defined in
  11064. Figure~\ref{fig:c2-syntax}.
  11065. %
  11066. \racket{(The concrete syntax is defined in
  11067. Figure~\ref{fig:c2-concrete-syntax} of the Appendix.)}
  11068. %
  11069. The new expressions of \LangCVec{} include \key{allocate},
  11070. %
  11071. \racket{\key{vector-ref}, and \key{vector-set!},}
  11072. %
  11073. \python{accessing tuple elements,}
  11074. %
  11075. and \key{global\_value}.
  11076. %
  11077. \python{\LangCVec{} also includes the \code{collect} statement and
  11078. assignment to a tuple element.}
  11079. %
  11080. \racket{\LangCVec{} also includes the new \code{collect} statement.}
  11081. %
  11082. The \code{explicate\_control} pass can treat these new forms much like
  11083. the other forms that we've already encoutered.
  11084. \section{Select Instructions and the \LangXGlobal{} Language}
  11085. \label{sec:select-instructions-gc}
  11086. \index{subject}{instruction selection}
  11087. %% void (rep as zero)
  11088. %% allocate
  11089. %% collect (callq collect)
  11090. %% vector-ref
  11091. %% vector-set!
  11092. %% vector-length
  11093. %% global (postpone)
  11094. In this pass we generate x86 code for most of the new operations that
  11095. were needed to compile tuples, including \code{Allocate},
  11096. \code{Collect}, and accessing tuple elements.
  11097. %
  11098. We compile \code{GlobalValue} to \code{Global} because the later has a
  11099. different concrete syntax (see Figures~\ref{fig:x86-2-concrete} and
  11100. \ref{fig:x86-2}). \index{subject}{x86}
  11101. The tuple read and write forms translate into \code{movq}
  11102. instructions. (The plus one in the offset is to get past the tag at
  11103. the beginning of the tuple representation.)
  11104. %
  11105. \begin{center}
  11106. \begin{minipage}{\textwidth}
  11107. {\if\edition\racketEd
  11108. \begin{lstlisting}
  11109. |$\itm{lhs}$| = (vector-ref |$\itm{tup}$| |$n$|);
  11110. |$\Longrightarrow$|
  11111. movq |$\itm{tup}'$|, %r11
  11112. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11113. |$\itm{lhs}$| = (vector-set! |$\itm{tup}$| |$n$| |$\itm{rhs}$|);
  11114. |$\Longrightarrow$|
  11115. movq |$\itm{tup}'$|, %r11
  11116. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11117. movq $0, |$\itm{lhs'}$|
  11118. \end{lstlisting}
  11119. \fi}
  11120. {\if\edition\pythonEd
  11121. \begin{lstlisting}
  11122. |$\itm{lhs}$| = |$\itm{tup}$|[|$n$|]
  11123. |$\Longrightarrow$|
  11124. movq |$\itm{tup}'$|, %r11
  11125. movq |$8(n+1)$|(%r11), |$\itm{lhs'}$|
  11126. |$\itm{tup}$|[|$n$|] = |$\itm{rhs}$|
  11127. |$\Longrightarrow$|
  11128. movq |$\itm{tup}'$|, %r11
  11129. movq |$\itm{rhs}'$|, |$8(n+1)$|(%r11)
  11130. \end{lstlisting}
  11131. \fi}
  11132. \end{minipage}
  11133. \end{center}
  11134. \racket{The $\itm{lhs}'$, $\itm{tup}'$, and $\itm{rhs}'$}
  11135. \python{The $\itm{tup}'$ and $\itm{rhs}'$}
  11136. are obtained by translating from \LangCVec{} to x86.
  11137. %
  11138. The move of $\itm{tup}'$ to
  11139. register \code{r11} ensures that offset expression
  11140. \code{$-8(n+1)$(\%r11)} contains a register operand. This requires
  11141. removing \code{r11} from consideration by the register allocating.
  11142. Why not use \code{rax} instead of \code{r11}? Suppose we instead used
  11143. \code{rax}. Then the generated code for tuple assignment would be
  11144. \begin{lstlisting}
  11145. movq |$\itm{tup}'$|, %rax
  11146. movq |$\itm{rhs}'$|, |$8(n+1)$|(%rax)
  11147. \end{lstlisting}
  11148. Next, suppose that $\itm{rhs}'$ ends up as a stack location, so
  11149. \code{patch\_instructions} would insert a move through \code{rax}
  11150. as follows.
  11151. \begin{lstlisting}
  11152. movq |$\itm{tup}'$|, %rax
  11153. movq |$\itm{rhs}'$|, %rax
  11154. movq %rax, |$8(n+1)$|(%rax)
  11155. \end{lstlisting}
  11156. But the above sequence of instructions does not work because we're
  11157. trying to use \code{rax} for two different values ($\itm{tup}'$ and
  11158. $\itm{rhs}'$) at the same time!
  11159. The \racket{\code{vector-length}}\python{\code{len}} operation should
  11160. be translated into a sequence of instructions that read the tag of the
  11161. tuple and extract the six bits that represent the tuple length, which
  11162. are the bits starting at index 1 and going up to and including bit 6.
  11163. The x86 instructions \code{andq} (for bitwise-and) and \code{sarq}
  11164. (shift right) can be used to accomplish this.
  11165. We compile the \code{allocate} form to operations on the
  11166. \code{free\_ptr}, as shown below. This approach is called \emph{inline
  11167. allocation} as it implements allocation without a function call, by
  11168. simply bumping the allocation pointer. It is much more efficient than
  11169. calling a function for each allocation. The address in the
  11170. \code{free\_ptr} is the next free address in the FromSpace, so we copy
  11171. it into \code{r11} and then move it forward by enough space for the
  11172. tuple being allocated, which is $8(\itm{len}+1)$ bytes because each
  11173. element is 8 bytes (64 bits) and we use 8 bytes for the tag. We then
  11174. initialize the \itm{tag} and finally copy the address in \code{r11} to
  11175. the left-hand-side. Refer to Figure~\ref{fig:tuple-rep} to see how the
  11176. tag is organized.
  11177. %
  11178. \racket{We recommend using the Racket operations
  11179. \code{bitwise-ior} and \code{arithmetic-shift} to compute the tag
  11180. during compilation.}
  11181. %
  11182. \python{We recommend using the bitwise-or operator \code{|} and the
  11183. shift-left operator \code{<<} to compute the tag during
  11184. compilation.}
  11185. %
  11186. The type annotation in the \code{allocate} form is used to determine
  11187. the pointer mask region of the tag.
  11188. %
  11189. The addressing mode \verb!free_ptr(%rip)! essentially stands for the
  11190. address of the \code{free\_ptr} global variable but uses a special
  11191. instruction-pointer relative addressing mode of the x86-64 processor.
  11192. In particular, the assembler computes the distance $d$ between the
  11193. address of \code{free\_ptr} and where the \code{rip} would be at that
  11194. moment and then changes the \code{free\_ptr(\%rip)} argument to
  11195. \code{$d$(\%rip)}, which at runtime will compute the address of
  11196. \code{free\_ptr}.
  11197. %
  11198. {\if\edition\racketEd
  11199. \begin{lstlisting}
  11200. |$\itm{lhs}$| = (allocate |$\itm{len}$| (Vector |$\itm{type} \ldots$|));
  11201. |$\Longrightarrow$|
  11202. movq free_ptr(%rip), %r11
  11203. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11204. movq $|$\itm{tag}$|, 0(%r11)
  11205. movq %r11, |$\itm{lhs}'$|
  11206. \end{lstlisting}
  11207. \fi}
  11208. {\if\edition\pythonEd
  11209. \begin{lstlisting}
  11210. |$\itm{lhs}$| = allocate(|$\itm{len}$|, TupleType([|$\itm{type}, \ldots$])|);
  11211. |$\Longrightarrow$|
  11212. movq free_ptr(%rip), %r11
  11213. addq |$8(\itm{len}+1)$|, free_ptr(%rip)
  11214. movq $|$\itm{tag}$|, 0(%r11)
  11215. movq %r11, |$\itm{lhs}'$|
  11216. \end{lstlisting}
  11217. \fi}
  11218. The \code{collect} form is compiled to a call to the \code{collect}
  11219. function in the runtime. The arguments to \code{collect} are 1) the
  11220. top of the root stack and 2) the number of bytes that need to be
  11221. allocated. We use another dedicated register, \code{r15}, to
  11222. store the pointer to the top of the root stack. So \code{r15} is not
  11223. available for use by the register allocator.
  11224. {\if\edition\racketEd
  11225. \begin{lstlisting}
  11226. (collect |$\itm{bytes}$|)
  11227. |$\Longrightarrow$|
  11228. movq %r15, %rdi
  11229. movq $|\itm{bytes}|, %rsi
  11230. callq collect
  11231. \end{lstlisting}
  11232. \fi}
  11233. {\if\edition\pythonEd
  11234. \begin{lstlisting}
  11235. collect(|$\itm{bytes}$|)
  11236. |$\Longrightarrow$|
  11237. movq %r15, %rdi
  11238. movq $|\itm{bytes}|, %rsi
  11239. callq collect
  11240. \end{lstlisting}
  11241. \fi}
  11242. \begin{figure}[tp]
  11243. \fbox{
  11244. \begin{minipage}{0.96\textwidth}
  11245. \[
  11246. \begin{array}{lcl}
  11247. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  11248. \LangXGlobalM{} &::= & \gray{ \key{.globl main} }\\
  11249. & & \gray{ \key{main:} \; \Instr^{*} }
  11250. \end{array}
  11251. \]
  11252. \end{minipage}
  11253. }
  11254. \caption{The concrete syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1-concrete}).}
  11255. \label{fig:x86-2-concrete}
  11256. \end{figure}
  11257. \begin{figure}[tp]
  11258. \fbox{
  11259. \begin{minipage}{0.96\textwidth}
  11260. \small
  11261. \[
  11262. \begin{array}{lcl}
  11263. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  11264. \MID \BYTEREG{\Reg}} \\
  11265. &\MID& \GLOBAL{\Var} \\
  11266. \LangXGlobalM{} &::= & \gray{ \XPROGRAM{\itm{info}}{\LP\LP\itm{label} \,\key{.}\, \Block \RP\ldots\RP} }
  11267. \end{array}
  11268. \]
  11269. \end{minipage}
  11270. }
  11271. \caption{The abstract syntax of \LangXGlobal{} (extends \LangXIf{} of Figure~\ref{fig:x86-1}).}
  11272. \label{fig:x86-2}
  11273. \end{figure}
  11274. The concrete and abstract syntax of the \LangXGlobal{} language is
  11275. defined in Figures~\ref{fig:x86-2-concrete} and \ref{fig:x86-2}. It
  11276. differs from \LangXIf{} just in the addition of global variables.
  11277. %
  11278. Figure~\ref{fig:select-instr-output-gc} shows the output of the
  11279. \code{select\_instructions} pass on the running example.
  11280. \begin{figure}[tbp]
  11281. \centering
  11282. % tests/s2_17.rkt
  11283. \begin{minipage}[t]{0.5\textwidth}
  11284. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11285. block35:
  11286. movq free_ptr(%rip), alloc9024
  11287. addq $16, free_ptr(%rip)
  11288. movq alloc9024, %r11
  11289. movq $131, 0(%r11)
  11290. movq alloc9024, %r11
  11291. movq vecinit9025, 8(%r11)
  11292. movq $0, initret9026
  11293. movq alloc9024, %r11
  11294. movq 8(%r11), tmp9034
  11295. movq tmp9034, %r11
  11296. movq 8(%r11), %rax
  11297. jmp conclusion
  11298. block36:
  11299. movq $0, collectret9027
  11300. jmp block35
  11301. block38:
  11302. movq free_ptr(%rip), alloc9020
  11303. addq $16, free_ptr(%rip)
  11304. movq alloc9020, %r11
  11305. movq $3, 0(%r11)
  11306. movq alloc9020, %r11
  11307. movq vecinit9021, 8(%r11)
  11308. movq $0, initret9022
  11309. movq alloc9020, vecinit9025
  11310. movq free_ptr(%rip), tmp9031
  11311. movq tmp9031, tmp9032
  11312. addq $16, tmp9032
  11313. movq fromspace_end(%rip), tmp9033
  11314. cmpq tmp9033, tmp9032
  11315. jl block36
  11316. jmp block37
  11317. block37:
  11318. movq %r15, %rdi
  11319. movq $16, %rsi
  11320. callq 'collect
  11321. jmp block35
  11322. block39:
  11323. movq $0, collectret9023
  11324. jmp block38
  11325. \end{lstlisting}
  11326. \end{minipage}
  11327. \begin{minipage}[t]{0.45\textwidth}
  11328. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11329. start:
  11330. movq $42, vecinit9021
  11331. movq free_ptr(%rip), tmp9028
  11332. movq tmp9028, tmp9029
  11333. addq $16, tmp9029
  11334. movq fromspace_end(%rip), tmp9030
  11335. cmpq tmp9030, tmp9029
  11336. jl block39
  11337. jmp block40
  11338. block40:
  11339. movq %r15, %rdi
  11340. movq $16, %rsi
  11341. callq 'collect
  11342. jmp block38
  11343. \end{lstlisting}
  11344. \end{minipage}
  11345. \caption{Output of the \code{select\_instructions} pass.}
  11346. \label{fig:select-instr-output-gc}
  11347. \end{figure}
  11348. \clearpage
  11349. \section{Register Allocation}
  11350. \label{sec:reg-alloc-gc}
  11351. \index{subject}{register allocation}
  11352. As discussed earlier in this chapter, the garbage collector needs to
  11353. access all the pointers in the root set, that is, all variables that
  11354. are tuples. It will be the responsibility of the register allocator
  11355. to make sure that:
  11356. \begin{enumerate}
  11357. \item the root stack is used for spilling tuple-typed variables, and
  11358. \item if a tuple-typed variable is live during a call to the
  11359. collector, it must be spilled to ensure it is visible to the
  11360. collector.
  11361. \end{enumerate}
  11362. The later responsibility can be handled during construction of the
  11363. interference graph, by adding interference edges between the call-live
  11364. tuple-typed variables and all the callee-saved registers. (They
  11365. already interfere with the caller-saved registers.)
  11366. %
  11367. \racket{The type information for variables is in the \code{Program}
  11368. form, so we recommend adding another parameter to the
  11369. \code{build\_interference} function to communicate this alist.}
  11370. %
  11371. \python{The type information for variables is generated by the type
  11372. checker for \LangCVec{}, stored a field named \code{var\_types} in
  11373. the \code{CProgram} AST mode. You'll need to propagate that
  11374. information so that it is available in this pass.}
  11375. The spilling of tuple-typed variables to the root stack can be handled
  11376. after graph coloring, when choosing how to assign the colors
  11377. (integers) to registers and stack locations. The
  11378. \racket{\code{Program}}\python{\code{CProgram}} output of this pass
  11379. changes to also record the number of spills to the root stack.
  11380. % build-interference
  11381. %
  11382. % callq
  11383. % extra parameter for var->type assoc. list
  11384. % update 'program' and 'if'
  11385. % allocate-registers
  11386. % allocate spilled vectors to the rootstack
  11387. % don't change color-graph
  11388. % TODO:
  11389. %\section{Patch Instructions}
  11390. %[mention that global variables are memory references]
  11391. \section{Prelude and Conclusion}
  11392. \label{sec:print-x86-gc}
  11393. \label{sec:prelude-conclusion-x86-gc}
  11394. \index{subject}{prelude}\index{subject}{conclusion}
  11395. Figure~\ref{fig:print-x86-output-gc} shows the output of the
  11396. \code{prelude\_and\_conclusion} pass on the running example. In the
  11397. prelude and conclusion of the \code{main} function, we allocate space
  11398. on the root stack to make room for the spills of tuple-typed
  11399. variables. We do so by bumping the root stack
  11400. pointer (\code{r15}) taking care that the root stack grows up instead of down. For the running
  11401. example, there was just one spill so we increment \code{r15} by 8
  11402. bytes. In the conclusion we decrement \code{r15} by 8 bytes.
  11403. One issue that deserves special care is that there may be a call to
  11404. \code{collect} prior to the initializing assignments for all the
  11405. variables in the root stack. We do not want the garbage collector to
  11406. accidentally think that some uninitialized variable is a pointer that
  11407. needs to be followed. Thus, we zero-out all locations on the root
  11408. stack in the prelude of \code{main}. In
  11409. Figure~\ref{fig:print-x86-output-gc}, the instruction
  11410. %
  11411. \lstinline{movq $0, 0(%r15)}
  11412. %
  11413. is sufficient to accomplish this task because there is only one spill.
  11414. In general, we have to clear as many words as there are spills of
  11415. tuple-typed variables. The garbage collector tests each root to see
  11416. if it is null prior to dereferencing it.
  11417. \begin{figure}[htbp]
  11418. % TODO: Python Version -Jeremy
  11419. \begin{minipage}[t]{0.5\textwidth}
  11420. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11421. block35:
  11422. movq free_ptr(%rip), %rcx
  11423. addq $16, free_ptr(%rip)
  11424. movq %rcx, %r11
  11425. movq $131, 0(%r11)
  11426. movq %rcx, %r11
  11427. movq -8(%r15), %rax
  11428. movq %rax, 8(%r11)
  11429. movq $0, %rdx
  11430. movq %rcx, %r11
  11431. movq 8(%r11), %rcx
  11432. movq %rcx, %r11
  11433. movq 8(%r11), %rax
  11434. jmp conclusion
  11435. block36:
  11436. movq $0, %rcx
  11437. jmp block35
  11438. block38:
  11439. movq free_ptr(%rip), %rcx
  11440. addq $16, free_ptr(%rip)
  11441. movq %rcx, %r11
  11442. movq $3, 0(%r11)
  11443. movq %rcx, %r11
  11444. movq %rbx, 8(%r11)
  11445. movq $0, %rdx
  11446. movq %rcx, -8(%r15)
  11447. movq free_ptr(%rip), %rcx
  11448. addq $16, %rcx
  11449. movq fromspace_end(%rip), %rdx
  11450. cmpq %rdx, %rcx
  11451. jl block36
  11452. movq %r15, %rdi
  11453. movq $16, %rsi
  11454. callq collect
  11455. jmp block35
  11456. block39:
  11457. movq $0, %rcx
  11458. jmp block38
  11459. \end{lstlisting}
  11460. \end{minipage}
  11461. \begin{minipage}[t]{0.45\textwidth}
  11462. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  11463. start:
  11464. movq $42, %rbx
  11465. movq free_ptr(%rip), %rdx
  11466. addq $16, %rdx
  11467. movq fromspace_end(%rip), %rcx
  11468. cmpq %rcx, %rdx
  11469. jl block39
  11470. movq %r15, %rdi
  11471. movq $16, %rsi
  11472. callq collect
  11473. jmp block38
  11474. .globl main
  11475. main:
  11476. pushq %rbp
  11477. movq %rsp, %rbp
  11478. pushq %r13
  11479. pushq %r12
  11480. pushq %rbx
  11481. pushq %r14
  11482. subq $0, %rsp
  11483. movq $16384, %rdi
  11484. movq $16384, %rsi
  11485. callq initialize
  11486. movq rootstack_begin(%rip), %r15
  11487. movq $0, 0(%r15)
  11488. addq $8, %r15
  11489. jmp start
  11490. conclusion:
  11491. subq $8, %r15
  11492. addq $0, %rsp
  11493. popq %r14
  11494. popq %rbx
  11495. popq %r12
  11496. popq %r13
  11497. popq %rbp
  11498. retq
  11499. \end{lstlisting}
  11500. \end{minipage}
  11501. \caption{Output of the \code{prelude\_and\_conclusion} pass.}
  11502. \label{fig:print-x86-output-gc}
  11503. \end{figure}
  11504. \begin{figure}[tbp]
  11505. \begin{tikzpicture}[baseline=(current bounding box.center)]
  11506. \node (Lvec) at (0,2) {\large \LangVec{}};
  11507. \node (Lvec-2) at (3,2) {\large \LangVec{}};
  11508. \node (Lvec-3) at (6,2) {\large \LangVec{}};
  11509. \node (Lvec-4) at (9,2) {\large \LangVec{}};
  11510. \node (Lvec-5) at (9,0) {\large \LangAllocANF{}};
  11511. \node (C2-4) at (3,0) {\large \LangCVec{}};
  11512. \node (x86-2) at (3,-2) {\large \LangXGlobalVar{}};
  11513. \node (x86-2-1) at (3,-4) {\large \LangXGlobalVar{}};
  11514. \node (x86-2-2) at (6,-4) {\large \LangXGlobalVar{}};
  11515. \node (x86-3) at (6,-2) {\large \LangXGlobalVar{}};
  11516. \node (x86-4) at (9,-2) {\large \LangXGlobal{}};
  11517. \node (x86-5) at (9,-4) {\large \LangXGlobal{}};
  11518. %\path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize type-check} (Lvec-2);
  11519. \path[->,bend left=15] (Lvec) edge [above] node {\ttfamily\footnotesize shrink} (Lvec-2);
  11520. \path[->,bend left=15] (Lvec-2) edge [above] node {\ttfamily\footnotesize uniquify} (Lvec-3);
  11521. \path[->,bend left=15] (Lvec-3) edge [above] node {\ttfamily\footnotesize expose\_alloc.} (Lvec-4);
  11522. \path[->,bend left=15] (Lvec-4) edge [above] node {\ttfamily\footnotesize remove\_complex.} (Lvec-5);
  11523. \path[->,bend left=10] (Lvec-5) edge [above] node {\ttfamily\footnotesize explicate\_control} (C2-4);
  11524. \path[->,bend left=15] (C2-4) edge [right] node {\ttfamily\footnotesize select\_instr.} (x86-2);
  11525. \path[->,bend right=15] (x86-2) edge [left] node {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  11526. \path[->,bend right=15] (x86-2-1) edge [below] node {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  11527. \path[->,bend right=15] (x86-2-2) edge [right] node {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  11528. \path[->,bend left=15] (x86-3) edge [above] node {\ttfamily\footnotesize patch\_instr.} (x86-4);
  11529. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  11530. \end{tikzpicture}
  11531. \caption{Diagram of the passes for \LangVec{}, a language with tuples.}
  11532. \label{fig:Lvec-passes}
  11533. \end{figure}
  11534. Figure~\ref{fig:Lvec-passes} gives an overview of all the passes needed
  11535. for the compilation of \LangVec{}.
  11536. \clearpage
  11537. {\if\edition\racketEd
  11538. \section{Challenge: Simple Structures}
  11539. \label{sec:simple-structures}
  11540. \index{subject}{struct}
  11541. \index{subject}{structure}
  11542. The language \LangStruct{} extends \LangVec{} with support for simple
  11543. structures. Its concrete syntax is defined in
  11544. Figure~\ref{fig:Lstruct-concrete-syntax} and the abstract syntax is in
  11545. Figure~\ref{fig:Lstruct-syntax}. Recall that a \code{struct} in Typed
  11546. Racket is a user-defined data type that contains named fields and that
  11547. is heap allocated, similar to a vector. The following is an example of
  11548. a structure definition, in this case the definition of a \code{point}
  11549. type.
  11550. \begin{lstlisting}
  11551. (struct point ([x : Integer] [y : Integer]) #:mutable)
  11552. \end{lstlisting}
  11553. \newcommand{\LstructGrammarRacket}{
  11554. \begin{array}{lcl}
  11555. \Type &::=& \Var \\
  11556. \Exp &::=& (\Var\;\Exp \ldots)\\
  11557. \Def &::=& (\key{struct}\; \Var \; ([\Var \,\key{:}\, \Type] \ldots)\; \code{\#:mutable})\\
  11558. \end{array}
  11559. }
  11560. \newcommand{\LstructASTRacket}{
  11561. \begin{array}{lcl}
  11562. \Type &::=& \VAR{\Var} \\
  11563. \Exp &::=& \APPLY{\Var}{\Exp\ldots} \\
  11564. \Def &::=& \LP\key{StructDef}\; \Var \; \LP\LS\Var \,\key{:}\, \Type\RS \ldots\RP\RP
  11565. \end{array}
  11566. }
  11567. \begin{figure}[tbp]
  11568. \centering
  11569. \fbox{
  11570. \begin{minipage}{0.96\textwidth}
  11571. \[
  11572. \begin{array}{l}
  11573. \gray{\LintGrammarRacket{}} \\ \hline
  11574. \gray{\LvarGrammarRacket{}} \\ \hline
  11575. \gray{\LifGrammarRacket{}} \\ \hline
  11576. \gray{\LwhileGrammarRacket} \\ \hline
  11577. \gray{\LtupGrammarRacket} \\ \hline
  11578. \LstructGrammarRacket \\
  11579. \begin{array}{lcl}
  11580. \LangStruct{} &::=& \Def \ldots \; \Exp
  11581. \end{array}
  11582. \end{array}
  11583. \]
  11584. \end{minipage}
  11585. }
  11586. \caption{The concrete syntax of \LangStruct{}, extending \LangVec{}
  11587. (Figure~\ref{fig:Lvec-concrete-syntax}).}
  11588. \label{fig:Lstruct-concrete-syntax}
  11589. \end{figure}
  11590. \begin{figure}[tbp]
  11591. \centering
  11592. \fbox{
  11593. \begin{minipage}{0.96\textwidth}
  11594. \[
  11595. \begin{array}{l}
  11596. \gray{\LintASTRacket{}} \\ \hline
  11597. \gray{\LvarASTRacket{}} \\ \hline
  11598. \gray{\LifASTRacket{}} \\ \hline
  11599. \gray{\LwhileASTRacket} \\ \hline
  11600. \gray{\LtupASTRacket} \\ \hline
  11601. \LstructASTRacket \\
  11602. \begin{array}{lcl}
  11603. \LangStruct{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  11604. \end{array}
  11605. \end{array}
  11606. \]
  11607. \end{minipage}
  11608. }
  11609. \caption{The abstract syntax of \LangStruct{}, extending \LangVec{}
  11610. (Figure~\ref{fig:Lvec-syntax}).}
  11611. \label{fig:Lstruct-syntax}
  11612. \end{figure}
  11613. An instance of a structure is created using function call syntax, with
  11614. the name of the structure in the function position:
  11615. \begin{lstlisting}
  11616. (point 7 12)
  11617. \end{lstlisting}
  11618. Function-call syntax is also used to read the value in a field of a
  11619. structure. The function name is formed by the structure name, a dash,
  11620. and the field name. The following example uses \code{point-x} and
  11621. \code{point-y} to access the \code{x} and \code{y} fields of two point
  11622. instances.
  11623. \begin{center}
  11624. \begin{lstlisting}
  11625. (let ([pt1 (point 7 12)])
  11626. (let ([pt2 (point 4 3)])
  11627. (+ (- (point-x pt1) (point-x pt2))
  11628. (- (point-y pt1) (point-y pt2)))))
  11629. \end{lstlisting}
  11630. \end{center}
  11631. Similarly, to write to a field of a structure, use its set function,
  11632. whose name starts with \code{set-}, followed by the structure name,
  11633. then a dash, then the field name, and concluded with an exclamation
  11634. mark. The following example uses \code{set-point-x!} to change the
  11635. \code{x} field from \code{7} to \code{42}.
  11636. \begin{center}
  11637. \begin{lstlisting}
  11638. (let ([pt (point 7 12)])
  11639. (let ([_ (set-point-x! pt 42)])
  11640. (point-x pt)))
  11641. \end{lstlisting}
  11642. \end{center}
  11643. \begin{exercise}\normalfont\normalsize
  11644. Create a type checker for \LangStruct{} by extending the type
  11645. checker for \LangVec{}. Extend your compiler with support for simple
  11646. structures, compiling \LangStruct{} to x86 assembly code. Create
  11647. five new test cases that use structures and test your compiler.
  11648. \end{exercise}
  11649. % TODO: create an interpreter for L_struct
  11650. \clearpage
  11651. \section{Challenge: Arrays}
  11652. \label{sec:arrays}
  11653. In Chapter~\ref{ch:Lvec} we studied tuples, that is, sequences of
  11654. elements whose length is determined at compile-time and where each
  11655. element of a tuple may have a different type (they are
  11656. heterogeous). This challenge is also about sequences, but this time
  11657. the length is determined at run-time and all the elements have the same
  11658. type (they are homogeneous). We use the term ``array'' for this later
  11659. kind of sequence.
  11660. The Racket language does not distinguish between tuples and arrays,
  11661. they are both represented by vectors. However, Typed Racket
  11662. distinguishes between tuples and arrays: the \code{Vector} type is for
  11663. tuples and the \code{Vectorof} type is for arrays.
  11664. %
  11665. Figure~\ref{fig:Lvecof-concrete-syntax} defines the concrete syntax
  11666. for \LangArray{}, extending \LangLoop{} with the \code{Vectorof} type
  11667. and the \code{make-vector} primitive operator for creating an array,
  11668. whose arguments are the length of the array and an initial value for
  11669. all the elements in the array. The \code{vector-length},
  11670. \code{vector-ref}, and \code{vector-ref!} operators that we defined
  11671. for tuples become overloaded for use with arrays.
  11672. %
  11673. We also include integer multiplication in \LangArray{}, as it is
  11674. useful in many examples involving arrays such as computing the
  11675. inner-product of two arrays (Figure~\ref{fig:inner-product}).
  11676. \begin{figure}[tp]
  11677. \centering
  11678. \fbox{
  11679. \begin{minipage}{0.96\textwidth}
  11680. \small
  11681. {\if\edition\racketEd
  11682. \[
  11683. \begin{array}{lcl}
  11684. \Type &::=& \ldots \MID \LP \key{Vectorof}~\Type \RP \\
  11685. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  11686. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \MID \CMUL{\Exp}{\Exp}\\
  11687. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  11688. &\MID& \gray{\key{\#t} \MID \key{\#f}
  11689. \MID \LP\key{and}\;\Exp\;\Exp\RP
  11690. \MID \LP\key{or}\;\Exp\;\Exp\RP
  11691. \MID \LP\key{not}\;\Exp\RP } \\
  11692. &\MID& \gray{ \LP\key{eq?}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  11693. &\MID& \gray{ \LP\key{vector}\;\Exp\ldots\RP \MID
  11694. \LP\key{vector-ref}\;\Exp\;\Int\RP} \\
  11695. &\MID& \gray{\LP\key{vector-set!}\;\Exp\;\Int\;\Exp\RP\MID \LP\key{void}\RP
  11696. \MID \LP\Exp \; \Exp\ldots\RP } \\
  11697. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP
  11698. \MID \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp} } \\
  11699. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  11700. \MID \CBEGIN{\Exp\ldots}{\Exp}
  11701. \MID \CWHILE{\Exp}{\Exp} } \\
  11702. &\MID& \CMAKEVEC{\Exp}{\Exp} \\
  11703. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  11704. \LangArray{} &::=& \gray{\Def\ldots \; \Exp}
  11705. \end{array}
  11706. \]
  11707. \fi}
  11708. {\if\edition\pythonEd
  11709. UNDER CONSTRUCTION
  11710. \fi}
  11711. \end{minipage}
  11712. }
  11713. \caption{The concrete syntax of \LangArray{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  11714. \label{fig:Lvecof-concrete-syntax}
  11715. \end{figure}
  11716. \begin{figure}[tp]
  11717. \begin{lstlisting}
  11718. (define (inner-product [A : (Vectorof Integer)] [B : (Vectorof Integer)]
  11719. [n : Integer]) : Integer
  11720. (let ([i 0])
  11721. (let ([prod 0])
  11722. (begin
  11723. (while (< i n)
  11724. (begin
  11725. (set! prod (+ prod (* (vector-ref A i)
  11726. (vector-ref B i))))
  11727. (set! i (+ i 1))
  11728. ))
  11729. prod))))
  11730. (let ([A (make-vector 2 2)])
  11731. (let ([B (make-vector 2 3)])
  11732. (+ (inner-product A B 2)
  11733. 30)))
  11734. \end{lstlisting}
  11735. \caption{Example program that computes the inner-product.}
  11736. \label{fig:inner-product}
  11737. \end{figure}
  11738. The type checker for \LangArray{} is define in
  11739. Figure~\ref{fig:type-check-Lvecof}. The result type of
  11740. \code{make-vector} is \code{(Vectorof T)} where \code{T} is the type
  11741. of the intializing expression. The length expression is required to
  11742. have type \code{Integer}. The type checking of the operators
  11743. \code{vector-length}, \code{vector-ref}, and \code{vector-set!} is
  11744. updated to handle the situation where the vector has type
  11745. \code{Vectorof}. In these cases we translate the operators to their
  11746. \code{vectorof} form so that later passes can easily distinguish
  11747. between operations on tuples versus arrays. We override the
  11748. \code{operator-types} method to provide the type signature for
  11749. multiplication: it takes two integers and returns an integer. To
  11750. support injection and projection of arrays to the \code{Any} type
  11751. (Section~\ref{sec:Rany-lang}), we also override the \code{flat-ty?}
  11752. predicate.
  11753. \begin{figure}[tbp]
  11754. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11755. (define type-check-Lvecof_class
  11756. (class type-check-Rwhile_class
  11757. (super-new)
  11758. (inherit check-type-equal?)
  11759. (define/override (flat-ty? ty)
  11760. (match ty
  11761. ['(Vectorof Any) #t]
  11762. [else (super flat-ty? ty)]))
  11763. (define/override (operator-types)
  11764. (append '((* . ((Integer Integer) . Integer)))
  11765. (super operator-types)))
  11766. (define/override (type-check-exp env)
  11767. (lambda (e)
  11768. (define recur (type-check-exp env))
  11769. (match e
  11770. [(Prim 'make-vector (list e1 e2))
  11771. (define-values (e1^ t1) (recur e1))
  11772. (define-values (e2^ elt-type) (recur e2))
  11773. (define vec-type `(Vectorof ,elt-type))
  11774. (values (HasType (Prim 'make-vector (list e1^ e2^)) vec-type)
  11775. vec-type)]
  11776. [(Prim 'vector-ref (list e1 e2))
  11777. (define-values (e1^ t1) (recur e1))
  11778. (define-values (e2^ t2) (recur e2))
  11779. (match* (t1 t2)
  11780. [(`(Vectorof ,elt-type) 'Integer)
  11781. (values (Prim 'vectorof-ref (list e1^ e2^)) elt-type)]
  11782. [(other wise) ((super type-check-exp env) e)])]
  11783. [(Prim 'vector-set! (list e1 e2 e3) )
  11784. (define-values (e-vec t-vec) (recur e1))
  11785. (define-values (e2^ t2) (recur e2))
  11786. (define-values (e-arg^ t-arg) (recur e3))
  11787. (match t-vec
  11788. [`(Vectorof ,elt-type)
  11789. (check-type-equal? elt-type t-arg e)
  11790. (values (Prim 'vectorof-set! (list e-vec e2^ e-arg^)) 'Void)]
  11791. [else ((super type-check-exp env) e)])]
  11792. [(Prim 'vector-length (list e1))
  11793. (define-values (e1^ t1) (recur e1))
  11794. (match t1
  11795. [`(Vectorof ,t)
  11796. (values (Prim 'vectorof-length (list e1^)) 'Integer)]
  11797. [else ((super type-check-exp env) e)])]
  11798. [else ((super type-check-exp env) e)])))
  11799. ))
  11800. (define (type-check-Lvecof p)
  11801. (send (new type-check-Lvecof_class) type-check-program p))
  11802. \end{lstlisting}
  11803. \caption{Type checker for the \LangArray{} language.}
  11804. \label{fig:type-check-Lvecof}
  11805. \end{figure}
  11806. The interpreter for \LangArray{} is defined in
  11807. Figure~\ref{fig:interp-Lvecof}. The \code{make-vector} operator is
  11808. implemented with Racket's \code{make-vector} function and
  11809. multiplication is \code{fx*}, multiplication for \code{fixnum}
  11810. integers.
  11811. \begin{figure}[tbp]
  11812. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  11813. (define interp-Lvecof_class
  11814. (class interp-Rwhile_class
  11815. (super-new)
  11816. (define/override (interp-op op)
  11817. (verbose "Lvecof/interp-op" op)
  11818. (match op
  11819. ['make-vector make-vector]
  11820. ['* fx*]
  11821. [else (super interp-op op)]))
  11822. ))
  11823. (define (interp-Lvecof p)
  11824. (send (new interp-Lvecof_class) interp-program p))
  11825. \end{lstlisting}
  11826. \caption{Interpreter for \LangArray{}.}
  11827. \label{fig:interp-Lvecof}
  11828. \end{figure}
  11829. \subsection{Data Representation}
  11830. \label{sec:array-rep}
  11831. Just like tuples, we store arrays on the heap which means that the
  11832. garbage collector will need to inspect arrays. An immediate thought is
  11833. to use the same representation for arrays that we use for tuples.
  11834. However, we limit tuples to a length of $50$ so that their length and
  11835. pointer mask can fit into the 64-bit tag at the beginning of each
  11836. tuple (Section~\ref{sec:data-rep-gc}). We intend arrays to allow
  11837. millions of elements, so we need more bits to store the length.
  11838. However, because arrays are homogeneous, we only need $1$ bit for the
  11839. pointer mask instead of one bit per array elements. Finally, the
  11840. garbage collector will need to be able to distinguish between tuples
  11841. and arrays, so we need to reserve $1$ bit for that purpose. So we
  11842. arrive at the following layout for the 64-bit tag at the beginning of
  11843. an array:
  11844. \begin{itemize}
  11845. \item The right-most bit is the forwarding bit, just like in a tuple.
  11846. A $0$ indicates it is a forwarding pointer and a $1$ indicates
  11847. it is not.
  11848. \item The next bit to the left is the pointer mask. A $0$ indicates
  11849. that none of the elements are pointers to the heap and a $1$
  11850. indicates that all of the elements are pointers.
  11851. \item The next $61$ bits store the length of the array.
  11852. \item The left-most bit distinguishes between a tuple ($0$) versus an
  11853. array ($1$).
  11854. \end{itemize}
  11855. Recall that in Chapter~\ref{ch:Ldyn}, we use a $3$-bit tag to
  11856. differentiate the kinds of values that have been injected into the
  11857. \code{Any} type. We use the bit pattern \code{110} (or $6$ in decimal)
  11858. to indicate that the value is an array.
  11859. In the following subsections we provide hints regarding how to update
  11860. the passes to handle arrays.
  11861. \subsection{Reveal Casts}
  11862. The array-access operators \code{vectorof-ref} and
  11863. \code{vectorof-set!} are similar to the \code{any-vector-ref} and
  11864. \code{any-vector-set!} operators of Chapter~\ref{ch:Ldyn} in
  11865. that the type checker cannot tell whether the index will be in bounds,
  11866. so the bounds check must be performed at run time. Recall that the
  11867. \code{reveal-casts} pass (Section~\ref{sec:reveal-casts-Rany}) wraps
  11868. an \code{If} arround a vector reference for update to check whether
  11869. the index is less than the length. You should do the same for
  11870. \code{vectorof-ref} and \code{vectorof-set!} .
  11871. In addition, the handling of the \code{any-vector} operators in
  11872. \code{reveal-casts} needs to be updated to account for arrays that are
  11873. injected to \code{Any}. For the \code{any-vector-length} operator, the
  11874. generated code should test whether the tag is for tuples (\code{010})
  11875. or arrays (\code{110}) and then dispatch to either
  11876. \code{any-vector-length} or \code{any-vectorof-length}. For the later
  11877. we add a case in \code{select\_instructions} to generate the
  11878. appropriate instructions for accessing the array length from the
  11879. header of an array.
  11880. For the \code{any-vector-ref} and \code{any-vector-set!} operators,
  11881. the generated code needs to check that the index is less than the
  11882. vector length, so like the code for \code{any-vector-length}, check
  11883. the tag to determine whether to use \code{any-vector-length} or
  11884. \code{any-vectorof-length} for this purpose. Once the bounds checking
  11885. is complete, the generated code can use \code{any-vector-ref} and
  11886. \code{any-vector-set!} for both tuples and arrays because the
  11887. instructions used for those operators do not look at the tag at the
  11888. front of the tuple or array.
  11889. \subsection{Expose Allocation}
  11890. This pass should translate the \code{make-vector} operator into
  11891. lower-level operations. In particular, the new AST node
  11892. $\LP\key{AllocateArray}~\Exp~\Type\RP$ allocates an array of the
  11893. length specified by the $\Exp$, but does not initialize the elements
  11894. of the array. (Analogous to the \code{Allocate} AST node for tuples.)
  11895. The $\Type$ argument must be $\LP\key{Vectorof}~T\RP$ where $T$ is the
  11896. element type for the array. Regarding the initialization of the array,
  11897. we recommend generated a \code{while} loop that uses
  11898. \code{vector-set!} to put the initializing value into every element of
  11899. the array.
  11900. \subsection{Remove Complex Operands}
  11901. Add cases in the \code{rco\_atom} and \code{rco\_exp} for
  11902. \code{AllocateArray}. In particular, an \code{AllocateArray} node is
  11903. complex and its subexpression must be atomic.
  11904. \subsection{Explicate Control}
  11905. Add cases for \code{AllocateArray} to \code{explicate\_tail} and
  11906. \code{explicate\_assign}.
  11907. \subsection{Select Instructions}
  11908. Generate instructions for \code{AllocateArray} similar to those for
  11909. \code{Allocate} in Section~\ref{sec:select-instructions-gc} except
  11910. that the tag at the front of the array should instead use the
  11911. representation discussed in Section~\ref{sec:array-rep}.
  11912. Regarding \code{vectorof-length}, extract the length from the tag
  11913. according to the representation discussed in
  11914. Section~\ref{sec:array-rep}.
  11915. The instructions generated for \code{vectorof-ref} differ from those
  11916. for \code{vector-ref} (Section~\ref{sec:select-instructions-gc}) in
  11917. that the index is not a constant so the offset must be computed at
  11918. runtime, similar to the instructions generated for
  11919. \code{any-vector-of-ref} (Section~\ref{sec:select-Rany}). The same is
  11920. true for \code{vectorof-set!}. Also, the \code{vectorof-set!} may
  11921. appear in an assignment and as a stand-alone statement, so make sure
  11922. to handle both situations in this pass.
  11923. Finally, the instructions for \code{any-vectorof-length} should be
  11924. similar to those for \code{vectorof-length}, except that one must
  11925. first project the array by writing zeroes into the $3$-bit tag
  11926. \begin{exercise}\normalfont\normalsize
  11927. Implement a compiler for the \LangArray{} language by extending your
  11928. compiler for \LangLoop{}. Test your compiler on a half dozen new
  11929. programs, including the one in Figure~\ref{fig:inner-product} and also
  11930. a program that multiplies two matrices. Note that matrices are
  11931. 2-dimensional arrays, but those can be encoded into 1-dimensional
  11932. arrays by laying out each row in the array, one after the next.
  11933. \end{exercise}
  11934. \section{Challenge: Generational Collection}
  11935. The copying collector described in Section~\ref{sec:GC} can incur
  11936. significant runtime overhead because the call to \code{collect} takes
  11937. time proportional to all of the live data. One way to reduce this
  11938. overhead is to reduce how much data is inspected in each call to
  11939. \code{collect}. In particular, researchers have observed that recently
  11940. allocated data is more likely to become garbage then data that has
  11941. survived one or more previous calls to \code{collect}. This insight
  11942. motivated the creation of \emph{generational garbage collectors}
  11943. \index{subject}{generational garbage collector} that
  11944. 1) segregates data according to its age into two or more generations,
  11945. 2) allocates less space for younger generations, so collecting them is
  11946. faster, and more space for the older generations, and 3) performs
  11947. collection on the younger generations more frequently then for older
  11948. generations~\citep{Wilson:1992fk}.
  11949. For this challenge assignment, the goal is to adapt the copying
  11950. collector implemented in \code{runtime.c} to use two generations, one
  11951. for young data and one for old data. Each generation consists of a
  11952. FromSpace and a ToSpace. The following is a sketch of how to adapt the
  11953. \code{collect} function to use the two generations.
  11954. \begin{enumerate}
  11955. \item Copy the young generation's FromSpace to its ToSpace then switch
  11956. the role of the ToSpace and FromSpace
  11957. \item If there is enough space for the requested number of bytes in
  11958. the young FromSpace, then return from \code{collect}.
  11959. \item If there is not enough space in the young FromSpace for the
  11960. requested bytes, then move the data from the young generation to the
  11961. old one with the following steps:
  11962. \begin{enumerate}
  11963. \item If there is enough room in the old FromSpace, copy the young
  11964. FromSpace to the old FromSpace and then return.
  11965. \item If there is not enough room in the old FromSpace, then collect
  11966. the old generation by copying the old FromSpace to the old ToSpace
  11967. and swap the roles of the old FromSpace and ToSpace.
  11968. \item If there is enough room now, copy the young FromSpace to the
  11969. old FromSpace and return. Otherwise, allocate a larger FromSpace
  11970. and ToSpace for the old generation. Copy the young FromSpace and
  11971. the old FromSpace into the larger FromSpace for the old
  11972. generation and then return.
  11973. \end{enumerate}
  11974. \end{enumerate}
  11975. We recommend that you generalize the \code{cheney} function so that it
  11976. can be used for all the copies mentioned above: between the young
  11977. FromSpace and ToSpace, between the old FromSpace and ToSpace, and
  11978. between the young FromSpace and old FromSpace. This can be
  11979. accomplished by adding parameters to \code{cheney} that replace its
  11980. use of the global variables \code{fromspace\_begin},
  11981. \code{fromspace\_end}, \code{tospace\_begin}, and \code{tospace\_end}.
  11982. Note that the collection of the young generation does not traverse the
  11983. old generation. This introduces a potential problem: there may be
  11984. young data that is only reachable through pointers in the old
  11985. generation. If these pointers are not taken into account, the
  11986. collector could throw away young data that is live! One solution,
  11987. called \emph{pointer recording}, is to maintain a set of all the
  11988. pointers from the old generation into the new generation and consider
  11989. this set as part of the root set. To maintain this set, the compiler
  11990. must insert extra instructions around every \code{vector-set!}. If the
  11991. vector being modified is in the old generation, and if the value being
  11992. written is a pointer into the new generation, than that pointer must
  11993. be added to the set. Also, if the value being overwritten was a
  11994. pointer into the new generation, then that pointer should be removed
  11995. from the set.
  11996. \begin{exercise}\normalfont\normalsize
  11997. Adapt the \code{collect} function in \code{runtime.c} to implement
  11998. generational garbage collection, as outlined in this section.
  11999. Update the code generation for \code{vector-set!} to implement
  12000. pointer recording. Make sure that your new compiler and runtime
  12001. passes your test suite.
  12002. \end{exercise}
  12003. \fi}
  12004. \section{Further Reading}
  12005. \citet{Appel90} describes many data representation approaches,
  12006. including the ones used in the compilation of Standard ML.
  12007. There are many alternatives to copying collectors (and their bigger
  12008. siblings, the generational collectors) when its comes to garbage
  12009. collection, such as mark-and-sweep~\citep{McCarthy:1960dz} and
  12010. reference counting~\citep{Collins:1960aa}. The strengths of copying
  12011. collectors are that allocation is fast (just a comparison and pointer
  12012. increment), there is no fragmentation, cyclic garbage is collected,
  12013. and the time complexity of collection only depends on the amount of
  12014. live data, and not on the amount of garbage~\citep{Wilson:1992fk}. The
  12015. main disadvantages of a two-space copying collector is that it uses a
  12016. lot of extra space and takes a long time to perform the copy, though
  12017. these problems are ameliorated in generational collectors.
  12018. \racket{Racket}\python{Object-oriented} programs tend to allocate many
  12019. small objects and generate a lot of garbage, so copying and
  12020. generational collectors are a good fit\python{~\citep{Dieckmann99}}.
  12021. Garbage collection is an active research topic, especially concurrent
  12022. garbage collection~\citep{Tene:2011kx}. Researchers are continuously
  12023. developing new techniques and revisiting old
  12024. trade-offs~\citep{Blackburn:2004aa,Jones:2011aa,Shahriyar:2013aa,Cutler:2015aa,Shidal:2015aa,Osterlund:2016aa,Jacek:2019aa,Gamari:2020aa}. Researchers
  12025. meet every year at the International Symposium on Memory Management to
  12026. present these findings.
  12027. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  12028. \chapter{Functions}
  12029. \label{ch:Lfun}
  12030. \index{subject}{function}
  12031. This chapter studies the compilation of a subset of \racket{Typed
  12032. Racket}\python{Python} in which only top-level function definitions
  12033. are allowed..
  12034. This kind of function is a realistic example as the C language imposes
  12035. similar restrictions. It is also an important stepping stone to
  12036. implementing lexically-scoped functions in the form of \key{lambda}
  12037. abstractions, which is the topic of Chapter~\ref{ch:Llambda}.
  12038. \section{The \LangFun{} Language}
  12039. The concrete and abstract syntax for function definitions and function
  12040. application is shown in Figures~\ref{fig:Rfun-concrete-syntax} and
  12041. \ref{fig:Rfun-syntax}, where we define the \LangFun{} language. Programs in
  12042. \LangFun{} begin with zero or more function definitions. The function
  12043. names from these definitions are in-scope for the entire program,
  12044. including all other function definitions (so the ordering of function
  12045. definitions does not matter).
  12046. %
  12047. \python{The abstract syntax for function parameters in
  12048. Figure~\ref{fig:Rfun-syntax} is a list of pairs, where each pair
  12049. consists of a parameter name and its type. This design differs from
  12050. Python's \code{ast} module, which has a more complex structure for
  12051. function parameters to handle keyword parameters,
  12052. defaults, and so on. The type checker in \code{type\_check\_Lfun} converts the
  12053. complex Python abstract syntax into the simpler syntax of
  12054. Figure~\ref{fig:Rfun-syntax}. The fourth and sixth parameters of the
  12055. \code{FunctionDef} constructor are for decorators and a type
  12056. comment, neither of which are used by our compiler. We recommend
  12057. replacing them with \code{None} in the \code{shrink} pass.
  12058. }
  12059. %
  12060. The concrete syntax for function application\index{subject}{function
  12061. application} is
  12062. \python{$\CAPPLY{\Exp}{\Exp\code{,} \ldots}$}
  12063. \racket{$\CAPPLY{\Exp}{\Exp \ldots}$}
  12064. where the first expression
  12065. must evaluate to a function and the remaining expressions are the arguments. The
  12066. abstract syntax for function application is
  12067. $\APPLY{\Exp}{\Exp^*}$.
  12068. %% The syntax for function application does not include an explicit
  12069. %% keyword, which is error prone when using \code{match}. To alleviate
  12070. %% this problem, we translate the syntax from $(\Exp \; \Exp \ldots)$ to
  12071. %% $(\key{app}\; \Exp \; \Exp \ldots)$ during type checking.
  12072. Functions are first-class in the sense that a function pointer
  12073. \index{subject}{function pointer} is data and can be stored in memory or passed
  12074. as a parameter to another function. Thus, there is a function
  12075. type, written
  12076. {\if\edition\racketEd
  12077. \begin{lstlisting}
  12078. (|$\Type_1$| |$\cdots$| |$\Type_n$| -> |$\Type_r$|)
  12079. \end{lstlisting}
  12080. \fi}
  12081. {\if\edition\pythonEd
  12082. \begin{lstlisting}
  12083. Callable[[|$\Type_1$|,|$\cdots$|,|$\Type_n$|], |$\Type_R$|]
  12084. \end{lstlisting}
  12085. \fi}
  12086. %
  12087. \noindent for a function whose $n$ parameters have the types $\Type_1$
  12088. through $\Type_n$ and whose return type is $\Type_R$. The main
  12089. limitation of these functions (with respect to
  12090. \racket{Racket}\python{Python} functions) is that they are not
  12091. lexically scoped. That is, the only external entities that can be
  12092. referenced from inside a function body are other globally-defined
  12093. functions. The syntax of \LangFun{} prevents function definitions from being
  12094. nested inside each other.
  12095. \newcommand{\LfunGrammarRacket}{
  12096. \begin{array}{lcl}
  12097. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12098. \Exp &::=& \LP\Exp \; \Exp \ldots\RP \\
  12099. \Def &::=& \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} \\
  12100. \end{array}
  12101. }
  12102. \newcommand{\LfunASTRacket}{
  12103. \begin{array}{lcl}
  12104. \Type &::=& (\Type \ldots \; \key{->}\; \Type) \\
  12105. \Exp &::=& \APPLY{\Exp}{\Exp\ldots}\\
  12106. \Def &::=& \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp}
  12107. \end{array}
  12108. }
  12109. \newcommand{\LfunGrammarPython}{
  12110. \begin{array}{lcl}
  12111. \Type &::=& \key{int}
  12112. \MID \key{bool}
  12113. \MID \key{tuple}\LS \Type^+ \RS
  12114. \MID \key{Callable}\LS \LS \Type \key{,} \ldots \RS \key{, } \Type \RS \\
  12115. \Exp &::=& \CAPPLY{\Exp}{\Exp\code{,} \ldots} \\
  12116. \Stmt &::=& \CRETURN{\Exp} \\
  12117. \Def &::=& \CDEF{\Var}{\Var \key{:} \Type\key{,} \ldots}{\Type}{\Stmt^{+}}
  12118. \end{array}
  12119. }
  12120. \newcommand{\LfunASTPython}{
  12121. \begin{array}{lcl}
  12122. \Type &::=& \key{IntType()} \MID \key{BoolType()} \key{VoidType()}
  12123. \MID \key{TupleType}\LS\Type^+\RS\\
  12124. &\MID& \key{FunctionType}\LP \Type^{*} \key{, } \Type \RP \\
  12125. \Exp &::=& \CALL{\Exp}{\Exp^{*}}\\
  12126. \Stmt &::=& \RETURN{\Exp} \\
  12127. \Params &::=& \LP\Var\key{,}\Type\RP^*
  12128. \\
  12129. \Def &::=& \FUNDEF{\Var}{\Params}{\Type}{}{\Stmt^{+}}
  12130. \end{array}
  12131. }
  12132. \begin{figure}[tp]
  12133. \centering
  12134. \fbox{
  12135. \begin{minipage}{0.96\textwidth}
  12136. \small
  12137. {\if\edition\racketEd
  12138. \[
  12139. \begin{array}{l}
  12140. \gray{\LintGrammarRacket{}} \\ \hline
  12141. \gray{\LvarGrammarRacket{}} \\ \hline
  12142. \gray{\LifGrammarRacket{}} \\ \hline
  12143. \gray{\LwhileGrammarRacket} \\ \hline
  12144. \gray{\LtupGrammarRacket} \\ \hline
  12145. \LfunGrammarRacket \\
  12146. \begin{array}{lcl}
  12147. \LangFunM{} &::=& \Def \ldots \; \Exp
  12148. \end{array}
  12149. \end{array}
  12150. \]
  12151. \fi}
  12152. {\if\edition\pythonEd
  12153. \[
  12154. \begin{array}{l}
  12155. \gray{\LintGrammarPython{}} \\ \hline
  12156. \gray{\LvarGrammarPython{}} \\ \hline
  12157. \gray{\LifGrammarPython{}} \\ \hline
  12158. \gray{\LwhileGrammarPython} \\ \hline
  12159. \gray{\LtupGrammarPython} \\ \hline
  12160. \LfunGrammarPython \\
  12161. \begin{array}{rcl}
  12162. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  12163. \end{array}
  12164. \end{array}
  12165. \]
  12166. \fi}
  12167. \end{minipage}
  12168. }
  12169. \caption{The concrete syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-concrete-syntax}).}
  12170. \label{fig:Rfun-concrete-syntax}
  12171. \end{figure}
  12172. \begin{figure}[tp]
  12173. \centering
  12174. \fbox{
  12175. \begin{minipage}{0.96\textwidth}
  12176. \small
  12177. {\if\edition\racketEd
  12178. \[
  12179. \begin{array}{l}
  12180. \gray{\LintOpAST} \\ \hline
  12181. \gray{\LvarASTRacket{}} \\ \hline
  12182. \gray{\LifASTRacket{}} \\ \hline
  12183. \gray{\LwhileASTRacket{}} \\ \hline
  12184. \gray{\LtupASTRacket{}} \\ \hline
  12185. \LfunASTRacket \\
  12186. \begin{array}{lcl}
  12187. \LangFunM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP)}{\Exp}
  12188. \end{array}
  12189. \end{array}
  12190. \]
  12191. \fi}
  12192. {\if\edition\pythonEd
  12193. \[
  12194. \begin{array}{l}
  12195. \gray{\LintASTPython{}} \\ \hline
  12196. \gray{\LvarASTPython{}} \\ \hline
  12197. \gray{\LifASTPython{}} \\ \hline
  12198. \gray{\LwhileASTPython} \\ \hline
  12199. \gray{\LtupASTPython} \\ \hline
  12200. \LfunASTPython \\
  12201. \begin{array}{rcl}
  12202. \LangFunM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  12203. \end{array}
  12204. \end{array}
  12205. \]
  12206. \fi}
  12207. \end{minipage}
  12208. }
  12209. \caption{The abstract syntax of \LangFun{}, extending \LangVec{} (Figure~\ref{fig:Lvec-syntax}).}
  12210. \label{fig:Rfun-syntax}
  12211. \end{figure}
  12212. The program in Figure~\ref{fig:Rfun-function-example} is a
  12213. representative example of defining and using functions in \LangFun{}.
  12214. We define a function \code{map} that applies some other function
  12215. \code{f} to both elements of a tuple and returns a new tuple
  12216. containing the results. We also define a function \code{inc}. The
  12217. program applies \code{map} to \code{inc} and
  12218. %
  12219. \racket{\code{(vector 0 41)}}\python{\code{(0, 41)}}.
  12220. %
  12221. The result is \racket{\code{(vector 1 42)}}\python{\code{(1, 42)}},
  12222. %
  12223. from which we return the \code{42}.
  12224. \begin{figure}[tbp]
  12225. {\if\edition\racketEd
  12226. \begin{lstlisting}
  12227. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  12228. : (Vector Integer Integer)
  12229. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  12230. (define (inc [x : Integer]) : Integer
  12231. (+ x 1))
  12232. (vector-ref (map inc (vector 0 41)) 1)
  12233. \end{lstlisting}
  12234. \fi}
  12235. {\if\edition\pythonEd
  12236. \begin{lstlisting}
  12237. def map(f : Callable[[int], int], v : tuple[int,int]) -> tuple[int,int]:
  12238. return f(v[0]), f(v[1])
  12239. def inc(x : int) -> int:
  12240. return x + 1
  12241. print( map(inc, (0, 41))[1] )
  12242. \end{lstlisting}
  12243. \fi}
  12244. \caption{Example of using functions in \LangFun{}.}
  12245. \label{fig:Rfun-function-example}
  12246. \end{figure}
  12247. The definitional interpreter for \LangFun{} is in
  12248. Figure~\ref{fig:interp-Rfun}. The case for the
  12249. %
  12250. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12251. %
  12252. AST is responsible for setting up the mutual recursion between the
  12253. top-level function definitions.
  12254. %
  12255. \racket{We use the classic back-patching
  12256. \index{subject}{back-patching} approach that uses mutable variables
  12257. and makes two passes over the function
  12258. definitions~\citep{Kelsey:1998di}. In the first pass we set up the
  12259. top-level environment using a mutable cons cell for each function
  12260. definition. Note that the \code{lambda} value for each function is
  12261. incomplete; it does not yet include the environment. Once the
  12262. top-level environment is constructed, we then iterate over it and
  12263. update the \code{lambda} values to use the top-level environment.}
  12264. %
  12265. \python{We create a dictionary named \code{env} and fill it in
  12266. by mapping each function name to a new \code{Function} value,
  12267. each of which stores a reference to the \code{env}.
  12268. (We define the class \code{Function} for this purpose.)}
  12269. %
  12270. To interpret a function \racket{application}\python{call}, we match
  12271. the result of the function expression to obtain a function value. We
  12272. then extend the function's environment with mapping of parameters to
  12273. argument values. Finally, we interpret the body of the function in
  12274. this extended environment.
  12275. \begin{figure}[tp]
  12276. {\if\edition\racketEd
  12277. \begin{lstlisting}
  12278. (define interp-Rfun_class
  12279. (class interp-Lvec_class
  12280. (super-new)
  12281. (define/override ((interp-exp env) e)
  12282. (define recur (interp-exp env))
  12283. (match e
  12284. [(Var x) (unbox (dict-ref env x))]
  12285. [(Let x e body)
  12286. (define new-env (dict-set env x (box (recur e))))
  12287. ((interp-exp new-env) body)]
  12288. [(Apply fun args)
  12289. (define fun-val (recur fun))
  12290. (define arg-vals (for/list ([e args]) (recur e)))
  12291. (match fun-val
  12292. [`(function (,xs ...) ,body ,fun-env)
  12293. (define params-args (for/list ([x xs] [arg arg-vals])
  12294. (cons x (box arg))))
  12295. (define new-env (append params-args fun-env))
  12296. ((interp-exp new-env) body)]
  12297. [else (error 'interp-exp "expected function, not ~a" fun-val)])]
  12298. [else ((super interp-exp env) e)]
  12299. ))
  12300. (define/public (interp-def d)
  12301. (match d
  12302. [(Def f (list `[,xs : ,ps] ...) rt _ body)
  12303. (cons f (box `(function ,xs ,body ())))]))
  12304. (define/override (interp-program p)
  12305. (match p
  12306. [(ProgramDefsExp info ds body)
  12307. (let ([top-level (for/list ([d ds]) (interp-def d))])
  12308. (for/list ([f (in-dict-values top-level)])
  12309. (set-box! f (match (unbox f)
  12310. [`(function ,xs ,body ())
  12311. `(function ,xs ,body ,top-level)])))
  12312. ((interp-exp top-level) body))]))
  12313. ))
  12314. (define (interp-Rfun p)
  12315. (send (new interp-Rfun_class) interp-program p))
  12316. \end{lstlisting}
  12317. \fi}
  12318. {\if\edition\pythonEd
  12319. \begin{lstlisting}
  12320. class InterpLfun(InterpLtup):
  12321. def apply_fun(self, fun, args, e):
  12322. match fun:
  12323. case Function(name, xs, body, env):
  12324. new_env = env.copy().update(zip(xs, args))
  12325. return self.interp_stmts(body, new_env)
  12326. case _:
  12327. raise Exception('apply_fun: unexpected: ' + repr(fun))
  12328. def interp_exp(self, e, env):
  12329. match e:
  12330. case Call(Name('input_int'), []):
  12331. return super().interp_exp(e, env)
  12332. case Call(func, args):
  12333. f = self.interp_exp(func, env)
  12334. vs = [self.interp_exp(arg, env) for arg in args]
  12335. return self.apply_fun(f, vs, e)
  12336. case _:
  12337. return super().interp_exp(e, env)
  12338. def interp_stmts(self, ss, env):
  12339. if len(ss) == 0:
  12340. return
  12341. match ss[0]:
  12342. case Return(value):
  12343. return self.interp_exp(value, env)
  12344. case FunctionDef(name, params, bod, dl, returns, comment):
  12345. ps = [x for (x,t) in params]
  12346. env[name] = Function(name, ps, bod, env)
  12347. return self.interp_stmts(ss[1:], env)
  12348. case _:
  12349. return super().interp_stmts(ss, env)
  12350. def interp(self, p):
  12351. match p:
  12352. case Module(ss):
  12353. env = {}
  12354. self.interp_stmts(ss, env)
  12355. if 'main' in env.keys():
  12356. self.apply_fun(env['main'], [], None)
  12357. case _:
  12358. raise Exception('interp: unexpected ' + repr(p))
  12359. \end{lstlisting}
  12360. \fi}
  12361. \caption{Interpreter for the \LangFun{} language.}
  12362. \label{fig:interp-Rfun}
  12363. \end{figure}
  12364. %\margincomment{TODO: explain type checker}
  12365. The type checker for \LangFun{} is in
  12366. Figure~\ref{fig:type-check-Rfun}. (We omit the code that parses
  12367. function parameters into the simpler abstract syntax.) Similar to the
  12368. interpreter, the case for the
  12369. \racket{\code{ProgramDefsExp}}\python{\code{Module}}
  12370. %
  12371. AST is responsible for setting up the mutual recursion between the
  12372. top-level function definitions. We begin by create a mapping
  12373. \code{env} from every function name to its type. We then type check
  12374. the program using this mapping.
  12375. %
  12376. In the case for function \racket{application}\python{call}, we match
  12377. the type of the function expression to a function type and check that
  12378. the types of the argument expressions are equal to the function's
  12379. parameter types. The type of the \racket{application}\python{call} as
  12380. a whole is the return type from the function type.
  12381. \begin{figure}[tp]
  12382. {\if\edition\racketEd
  12383. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  12384. (define type-check-Rfun_class
  12385. (class type-check-Lvec_class
  12386. (super-new)
  12387. (inherit check-type-equal?)
  12388. (define/public (type-check-apply env e es)
  12389. (define-values (e^ ty) ((type-check-exp env) e))
  12390. (define-values (e* ty*) (for/lists (e* ty*) ([e (in-list es)])
  12391. ((type-check-exp env) e)))
  12392. (match ty
  12393. [`(,ty^* ... -> ,rt)
  12394. (for ([arg-ty ty*] [param-ty ty^*])
  12395. (check-type-equal? arg-ty param-ty (Apply e es)))
  12396. (values e^ e* rt)]))
  12397. (define/override (type-check-exp env)
  12398. (lambda (e)
  12399. (match e
  12400. [(FunRef f n)
  12401. (values (FunRef f n) (dict-ref env f))]
  12402. [(Apply e es)
  12403. (define-values (e^ es^ rt) (type-check-apply env e es))
  12404. (values (Apply e^ es^) rt)]
  12405. [(Call e es)
  12406. (define-values (e^ es^ rt) (type-check-apply env e es))
  12407. (values (Call e^ es^) rt)]
  12408. [else ((super type-check-exp env) e)])))
  12409. (define/public (type-check-def env)
  12410. (lambda (e)
  12411. (match e
  12412. [(Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body)
  12413. (define new-env (append (map cons xs ps) env))
  12414. (define-values (body^ ty^) ((type-check-exp new-env) body))
  12415. (check-type-equal? ty^ rt body)
  12416. (Def f p:t* rt info body^)])))
  12417. (define/public (fun-def-type d)
  12418. (match d
  12419. [(Def f (list `[,xs : ,ps] ...) rt info body) `(,@ps -> ,rt)]))
  12420. (define/override (type-check-program e)
  12421. (match e
  12422. [(ProgramDefsExp info ds body)
  12423. (define env (for/list ([d ds])
  12424. (cons (Def-name d) (fun-def-type d))))
  12425. (define ds^ (for/list ([d ds]) ((type-check-def env) d)))
  12426. (define-values (body^ ty) ((type-check-exp env) body))
  12427. (check-type-equal? ty 'Integer body)
  12428. (ProgramDefsExp info ds^ body^)]))))
  12429. (define (type-check-Rfun p)
  12430. (send (new type-check-Rfun_class) type-check-program p))
  12431. \end{lstlisting}
  12432. \fi}
  12433. {\if\edition\pythonEd
  12434. \begin{lstlisting}
  12435. class TypeCheckLfun(TypeCheckLtup):
  12436. def type_check_exp(self, e, env):
  12437. match e:
  12438. case Call(Name('input_int'), []):
  12439. return super().type_check_exp(e, env)
  12440. case Call(func, args):
  12441. func_t = self.type_check_exp(func, env)
  12442. args_t = [self.type_check_exp(arg, env) for arg in args]
  12443. match func_t:
  12444. case FunctionType(params_t, return_t):
  12445. for (arg_t, param_t) in zip(args_t, params_t):
  12446. check_type_equal(param_t, arg_t, e)
  12447. return return_t
  12448. case _:
  12449. raise Exception('type_check_exp: in call, unexpected ' +
  12450. repr(func_t))
  12451. case _:
  12452. return super().type_check_exp(e, env)
  12453. def type_check_stmts(self, ss, env):
  12454. if len(ss) == 0:
  12455. return
  12456. match ss[0]:
  12457. case FunctionDef(name, params, body, dl, returns, comment):
  12458. new_env = env.copy().update(params)
  12459. rt = self.type_check_stmts(body, new_env)
  12460. check_type_equal(returns, rt, ss[0])
  12461. return self.type_check_stmts(ss[1:], env)
  12462. case Return(value):
  12463. return self.type_check_exp(value, env)
  12464. case _:
  12465. return super().type_check_stmts(ss, env)
  12466. def type_check(self, p):
  12467. match p:
  12468. case Module(body):
  12469. env = {}
  12470. for s in body:
  12471. match s:
  12472. case FunctionDef(name, params, bod, dl, returns, comment):
  12473. if name in env:
  12474. raise Exception('type_check: function ' +
  12475. repr(name) + ' defined twice')
  12476. params_t = [t for (x,t) in params]
  12477. env[name] = FunctionType(params_t, returns)
  12478. self.type_check_stmts(body, env)
  12479. case _:
  12480. raise Exception('type_check: unexpected ' + repr(p))
  12481. \end{lstlisting}
  12482. \fi}
  12483. \caption{Type checker for the \LangFun{} language.}
  12484. \label{fig:type-check-Rfun}
  12485. \end{figure}
  12486. \clearpage
  12487. \section{Functions in x86}
  12488. \label{sec:fun-x86}
  12489. %% \margincomment{\tiny Make sure callee-saved registers are discussed
  12490. %% in enough depth, especially updating Fig 6.4 \\ --Jeremy }
  12491. %% \margincomment{\tiny Talk about the return address on the
  12492. %% stack and what callq and retq does.\\ --Jeremy }
  12493. The x86 architecture provides a few features to support the
  12494. implementation of functions. We have already seen that there are
  12495. labels in x86 so that one can refer to the location of an instruction,
  12496. as is needed for jump instructions. Labels can also be used to mark
  12497. the beginning of the instructions for a function. Going further, we
  12498. can obtain the address of a label by using the \key{leaq} instruction
  12499. and instruction-pointer relative addressing. For example, the
  12500. following puts the address of the \code{inc} label into the \code{rbx}
  12501. register.
  12502. \begin{lstlisting}
  12503. leaq inc(%rip), %rbx
  12504. \end{lstlisting}
  12505. Recall from Section~\ref{sec:select-instructions-gc} that
  12506. \verb!inc(%rip)! is an example of instruction-pointer relative
  12507. addressing. It computes the address of \code{inc}.
  12508. In Section~\ref{sec:x86} we used the \code{callq} instruction to jump
  12509. to functions whose locations were given by a label, such as
  12510. \code{read\_int}. To support function calls in this chapter we instead
  12511. will be jumping to functions whose location are given by an address in
  12512. a register, that is, we need to make an \emph{indirect function
  12513. call}. The x86 syntax for this is a \code{callq} instruction but with
  12514. an asterisk before the register name.\index{subject}{indirect function
  12515. call}
  12516. \begin{lstlisting}
  12517. callq *%rbx
  12518. \end{lstlisting}
  12519. \subsection{Calling Conventions}
  12520. \index{subject}{calling conventions}
  12521. The \code{callq} instruction provides partial support for implementing
  12522. functions: it pushes the return address on the stack and it jumps to
  12523. the target. However, \code{callq} does not handle
  12524. \begin{enumerate}
  12525. \item parameter passing,
  12526. \item pushing frames on the procedure call stack and popping them off,
  12527. or
  12528. \item determining how registers are shared by different functions.
  12529. \end{enumerate}
  12530. Regarding (1) parameter passing, recall that the x86-64 calling convention
  12531. for Unix-based system uses the following six
  12532. registers to pass arguments to a function, in this order.
  12533. \begin{lstlisting}
  12534. rdi rsi rdx rcx r8 r9
  12535. \end{lstlisting}
  12536. If there are
  12537. more than six arguments, then the calling convention mandates to use space on the
  12538. frame of the caller for the rest of the arguments. However, to ease
  12539. the implementation of efficient tail calls
  12540. (Section~\ref{sec:tail-call}), we arrange never to need more than six
  12541. arguments.
  12542. %
  12543. Also recall that the register \code{rax} is for the return value of
  12544. the function.
  12545. \index{subject}{prelude}\index{subject}{conclusion}
  12546. Regarding (2) frames \index{subject}{frame} and the procedure call
  12547. stack, \index{subject}{procedure call stack} recall from
  12548. Section~\ref{sec:x86} that the stack grows down and each function call
  12549. uses a chunk of space on the stack called a frame. The caller sets the
  12550. stack pointer, register \code{rsp}, to the last data item in its
  12551. frame. The callee must not change anything in the caller's frame, that
  12552. is, anything that is at or above the stack pointer. The callee is free
  12553. to use locations that are below the stack pointer.
  12554. Recall that we are storing variables of tuple type on the root stack.
  12555. So the prelude needs to move the root stack pointer \code{r15} up
  12556. according to the number of variables of tuple type and
  12557. the conclusion needs to move the root stack pointer back down. Also,
  12558. the prelude must initialize to \code{0} this frame's slots in the root
  12559. stack to signal to the garbage collector that those slots do not yet
  12560. contain a pointer to a vector. Otherwise the garbage collector will
  12561. interpret the garbage bits in those slots as memory addresses and try
  12562. to traverse them, causing serious mayhem!
  12563. Regarding (3) the sharing of registers between different functions,
  12564. recall from Section~\ref{sec:calling-conventions} that the registers
  12565. are divided into two groups, the caller-saved registers and the
  12566. callee-saved registers. The caller should assume that all the
  12567. caller-saved registers get overwritten with arbitrary values by the
  12568. callee. For that reason we recommend in
  12569. Section~\ref{sec:calling-conventions} that variables that are live
  12570. during a function call should not be assigned to caller-saved
  12571. registers.
  12572. On the flip side, if the callee wants to use a callee-saved register,
  12573. the callee must save the contents of those registers on their stack
  12574. frame and then put them back prior to returning to the caller. For
  12575. that reason we recommend in Section~\ref{sec:calling-conventions} that if
  12576. the register allocator assigns a variable to a callee-saved register,
  12577. then the prelude of the \code{main} function must save that register
  12578. to the stack and the conclusion of \code{main} must restore it. This
  12579. recommendation now generalizes to all functions.
  12580. Recall that the base pointer, register \code{rbp}, is used as a
  12581. point-of-reference within a frame, so that each local variable can be
  12582. accessed at a fixed offset from the base pointer
  12583. (Section~\ref{sec:x86}).
  12584. %
  12585. Figure~\ref{fig:call-frames} shows the general layout of the caller
  12586. and callee frames.
  12587. \begin{figure}[tbp]
  12588. \centering
  12589. \begin{tabular}{r|r|l|l} \hline
  12590. Caller View & Callee View & Contents & Frame \\ \hline
  12591. 8(\key{\%rbp}) & & return address & \multirow{5}{*}{Caller}\\
  12592. 0(\key{\%rbp}) & & old \key{rbp} \\
  12593. -8(\key{\%rbp}) & & callee-saved $1$ \\
  12594. \ldots & & \ldots \\
  12595. $-8j$(\key{\%rbp}) & & callee-saved $j$ \\
  12596. $-8(j+1)$(\key{\%rbp}) & & local variable $1$ \\
  12597. \ldots & & \ldots \\
  12598. $-8(j+k)$(\key{\%rbp}) & & local variable $k$ \\
  12599. %% & & \\
  12600. %% $8n-8$\key{(\%rsp)} & $8n+8$(\key{\%rbp})& argument $n$ \\
  12601. %% & \ldots & \ldots \\
  12602. %% 0\key{(\%rsp)} & 16(\key{\%rbp}) & argument $1$ & \\
  12603. \hline
  12604. & 8(\key{\%rbp}) & return address & \multirow{5}{*}{Callee}\\
  12605. & 0(\key{\%rbp}) & old \key{rbp} \\
  12606. & -8(\key{\%rbp}) & callee-saved $1$ \\
  12607. & \ldots & \ldots \\
  12608. & $-8n$(\key{\%rbp}) & callee-saved $n$ \\
  12609. & $-8(n+1)$(\key{\%rbp}) & local variable $1$ \\
  12610. & \ldots & \ldots \\
  12611. & $-8(n+m)$(\key{\%rbp}) & local variable $m$\\ \hline
  12612. \end{tabular}
  12613. \caption{Memory layout of caller and callee frames.}
  12614. \label{fig:call-frames}
  12615. \end{figure}
  12616. %% Recall from Section~\ref{sec:x86} that the stack is also used for
  12617. %% local variables and for storing the values of callee-saved registers
  12618. %% (we shall refer to all of these collectively as ``locals''), and that
  12619. %% at the beginning of a function we move the stack pointer \code{rsp}
  12620. %% down to make room for them.
  12621. %% We recommend storing the local variables
  12622. %% first and then the callee-saved registers, so that the local variables
  12623. %% can be accessed using \code{rbp} the same as before the addition of
  12624. %% functions.
  12625. %% To make additional room for passing arguments, we shall
  12626. %% move the stack pointer even further down. We count how many stack
  12627. %% arguments are needed for each function call that occurs inside the
  12628. %% body of the function and find their maximum. Adding this number to the
  12629. %% number of locals gives us how much the \code{rsp} should be moved at
  12630. %% the beginning of the function. In preparation for a function call, we
  12631. %% offset from \code{rsp} to set up the stack arguments. We put the first
  12632. %% stack argument in \code{0(\%rsp)}, the second in \code{8(\%rsp)}, and
  12633. %% so on.
  12634. %% Upon calling the function, the stack arguments are retrieved by the
  12635. %% callee using the base pointer \code{rbp}. The address \code{16(\%rbp)}
  12636. %% is the location of the first stack argument, \code{24(\%rbp)} is the
  12637. %% address of the second, and so on. Figure~\ref{fig:call-frames} shows
  12638. %% the layout of the caller and callee frames. Notice how important it is
  12639. %% that we correctly compute the maximum number of arguments needed for
  12640. %% function calls; if that number is too small then the arguments and
  12641. %% local variables will smash into each other!
  12642. \subsection{Efficient Tail Calls}
  12643. \label{sec:tail-call}
  12644. In general, the amount of stack space used by a program is determined
  12645. by the longest chain of nested function calls. That is, if function
  12646. $f_1$ calls $f_2$, $f_2$ calls $f_3$, $\ldots$, $f_n$, then the amount
  12647. of stack space is linear in $n$. The depth $n$ can grow quite large
  12648. if functions are (mutually) recursive. However, in
  12649. some cases we can arrange to use only a constant amount of space for a
  12650. long chain of nested function calls.
  12651. A \emph{tail call}\index{subject}{tail call} is a function call that
  12652. happens as the last action in a function body.
  12653. For example, in the following
  12654. program, the recursive call to \code{tail\_sum} is a tail call.
  12655. \begin{center}
  12656. {\if\edition\racketEd
  12657. \begin{lstlisting}
  12658. (define (tail_sum [n : Integer] [r : Integer]) : Integer
  12659. (if (eq? n 0)
  12660. r
  12661. (tail_sum (- n 1) (+ n r))))
  12662. (+ (tail_sum 3 0) 36)
  12663. \end{lstlisting}
  12664. \fi}
  12665. {\if\edition\pythonEd
  12666. \begin{lstlisting}
  12667. def tail_sum(n : int, r : int) -> int:
  12668. if n == 0:
  12669. return r
  12670. else:
  12671. return tail_sum(n - 1, n + r)
  12672. print( tail_sum(3, 0) + 36)
  12673. \end{lstlisting}
  12674. \fi}
  12675. \end{center}
  12676. At a tail call, the frame of the caller is no longer needed, so we can
  12677. pop the caller's frame before making the tail call. With this
  12678. approach, a recursive function that only makes tail calls ends up
  12679. using a constant amount of stack space. Functional languages like
  12680. Racket rely heavily on recursive functions, so the definition of
  12681. Racket \emph{requires} that all tail calls be optimized in this way.
  12682. \index{subject}{frame}
  12683. Some care is needed with regards to argument passing in tail calls.
  12684. As mentioned above, for arguments beyond the sixth, the convention is
  12685. to use space in the caller's frame for passing arguments. But for a
  12686. tail call we pop the caller's frame and can no longer use it. An
  12687. alternative is to use space in the callee's frame for passing
  12688. arguments. However, this option is also problematic because the caller
  12689. and callee's frames overlap in memory. As we begin to copy the
  12690. arguments from their sources in the caller's frame, the target
  12691. locations in the callee's frame might collide with the sources for
  12692. later arguments! We solve this problem by using the heap instead of
  12693. the stack for passing more than six arguments, which we describe in
  12694. the Section~\ref{sec:limit-functions-r4}.
  12695. As mentioned above, for a tail call we pop the caller's frame prior to
  12696. making the tail call. The instructions for popping a frame are the
  12697. instructions that we usually place in the conclusion of a
  12698. function. Thus, we also need to place such code immediately before
  12699. each tail call. These instructions include restoring the callee-saved
  12700. registers, so it is fortunate that the argument passing registers are
  12701. all caller-saved registers!
  12702. One last note regarding which instruction to use to make the tail
  12703. call. When the callee is finished, it should not return to the current
  12704. function, but it should return to the function that called the current
  12705. one. Thus, the return address that is already on the stack is the
  12706. right one, and we should not use \key{callq} to make the tail call, as
  12707. that would unnecessarily overwrite the return address. Instead we can
  12708. simply use the \key{jmp} instruction. Like the indirect function call,
  12709. we write an \emph{indirect jump}\index{subject}{indirect jump} with a
  12710. register prefixed with an asterisk. We recommend using \code{rax} to
  12711. hold the jump target because the preceding conclusion can overwrite
  12712. just about everything else.
  12713. \begin{lstlisting}
  12714. jmp *%rax
  12715. \end{lstlisting}
  12716. \section{Shrink \LangFun{}}
  12717. \label{sec:shrink-r4}
  12718. The \code{shrink} pass performs a minor modification to ease the
  12719. later passes. This pass introduces an explicit \code{main} function
  12720. that gobbles up all the top-level statements of the module.
  12721. %
  12722. \racket{It also changes the top \code{ProgramDefsExp} form to
  12723. \code{ProgramDefs}.}
  12724. {\if\edition\racketEd
  12725. \begin{lstlisting}
  12726. (ProgramDefsExp |$\itm{info}$| (|$\Def\ldots$|) |$\Exp$|)
  12727. |$\Rightarrow$| (ProgramDefs |$\itm{info}$| (|$\Def\ldots$| |$\itm{mainDef}$|))
  12728. \end{lstlisting}
  12729. where $\itm{mainDef}$ is
  12730. \begin{lstlisting}
  12731. (Def 'main '() 'Integer '() |$\Exp'$|)
  12732. \end{lstlisting}
  12733. \fi}
  12734. {\if\edition\pythonEd
  12735. \begin{lstlisting}
  12736. Module(|$\Def\ldots\Stmt\ldots$|)
  12737. |$\Rightarrow$| Module(|$\Def\ldots\itm{mainDef}$|)
  12738. \end{lstlisting}
  12739. where $\itm{mainDef}$ is
  12740. \begin{lstlisting}
  12741. FunctionDef('main', [], int, None, |$\Stmt\ldots$|Return(Constant(0)), None)
  12742. \end{lstlisting}
  12743. \fi}
  12744. \section{Reveal Functions and the \LangFunRef{} language}
  12745. \label{sec:reveal-functions-r4}
  12746. The syntax of \LangFun{} is inconvenient for purposes of compilation
  12747. in that it conflates the use of function names and local
  12748. variables. This is a problem because we need to compile the use of a
  12749. function name differently than the use of a local variable; we need to
  12750. use \code{leaq} to convert the function name (a label in x86) to an
  12751. address in a register. Thus, we create a new pass that changes
  12752. function references from $\VAR{f}$ to $\FUNREF{f}{n}$ where $n$ is the
  12753. arity of the function.\python{\footnote{The arity is not needed in this
  12754. chapter but is used in Chapter~\ref{ch:Ldyn}.}} This pass is
  12755. named \code{reveal\_functions} and the output language, \LangFunRef{},
  12756. is defined in Figure~\ref{fig:f1-syntax}.
  12757. %% The concrete syntax for a
  12758. %% function reference is $\CFUNREF{f}$.
  12759. \begin{figure}[tp]
  12760. \centering
  12761. \fbox{
  12762. \begin{minipage}{0.96\textwidth}
  12763. {\if\edition\racketEd
  12764. \[
  12765. \begin{array}{lcl}
  12766. \Exp &::=& \ldots \MID \FUNREF{\Var}{\Int}\\
  12767. \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12768. \LangFunRefM{} &::=& \PROGRAMDEFS{\code{'()}}{\LP \Def\ldots \RP}
  12769. \end{array}
  12770. \]
  12771. \fi}
  12772. {\if\edition\pythonEd
  12773. \[
  12774. \begin{array}{lcl}
  12775. \Exp &::=& \FUNREF{\Var}{\Int}\\
  12776. \LangFunRefM{} &::=& \PROGRAM{}{\LS \Def \code{,} \ldots \RS}
  12777. \end{array}
  12778. \]
  12779. \fi}
  12780. \end{minipage}
  12781. }
  12782. \caption{The abstract syntax \LangFunRef{}, an extension of \LangFun{}
  12783. (Figure~\ref{fig:Rfun-syntax}).}
  12784. \label{fig:f1-syntax}
  12785. \end{figure}
  12786. %% Distinguishing between calls in tail position and non-tail position
  12787. %% requires the pass to have some notion of context. We recommend using
  12788. %% two mutually recursive functions, one for processing expressions in
  12789. %% tail position and another for the rest.
  12790. \racket{Placing this pass after \code{uniquify} will make sure that
  12791. there are no local variables and functions that share the same
  12792. name.}
  12793. %
  12794. The \code{reveal\_functions} pass should come before the
  12795. \code{remove\_complex\_operands} pass because function references
  12796. should be categorized as complex expressions.
  12797. \section{Limit Functions}
  12798. \label{sec:limit-functions-r4}
  12799. Recall that we wish to limit the number of function parameters to six
  12800. so that we do not need to use the stack for argument passing, which
  12801. makes it easier to implement efficient tail calls. However, because
  12802. the input language \LangFun{} supports arbitrary numbers of function
  12803. arguments, we have some work to do!
  12804. This pass transforms functions and function calls that involve more
  12805. than six arguments to pass the first five arguments as usual, but it
  12806. packs the rest of the arguments into a vector and passes it as the
  12807. sixth argument.
  12808. Each function definition with seven or more parameters is transformed as
  12809. follows.
  12810. {\if\edition\racketEd
  12811. \begin{lstlisting}
  12812. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_n$|:|$T_n$|]) |$T_r$| |$\itm{info}$| |$\itm{body}$|)
  12813. |$\Rightarrow$|
  12814. (Def |$f$| ([|$x_1$|:|$T_1$|] |$\ldots$| [|$x_5$|:|$T_5$|] [tup : (Vector |$T_6 \ldots T_n$|)]) |$T_r$| |$\itm{info}$| |$\itm{body}'$|)
  12815. \end{lstlisting}
  12816. \fi}
  12817. {\if\edition\pythonEd
  12818. \begin{lstlisting}
  12819. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_n$|,|$T_n$|)], |$T_r$|, None, |$\itm{body}$|, None)
  12820. |$\Rightarrow$|
  12821. FunctionDef(|$f$|, [(|$x_1$|,|$T_1$|),|$\ldots$|,(|$x_5$|,|$T_5$|),(tup,TupleType([|$T_6, \ldots, T_n$|]))],
  12822. |$T_r$|, None, |$\itm{body}'$|, None)
  12823. \end{lstlisting}
  12824. \fi}
  12825. %
  12826. \noindent where the $\itm{body}$ is transformed into $\itm{body}'$ by
  12827. replacing the occurrences of each parameter $x_i$ where $i > 5$ with
  12828. the $k$th element of the tuple, where $k = i - 6$.
  12829. %
  12830. {\if\edition\racketEd
  12831. \begin{lstlisting}
  12832. (Var |$x_i$|) |$\Rightarrow$| (Prim 'vector-ref (list tup (Int |$k$|)))
  12833. \end{lstlisting}
  12834. \fi}
  12835. {\if\edition\pythonEd
  12836. \begin{lstlisting}
  12837. Name(|$x_i$|) |$\Rightarrow$| Subscript(tup, Constant(|$k$|), Load())
  12838. \end{lstlisting}
  12839. \fi}
  12840. For function calls with too many arguments, the \code{limit\_functions}
  12841. pass transforms them in the following way.
  12842. \begin{tabular}{lll}
  12843. \begin{minipage}{0.3\textwidth}
  12844. {\if\edition\racketEd
  12845. \begin{lstlisting}
  12846. (|$e_0$| |$e_1$| |$\ldots$| |$e_n$|)
  12847. \end{lstlisting}
  12848. \fi}
  12849. {\if\edition\pythonEd
  12850. \begin{lstlisting}
  12851. Call(|$e_0$|, [|$e_1,\ldots,e_n$|])
  12852. \end{lstlisting}
  12853. \fi}
  12854. \end{minipage}
  12855. &
  12856. $\Rightarrow$
  12857. &
  12858. \begin{minipage}{0.5\textwidth}
  12859. {\if\edition\racketEd
  12860. \begin{lstlisting}
  12861. (|$e_0$| |$e_1 \ldots e_5$| (vector |$e_6 \ldots e_n$|))
  12862. \end{lstlisting}
  12863. \fi}
  12864. {\if\edition\pythonEd
  12865. \begin{lstlisting}
  12866. Call(|$e_0$|, [|$e_1,\ldots,e_5$|,Tuple([|$e_6,\ldots,e_n$|])])
  12867. \end{lstlisting}
  12868. \fi}
  12869. \end{minipage}
  12870. \end{tabular}
  12871. \section{Remove Complex Operands}
  12872. \label{sec:rco-r4}
  12873. The primary decisions to make for this pass is whether to classify
  12874. \code{FunRef} and \racket{\code{Apply}}\python{\code{Call}} as either
  12875. atomic or complex expressions. Recall that a simple expression will
  12876. eventually end up as just an immediate argument of an x86
  12877. instruction. Function application will be translated to a sequence of
  12878. instructions, so \racket{\code{Apply}}\python{\code{Call}} must be
  12879. classified as complex expression. On the other hand, the arguments of
  12880. \racket{\code{Apply}}\python{\code{Call}} should be atomic expressions.
  12881. %
  12882. Regarding \code{FunRef}, as discussed above, the function label needs
  12883. to be converted to an address using the \code{leaq} instruction. Thus,
  12884. even though \code{FunRef} seems rather simple, it needs to be
  12885. classified as a complex expression so that we generate an assignment
  12886. statement with a left-hand side that can serve as the target of the
  12887. \code{leaq}.
  12888. The output of this pass, \LangFunANF{}, extends \LangAllocANF{}
  12889. (Figure~\ref{fig:Lvec-anf-syntax}) with \code{FunRef}
  12890. and \racket{\code{Apply}}\python{\code{Call}} in the grammar for expressions.
  12891. %
  12892. \python{Also, \LangFunANF{} adds \code{Return} to the grammar for statements.}
  12893. % TODO: Return?
  12894. %% Figure~\ref{fig:Rfun-anf-syntax} defines the output language
  12895. %% \LangFunANF{} of this pass.
  12896. %% \begin{figure}[tp]
  12897. %% \centering
  12898. %% \fbox{
  12899. %% \begin{minipage}{0.96\textwidth}
  12900. %% \small
  12901. %% \[
  12902. %% \begin{array}{rcl}
  12903. %% \Atm &::=& \gray{ \INT{\Int} \MID \VAR{\Var} \MID \BOOL{\itm{bool}}
  12904. %% \MID \VOID{} } \\
  12905. %% \Exp &::=& \gray{ \Atm \MID \READ{} } \\
  12906. %% &\MID& \gray{ \NEG{\Atm} \MID \ADD{\Atm}{\Atm} } \\
  12907. %% &\MID& \gray{ \LET{\Var}{\Exp}{\Exp} } \\
  12908. %% &\MID& \gray{ \UNIOP{\key{'not}}{\Atm} } \\
  12909. %% &\MID& \gray{ \BINOP{\itm{cmp}}{\Atm}{\Atm} \MID \IF{\Exp}{\Exp}{\Exp} }\\
  12910. %% &\MID& \gray{ \LP\key{Collect}~\Int\RP \MID \LP\key{Allocate}~\Int~\Type\RP
  12911. %% \MID \LP\key{GlobalValue}~\Var\RP }\\
  12912. %% &\MID& \FUNREF{\Var} \MID \APPLY{\Atm}{\Atm\ldots}\\
  12913. %% \Def &::=& \gray{ \FUNDEF{\Var}{([\Var \code{:} \Type]\ldots)}{\Type}{\code{'()}}{\Exp} }\\
  12914. %% R^{\dagger}_4 &::=& \gray{ \PROGRAMDEFS{\code{'()}}{\Def} }
  12915. %% \end{array}
  12916. %% \]
  12917. %% \end{minipage}
  12918. %% }
  12919. %% \caption{\LangFunANF{} is \LangFunRefAlloc{} in monadic normal form.}
  12920. %% \label{fig:Rfun-anf-syntax}
  12921. %% \end{figure}
  12922. \section{Explicate Control and the \LangCFun{} language}
  12923. \label{sec:explicate-control-r4}
  12924. Figure~\ref{fig:c3-syntax} defines the abstract syntax for \LangCFun{}, the
  12925. output of \code{explicate\_control}.
  12926. %
  12927. \racket{(The concrete syntax is given in
  12928. Figure~\ref{fig:c3-concrete-syntax} of the Appendix.)}
  12929. %
  12930. The auxiliary functions for assignment\racket{and tail contexts} should
  12931. be updated with cases for
  12932. \racket{\code{Apply}}\python{\code{Call}} and \code{FunRef} and the
  12933. function for predicate context should be updated for
  12934. \racket{\code{Apply}}\python{\code{Call}} but not \code{FunRef}. (A
  12935. \code{FunRef} cannot be a Boolean.) In assignment and predicate
  12936. contexts, \code{Apply} becomes \code{Call}\racket{, whereas in tail position
  12937. \code{Apply} becomes \code{TailCall}}. We recommend defining a new
  12938. auxiliary function for processing function definitions. This code is
  12939. similar to the case for \code{Program} in \LangVec{}. The top-level
  12940. \code{explicate\_control} function that handles the \code{ProgramDefs}
  12941. form of \LangFun{} can then apply this new function to all the
  12942. function definitions.
  12943. {\if\edition\pythonEd
  12944. The translation of \code{Return} statements requires a new auxiliary
  12945. function to handle expressions in tail context, called
  12946. \code{explicate\_tail}. The function should take an expression and the
  12947. dictionary of basic blocks and produce a list of statements in the
  12948. \LangCFun{} language. The \code{explicate\_tail} function should
  12949. include cases for \code{Begin}, \code{IfExp}, \code{Let}, \code{Call},
  12950. and a default case for other kinds of expressions. The default case
  12951. should produce a \code{Return} statement. The case for \code{Call}
  12952. should change it into \code{TailCall}. The other cases should
  12953. recursively process their subexpressions and statements, choosing the
  12954. appropriate explicate functions for the various contexts.
  12955. \fi}
  12956. \newcommand{\CfunASTRacket}{
  12957. \begin{array}{lcl}
  12958. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\LP\Atm\ldots\RP} \\
  12959. \Tail &::= & \TAILCALL{\Atm}{\Atm\ldots} \\
  12960. \Def &::=& \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP}
  12961. \end{array}
  12962. }
  12963. \newcommand{\CfunASTPython}{
  12964. \begin{array}{lcl}
  12965. \Exp &::= & \FUNREF{\itm{label}}{\Int} \MID \CALL{\Atm}{\Atm^{*}} \\
  12966. \Stmt &::= & \TAILCALL{\Atm}{\Atm^{*}} \\
  12967. \Params &::=& \LS\LP\Var\key{,}\Type\RP\code{,}\ldots\RS \\
  12968. \Block &::=& \itm{label}\key{:} \Stmt^{*} \\
  12969. \Blocks &::=& \LC\Block\code{,}\ldots\RC \\
  12970. \Def &::=& \DEF{\itm{label}}{\Params}{\Blocks}{\key{None}}{\Type}{\key{None}}
  12971. \end{array}
  12972. }
  12973. \begin{figure}[tp]
  12974. \fbox{
  12975. \begin{minipage}{0.96\textwidth}
  12976. \small
  12977. {\if\edition\racketEd
  12978. \[
  12979. \begin{array}{l}
  12980. \gray{\CvarASTRacket} \\ \hline
  12981. \gray{\CifASTRacket} \\ \hline
  12982. \gray{\CloopASTRacket} \\ \hline
  12983. \gray{\CtupASTRacket} \\ \hline
  12984. \CfunASTRacket \\
  12985. \begin{array}{lcl}
  12986. \LangCFunM{} & ::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  12987. \end{array}
  12988. \end{array}
  12989. \]
  12990. \fi}
  12991. {\if\edition\pythonEd
  12992. \[
  12993. \begin{array}{l}
  12994. \gray{\CifASTPython} \\ \hline
  12995. \gray{\CtupASTPython} \\ \hline
  12996. \CfunASTPython \\
  12997. \begin{array}{lcl}
  12998. \LangCFunM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  12999. \end{array}
  13000. \end{array}
  13001. \]
  13002. \fi}
  13003. \end{minipage}
  13004. }
  13005. \caption{The abstract syntax of \LangCFun{}, extending \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  13006. \label{fig:c3-syntax}
  13007. \end{figure}
  13008. \section{Select Instructions and the \LangXIndCall{} Language}
  13009. \label{sec:select-r4}
  13010. \index{subject}{instruction selection}
  13011. The output of select instructions is a program in the \LangXIndCall{}
  13012. language, whose syntax is defined in Figure~\ref{fig:x86-3}.
  13013. \index{subject}{x86}
  13014. \begin{figure}[tp]
  13015. \fbox{
  13016. \begin{minipage}{0.96\textwidth}
  13017. \small
  13018. \[
  13019. \begin{array}{lcl}
  13020. \Arg &::=& \gray{ \key{\$}\Int \MID \key{\%}\Reg \MID \Int\key{(}\key{\%}\Reg\key{)} \MID \key{\%}\itm{bytereg} } \MID \Var \key{(\%rip)} \\
  13021. \itm{cc} & ::= & \gray{ \key{e} \MID \key{ne} \MID \key{l} \MID \key{le} \MID \key{g} \MID \key{ge} } \\
  13022. \Instr &::=& \ldots
  13023. \MID \key{callq}\;\key{*}\Arg \MID \key{tailjmp}\;\Arg
  13024. \MID \key{leaq}\;\Arg\key{,}\;\key{\%}\Reg \\
  13025. \Block &::= & \itm{label}\key{:}\, \Instr^{*} \\
  13026. \Def &::= & \key{.globl}\,\itm{label}\; \Block^{*} \\
  13027. \LangXIndCallM{} &::= & \Def\ldots
  13028. \end{array}
  13029. \]
  13030. \end{minipage}
  13031. }
  13032. \caption{The concrete syntax of \LangXIndCall{} (extends \LangXGlobal{} of Figure~\ref{fig:x86-2-concrete}).}
  13033. \label{fig:x86-3-concrete}
  13034. \end{figure}
  13035. \begin{figure}[tp]
  13036. \fbox{
  13037. \begin{minipage}{0.96\textwidth}
  13038. \small
  13039. {\if\edition\racketEd
  13040. \[
  13041. \begin{array}{lcl}
  13042. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13043. \MID \BYTEREG{\Reg} } \\
  13044. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13045. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13046. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13047. &\MID& \BININSTR{\code{'leaq}}{\Arg}{\REG{\Reg}}\\
  13048. \Block &::= & \BLOCK{\itm{info}}{\LP\Instr\ldots\RP}\\
  13049. \Def &::= & \DEF{\itm{label}}{\code{'()}}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Block\RP\ldots\RP} \\
  13050. \LangXIndCallM{} &::= & \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP}
  13051. \end{array}
  13052. \]
  13053. \fi}
  13054. {\if\edition\pythonEd
  13055. \[
  13056. \begin{array}{lcl}
  13057. \Arg &::=& \gray{ \INT{\Int} \MID \REG{\Reg} \MID \DEREF{\Reg}{\Int}
  13058. \MID \BYTEREG{\Reg} } \\
  13059. &\MID& \gray{ \GLOBAL{\Var} } \MID \FUNREF{\itm{label}}{\Int} \\
  13060. \Instr &::=& \ldots \MID \INDCALLQ{\Arg}{\itm{int}}
  13061. \MID \TAILJMP{\Arg}{\itm{int}}\\
  13062. &\MID& \BININSTR{\scode{leaq}}{\Arg}{\REG{\Reg}}\\
  13063. \Block &::=&\itm{label}\key{:}\,\Instr^{*} \\
  13064. \Blocks &::= & \LC\Block\code{,}\ldots\RC\\
  13065. \Def &::= & \DEF{\itm{label}}{\LS\RS}{\Blocks}{\_}{\Type}{\_} \\
  13066. \LangXIndCallM{} &::= & \XPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  13067. \end{array}
  13068. \]
  13069. \fi}
  13070. \end{minipage}
  13071. }
  13072. \caption{The abstract syntax of \LangXIndCall{} (extends
  13073. \LangXGlobal{} of Figure~\ref{fig:x86-2}).}
  13074. \label{fig:x86-3}
  13075. \end{figure}
  13076. An assignment of a function reference to a variable becomes a
  13077. load-effective-address instruction as follows, where $\itm{lhs}'$
  13078. is the translation of $\itm{lhs}$ from \Atm{} in \LangCFun{}
  13079. to \Arg{} in \LangXIndCallVar{}. \\
  13080. \begin{tabular}{lcl}
  13081. \begin{minipage}{0.35\textwidth}
  13082. {\if\edition\racketEd
  13083. \begin{lstlisting}
  13084. |$\itm{lhs}$| = (fun-ref |$f$| |$n$|);
  13085. \end{lstlisting}
  13086. \fi}
  13087. {\if\edition\pythonEd
  13088. \begin{lstlisting}
  13089. |$\itm{lhs}$| = FunRef(|$f$|, |$n$|);
  13090. \end{lstlisting}
  13091. \fi}
  13092. \end{minipage}
  13093. &
  13094. $\Rightarrow$\qquad\qquad
  13095. &
  13096. \begin{minipage}{0.3\textwidth}
  13097. {\if\edition\racketEd
  13098. \begin{lstlisting}
  13099. leaq (fun-ref |$f$| |$n$|), |$\itm{lhs}'$|
  13100. \end{lstlisting}
  13101. \fi}
  13102. {\if\edition\pythonEd
  13103. \begin{lstlisting}
  13104. leaq |$f$|(%rip), |$\itm{lhs}'$|
  13105. \end{lstlisting}
  13106. \fi}
  13107. \end{minipage}
  13108. \end{tabular} \\
  13109. Regarding function definitions, we need to remove the parameters and
  13110. instead perform parameter passing using the conventions discussed in
  13111. Section~\ref{sec:fun-x86}. That is, the arguments are passed in
  13112. registers. We recommend turning the parameters into local variables
  13113. and generating instructions at the beginning of the function to move
  13114. from the argument passing registers to these local variables.
  13115. {\if\edition\racketEd
  13116. \begin{lstlisting}
  13117. (Def |$f$| '([|$x_1$| : |$T_1$|] [|$x_2$| : |$T_2$|] |$\ldots$| ) |$T_r$| |$\itm{info}$| |$B$|)
  13118. |$\Rightarrow$|
  13119. (Def |$f$| '() 'Integer |$\itm{info}'$| |$B'$|)
  13120. \end{lstlisting}
  13121. \fi}
  13122. {\if\edition\pythonEd
  13123. \begin{lstlisting}
  13124. FunctionDef(|$f$|, [|$(x_1,T_1),\ldots$|], |$B$|, _, |$T_r$|, _)
  13125. |$\Rightarrow$|
  13126. FunctionDef(|$f$|, [], |$B'$|, _, int, _)
  13127. \end{lstlisting}
  13128. \fi}
  13129. The basic blocks $B'$ are the same as $B$ except that the
  13130. \code{start} block is modified to add the instructions for moving from
  13131. the argument registers to the parameter variables. So the \code{start}
  13132. block of $B$ shown on the left is changed to the code on the right.
  13133. \begin{center}
  13134. \begin{minipage}{0.3\textwidth}
  13135. \begin{lstlisting}
  13136. start:
  13137. |$\itm{instr}_1$|
  13138. |$\cdots$|
  13139. |$\itm{instr}_n$|
  13140. \end{lstlisting}
  13141. \end{minipage}
  13142. $\Rightarrow$
  13143. \begin{minipage}{0.3\textwidth}
  13144. \begin{lstlisting}
  13145. start:
  13146. movq %rdi, |$x_1$|
  13147. |$\cdots$|
  13148. |$\itm{instr}_1$|
  13149. |$\cdots$|
  13150. |$\itm{instr}_n$|
  13151. \end{lstlisting}
  13152. \end{minipage}
  13153. \end{center}
  13154. \racket{The interpreter for \LangXIndCall{} needs to know how many
  13155. parameters the function expects, but the parameters are no longer in
  13156. the syntax of function definitions. Instead, add an entry to
  13157. $\itm{info}$ that maps \code{num-params} to the number of parameters
  13158. to construct $\itm{info}'$.}
  13159. By changing the parameters to local variables, we are giving the
  13160. register allocator control over which registers or stack locations to
  13161. use for them. If you implemented the move-biasing challenge
  13162. (Section~\ref{sec:move-biasing}), the register allocator will try to
  13163. assign the parameter variables to the corresponding argument register,
  13164. in which case the \code{patch\_instructions} pass will remove the
  13165. \code{movq} instruction. This happens in the example translation in
  13166. Figure~\ref{fig:add-fun} of Section~\ref{sec:functions-example}, in
  13167. the \code{add} function.
  13168. %
  13169. Also, note that the register allocator will perform liveness analysis
  13170. on this sequence of move instructions and build the interference
  13171. graph. So, for example, $x_1$ will be marked as interfering with
  13172. \code{rsi} and that will prevent the assignment of $x_1$ to
  13173. \code{rsi}, which is good, because that would overwrite the argument
  13174. that needs to move into $x_2$.
  13175. Next, consider the compilation of function calls. In the mirror image
  13176. of handling the parameters of function definitions, the arguments need
  13177. to be moved to the argument passing registers. The function call
  13178. itself is performed with an indirect function call. The return value
  13179. from the function is stored in \code{rax}, so it needs to be moved
  13180. into the \itm{lhs}.
  13181. \begin{lstlisting}
  13182. |\itm{lhs}| = |$\CALL{\itm{fun}}{\itm{arg}_1\ldots}$|
  13183. |$\Rightarrow$|
  13184. movq |$\itm{arg}_1$|, %rdi
  13185. movq |$\itm{arg}_2$|, %rsi
  13186. |$\vdots$|
  13187. callq *|\itm{fun}|
  13188. movq %rax, |\itm{lhs}|
  13189. \end{lstlisting}
  13190. The \code{IndirectCallq} AST node includes an integer for the arity of
  13191. the function, i.e., the number of parameters. That information is
  13192. useful in the \code{uncover\_live} pass for determining which
  13193. argument-passing registers are potentially read during the call.
  13194. For tail calls, the parameter passing is the same as non-tail calls:
  13195. generate instructions to move the arguments into the argument
  13196. passing registers. After that we need to pop the frame from the
  13197. procedure call stack. However, we do not yet know how big the frame
  13198. is; that gets determined during register allocation. So instead of
  13199. generating those instructions here, we invent a new instruction that
  13200. means ``pop the frame and then do an indirect jump'', which we name
  13201. \code{TailJmp}. The abstract syntax for this instruction includes an
  13202. argument that specifies where to jump and an integer that represents
  13203. the arity of the function being called.
  13204. Recall that we use the label \code{start} for the initial block of a
  13205. program, and in Section~\ref{sec:select-Lvar} we recommend labeling
  13206. the conclusion of the program with \code{conclusion}, so that
  13207. $\RETURN{Arg}$ can be compiled to an assignment to \code{rax} followed
  13208. by a jump to \code{conclusion}. With the addition of function
  13209. definitions, there is a start block and conclusion for each function,
  13210. but their labels need to be unique. We recommend prepending the
  13211. function's name to \code{start} and \code{conclusion}, respectively,
  13212. to obtain unique labels.
  13213. \section{Register Allocation}
  13214. \label{sec:register-allocation-r4}
  13215. \subsection{Liveness Analysis}
  13216. \label{sec:liveness-analysis-r4}
  13217. \index{subject}{liveness analysis}
  13218. %% The rest of the passes need only minor modifications to handle the new
  13219. %% kinds of AST nodes: \code{fun-ref}, \code{indirect-callq}, and
  13220. %% \code{leaq}.
  13221. The \code{IndirectCallq} instruction should be treated like
  13222. \code{Callq} regarding its written locations $W$, in that they should
  13223. include all the caller-saved registers. Recall that the reason for
  13224. that is to force variables that are live across a function call to be assigned to callee-saved
  13225. registers or to be spilled to the stack.
  13226. Regarding the set of read locations $R$, the arity field of
  13227. \code{TailJmp} and \code{IndirectCallq} determines how many of the
  13228. argument-passing registers should be considered as read by those
  13229. instructions. Also, the target field of \code{TailJmp} and
  13230. \code{IndirectCallq} should be included in the set of read locations
  13231. $R$.
  13232. \subsection{Build Interference Graph}
  13233. \label{sec:build-interference-r4}
  13234. With the addition of function definitions, we compute a separate interference
  13235. graph for each function (not just one for the whole program).
  13236. Recall that in Section~\ref{sec:reg-alloc-gc} we discussed the need to
  13237. spill vector-typed variables that are live during a call to
  13238. \code{collect}, the garbage collector. With the addition of functions to our language, we
  13239. need to revisit this issue. Functions that perform allocation contain
  13240. calls to the collector. Thus, we should
  13241. not only spill a vector-typed variable when it is live during a call
  13242. to \code{collect}, but we should spill the variable if it is live
  13243. during call to a user-defined function. Thus, in the \code{build\_interference} pass,
  13244. we recommend adding interference edges between call-live vector-typed
  13245. variables and the callee-saved registers (in addition to the usual
  13246. addition of edges between call-live variables and the caller-saved
  13247. registers).
  13248. \subsection{Allocate Registers}
  13249. The primary change to the \code{allocate\_registers} pass is adding an
  13250. auxiliary function for handling definitions (the \Def{} non-terminal
  13251. in Figure~\ref{fig:x86-3}) with one case for function definitions. The
  13252. logic is the same as described in
  13253. Chapter~\ref{ch:register-allocation-Lvar}, except now register
  13254. allocation is performed many times, once for each function definition,
  13255. instead of just once for the whole program.
  13256. \section{Patch Instructions}
  13257. In \code{patch\_instructions}, you should deal with the x86
  13258. idiosyncrasy that the destination argument of \code{leaq} must be a
  13259. register. Additionally, you should ensure that the argument of
  13260. \code{TailJmp} is \itm{rax}, our reserved register---mostly to make
  13261. code generation more convenient, because we trample many registers
  13262. before the tail call (as explained in the next section).
  13263. \section{Prelude and Conclusion}
  13264. %% For the \code{print\_x86} pass, the cases for \code{FunRef} and
  13265. %% \code{IndirectCallq} are straightforward: output their concrete
  13266. %% syntax.
  13267. %% \begin{lstlisting}
  13268. %% (FunRef |\itm{label}|) |$\Rightarrow$| |\itm{label}|(%rip)
  13269. %% (IndirectCallq |\itm{arg}| |\itm{int}|) |$\Rightarrow$| callq *|\itm{arg}'|
  13270. %% \end{lstlisting}
  13271. Now that register allocation is complete, we can translate the
  13272. \code{TailJmp} into a sequence of instructions. A straightforward
  13273. translation of \code{TailJmp} would simply be \code{jmp *$\itm{arg}$}.
  13274. However, before the jump we need to pop the current frame. This
  13275. sequence of instructions is the same as the code for the conclusion of
  13276. a function, except the \code{retq} is replaced with \code{jmp *$\itm{arg}$}.
  13277. Regarding function definitions, you need to generate a prelude
  13278. and conclusion for each one. This code is similar to the prelude and
  13279. conclusion generated for the \code{main} function in
  13280. Chapter~\ref{ch:Lvec}. To review, the prelude of every function
  13281. should carry out the following steps.
  13282. % TODO: .align the functions!
  13283. \begin{enumerate}
  13284. %% \item Start with \code{.global} and \code{.align} directives followed
  13285. %% by the label for the function. (See Figure~\ref{fig:add-fun} for an
  13286. %% example.)
  13287. \item Push \code{rbp} to the stack and set \code{rbp} to current stack
  13288. pointer.
  13289. \item Push to the stack all of the callee-saved registers that were
  13290. used for register allocation.
  13291. \item Move the stack pointer \code{rsp} down by the size of the stack
  13292. frame for this function, which depends on the number of regular
  13293. spills. (Aligned to 16 bytes.)
  13294. \item Move the root stack pointer \code{r15} up by the size of the
  13295. root-stack frame for this function, which depends on the number of
  13296. spilled vectors. \label{root-stack-init}
  13297. \item Initialize to zero all new entries in the root-stack frame.
  13298. \item Jump to the start block.
  13299. \end{enumerate}
  13300. The prelude of the \code{main} function has one additional task: call
  13301. the \code{initialize} function to set up the garbage collector and
  13302. move the value of the global \code{rootstack\_begin} in
  13303. \code{r15}. This initialization should happen before step \ref{root-stack-init}
  13304. above, which depends on \code{r15}.
  13305. The conclusion of every function should do the following.
  13306. \begin{enumerate}
  13307. \item Move the stack pointer back up by the size of the stack frame
  13308. for this function.
  13309. \item Restore the callee-saved registers by popping them from the
  13310. stack.
  13311. \item Move the root stack pointer back down by the size of the
  13312. root-stack frame for this function.
  13313. \item Restore \code{rbp} by popping it from the stack.
  13314. \item Return to the caller with the \code{retq} instruction.
  13315. \end{enumerate}
  13316. \begin{exercise}\normalfont\normalsize
  13317. Expand your compiler to handle \LangFun{} as outlined in this chapter.
  13318. Create 5 new programs that use functions, including examples that pass
  13319. functions and return functions from other functions, recursive
  13320. functions, functions that create vectors, and functions that make tail
  13321. calls. Test your compiler on these new programs and all of your
  13322. previously created test programs.
  13323. \end{exercise}
  13324. \begin{figure}[tbp]
  13325. \begin{tikzpicture}[baseline=(current bounding box.center)]
  13326. \node (Rfun) at (0,2) {\large \LangFun{}};
  13327. \node (Rfun-1) at (3,2) {\large \LangFun{}};
  13328. \node (Rfun-2) at (6,2) {\large \LangFun{}};
  13329. \node (F1-1) at (9,2) {\large \LangFunRef{}};
  13330. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  13331. \node (F1-3) at (6,0) {\large \LangFunRefAlloc{}};
  13332. \node (F1-4) at (3,0) {\large \LangFunANF{}};
  13333. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  13334. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  13335. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  13336. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  13337. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  13338. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  13339. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  13340. \path[->,bend left=15] (Rfun) edge [above] node
  13341. {\ttfamily\footnotesize shrink} (Rfun-1);
  13342. \path[->,bend left=15] (Rfun-1) edge [above] node
  13343. {\ttfamily\footnotesize uniquify} (Rfun-2);
  13344. \path[->,bend left=15] (Rfun-2) edge [above] node
  13345. {\ttfamily\footnotesize ~~reveal\_functions} (F1-1);
  13346. \path[->,bend left=15] (F1-1) edge [right] node
  13347. {\ttfamily\footnotesize limit\_functions} (F1-2);
  13348. \path[->,bend right=15] (F1-2) edge [above] node
  13349. {\ttfamily\footnotesize expose\_alloc.} (F1-3);
  13350. \path[->,bend right=15] (F1-3) edge [above] node
  13351. {\ttfamily\footnotesize remove\_complex.} (F1-4);
  13352. \path[->,bend left=15] (F1-4) edge [right] node
  13353. {\ttfamily\footnotesize explicate\_control} (C3-2);
  13354. \path[->,bend right=15] (C3-2) edge [left] node
  13355. {\ttfamily\footnotesize select\_instr.} (x86-2);
  13356. \path[->,bend left=15] (x86-2) edge [left] node
  13357. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  13358. \path[->,bend right=15] (x86-2-1) edge [below] node
  13359. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  13360. \path[->,bend right=15] (x86-2-2) edge [left] node
  13361. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  13362. \path[->,bend left=15] (x86-3) edge [above] node
  13363. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  13364. \path[->,bend right=15] (x86-4) edge [left] node {\ttfamily\footnotesize print-x86} (x86-5);
  13365. \end{tikzpicture}
  13366. \caption{Diagram of the passes for \LangFun{}, a language with functions.}
  13367. \label{fig:Rfun-passes}
  13368. \end{figure}
  13369. Figure~\ref{fig:Rfun-passes} gives an overview of the passes for
  13370. compiling \LangFun{} to x86.
  13371. \section{An Example Translation}
  13372. \label{sec:functions-example}
  13373. Figure~\ref{fig:add-fun} shows an example translation of a simple
  13374. function in \LangFun{} to x86. The figure also includes the results of the
  13375. \code{explicate\_control} and \code{select\_instructions} passes.
  13376. \begin{figure}[htbp]
  13377. \begin{tabular}{ll}
  13378. \begin{minipage}{0.4\textwidth}
  13379. % s3_2.rkt
  13380. {\if\edition\racketEd
  13381. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13382. (define (add [x : Integer] [y : Integer])
  13383. : Integer
  13384. (+ x y))
  13385. (add 40 2)
  13386. \end{lstlisting}
  13387. \fi}
  13388. {\if\edition\pythonEd
  13389. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13390. def add(x:int, y:int) -> int:
  13391. return x + y
  13392. print(add(40, 2))
  13393. \end{lstlisting}
  13394. \fi}
  13395. $\Downarrow$
  13396. {\if\edition\racketEd
  13397. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13398. (define (add86 [x87 : Integer]
  13399. [y88 : Integer]) : Integer
  13400. add86start:
  13401. return (+ x87 y88);
  13402. )
  13403. (define (main) : Integer ()
  13404. mainstart:
  13405. tmp89 = (fun-ref add86 2);
  13406. (tail-call tmp89 40 2)
  13407. )
  13408. \end{lstlisting}
  13409. \fi}
  13410. {\if\edition\pythonEd
  13411. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13412. def add(x:int, y:int) -> int:
  13413. addstart:
  13414. return x + y
  13415. def main() -> int:
  13416. mainstart:
  13417. fun.0 = add
  13418. tmp.1 = fun.0(40, 2)
  13419. print(tmp.1)
  13420. return 0
  13421. \end{lstlisting}
  13422. \fi}
  13423. \end{minipage}
  13424. &
  13425. $\Rightarrow$
  13426. \begin{minipage}{0.5\textwidth}
  13427. {\if\edition\racketEd
  13428. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13429. (define (add86) : Integer
  13430. add86start:
  13431. movq %rdi, x87
  13432. movq %rsi, y88
  13433. movq x87, %rax
  13434. addq y88, %rax
  13435. jmp inc1389conclusion
  13436. )
  13437. (define (main) : Integer
  13438. mainstart:
  13439. leaq (fun-ref add86 2), tmp89
  13440. movq $40, %rdi
  13441. movq $2, %rsi
  13442. tail-jmp tmp89
  13443. )
  13444. \end{lstlisting}
  13445. \fi}
  13446. {\if\edition\pythonEd
  13447. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13448. def add() -> int:
  13449. addstart:
  13450. movq %rdi, x
  13451. movq %rsi, y
  13452. movq x, %rax
  13453. addq y, %rax
  13454. jmp addconclusion
  13455. def main() -> int:
  13456. mainstart:
  13457. leaq add, fun.0
  13458. movq $40, %rdi
  13459. movq $2, %rsi
  13460. callq *fun.0
  13461. movq %rax, tmp.1
  13462. movq tmp.1, %rdi
  13463. callq print_int
  13464. movq $0, %rax
  13465. jmp mainconclusion
  13466. \end{lstlisting}
  13467. \fi}
  13468. $\Downarrow$
  13469. \end{minipage}
  13470. \end{tabular}
  13471. \begin{tabular}{ll}
  13472. \begin{minipage}{0.3\textwidth}
  13473. {\if\edition\racketEd
  13474. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13475. .globl add86
  13476. .align 16
  13477. add86:
  13478. pushq %rbp
  13479. movq %rsp, %rbp
  13480. jmp add86start
  13481. add86start:
  13482. movq %rdi, %rax
  13483. addq %rsi, %rax
  13484. jmp add86conclusion
  13485. add86conclusion:
  13486. popq %rbp
  13487. retq
  13488. \end{lstlisting}
  13489. \fi}
  13490. {\if\edition\pythonEd
  13491. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13492. .align 16
  13493. add:
  13494. pushq %rbp
  13495. movq %rsp, %rbp
  13496. subq $0, %rsp
  13497. jmp addstart
  13498. addstart:
  13499. movq %rdi, %rdx
  13500. movq %rsi, %rcx
  13501. movq %rdx, %rax
  13502. addq %rcx, %rax
  13503. jmp addconclusion
  13504. addconclusion:
  13505. subq $0, %r15
  13506. addq $0, %rsp
  13507. popq %rbp
  13508. retq
  13509. \end{lstlisting}
  13510. \fi}
  13511. \end{minipage}
  13512. &
  13513. \begin{minipage}{0.5\textwidth}
  13514. {\if\edition\racketEd
  13515. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13516. .globl main
  13517. .align 16
  13518. main:
  13519. pushq %rbp
  13520. movq %rsp, %rbp
  13521. movq $16384, %rdi
  13522. movq $16384, %rsi
  13523. callq initialize
  13524. movq rootstack_begin(%rip), %r15
  13525. jmp mainstart
  13526. mainstart:
  13527. leaq add86(%rip), %rcx
  13528. movq $40, %rdi
  13529. movq $2, %rsi
  13530. movq %rcx, %rax
  13531. popq %rbp
  13532. jmp *%rax
  13533. mainconclusion:
  13534. popq %rbp
  13535. retq
  13536. \end{lstlisting}
  13537. \fi}
  13538. {\if\edition\pythonEd
  13539. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  13540. .globl main
  13541. .align 16
  13542. main:
  13543. pushq %rbp
  13544. movq %rsp, %rbp
  13545. subq $0, %rsp
  13546. movq $65536, %rdi
  13547. movq $65536, %rsi
  13548. callq initialize
  13549. movq rootstack_begin(%rip), %r15
  13550. jmp mainstart
  13551. mainstart:
  13552. leaq add(%rip), %rcx
  13553. movq $40, %rdi
  13554. movq $2, %rsi
  13555. callq *%rcx
  13556. movq %rax, %rcx
  13557. movq %rcx, %rdi
  13558. callq print_int
  13559. movq $0, %rax
  13560. jmp mainconclusion
  13561. mainconclusion:
  13562. subq $0, %r15
  13563. addq $0, %rsp
  13564. popq %rbp
  13565. retq
  13566. \end{lstlisting}
  13567. \fi}
  13568. \end{minipage}
  13569. \end{tabular}
  13570. \caption{Example compilation of a simple function to x86.}
  13571. \label{fig:add-fun}
  13572. \end{figure}
  13573. % Challenge idea: inlining! (simple version)
  13574. % Further Reading
  13575. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  13576. \chapter{Lexically Scoped Functions}
  13577. \label{ch:Llambda}
  13578. \index{subject}{lambda}
  13579. \index{subject}{lexical scoping}
  13580. This chapter studies lexically scoped functions. Lexical scoping means
  13581. that a function's body may refer to variables whose binding site is
  13582. outside of the function, in an enclosing scope.
  13583. %
  13584. Consider the example in Figure~\ref{fig:lexical-scoping} written in
  13585. \LangLam{}, which extends \LangFun{} with lexically scoped functions
  13586. using the \key{lambda} form. The body of the \key{lambda} refers to
  13587. three variables: \code{x}, \code{y}, and \code{z}. The binding sites
  13588. for \code{x} and \code{y} are outside of the \key{lambda}. Variable
  13589. \code{y} is \racket{bound by the enclosing \key{let}}\python{a local
  13590. variable of function \code{f}} and \code{x} is a parameter of
  13591. function \code{f}. The \key{lambda} is returned from the function
  13592. \code{f}. The main expression of the program includes two calls to
  13593. \code{f} with different arguments for \code{x}, first \code{5} then
  13594. \code{3}. The functions returned from \code{f} are bound to variables
  13595. \code{g} and \code{h}. Even though these two functions were created by
  13596. the same \code{lambda}, they are really different functions because
  13597. they use different values for \code{x}. Applying \code{g} to \code{11}
  13598. produces \code{20} whereas applying \code{h} to \code{15} produces
  13599. \code{22}. The result of this program is \code{42}.
  13600. \begin{figure}[btp]
  13601. {\if\edition\racketEd
  13602. % lambda_test_21.rkt
  13603. \begin{lstlisting}
  13604. (define (f [x : Integer]) : (Integer -> Integer)
  13605. (let ([y 4])
  13606. (lambda: ([z : Integer]) : Integer
  13607. (+ x (+ y z)))))
  13608. (let ([g (f 5)])
  13609. (let ([h (f 3)])
  13610. (+ (g 11) (h 15))))
  13611. \end{lstlisting}
  13612. \fi}
  13613. {\if\edition\pythonEd
  13614. \begin{lstlisting}
  13615. def f(x : int) -> Callable[[int], int]:
  13616. y = 4
  13617. return lambda z: x + y + z
  13618. g = f(5)
  13619. h = f(3)
  13620. print( g(11) + h(15) )
  13621. \end{lstlisting}
  13622. \fi}
  13623. \caption{Example of a lexically scoped function.}
  13624. \label{fig:lexical-scoping}
  13625. \end{figure}
  13626. The approach that we take for implementing lexically scoped functions
  13627. is to compile them into top-level function definitions, translating
  13628. from \LangLam{} into \LangFun{}. However, the compiler must give
  13629. special treatment to variable occurrences such as \code{x} and
  13630. \code{y} in the body of the \code{lambda} of
  13631. Figure~\ref{fig:lexical-scoping}. After all, an \LangFun{} function
  13632. may not refer to variables defined outside of it. To identify such
  13633. variable occurrences, we review the standard notion of free variable.
  13634. \begin{definition}
  13635. A variable is \textbf{free in expression} $e$ if the variable occurs
  13636. inside $e$ but does not have an enclosing definition that is also in
  13637. $e$.\index{subject}{free variable}
  13638. \end{definition}
  13639. For example, in the expression
  13640. \racket{\code{(+ x (+ y z))}}\python{\code{x + y + z}}
  13641. the variables \code{x}, \code{y}, and \code{z} are all free. On the other hand,
  13642. only \code{x} and \code{y} are free in the following expression
  13643. because \code{z} is defined by the \code{lambda}.
  13644. {\if\edition\racketEd
  13645. \begin{lstlisting}
  13646. (lambda: ([z : Integer]) : Integer
  13647. (+ x (+ y z)))
  13648. \end{lstlisting}
  13649. \fi}
  13650. {\if\edition\pythonEd
  13651. \begin{lstlisting}
  13652. lambda z: x + y + z
  13653. \end{lstlisting}
  13654. \fi}
  13655. %
  13656. So the free variables of a \code{lambda} are the ones that need
  13657. special treatment. We need to transport, at runtime, the values of
  13658. those variables from the point where the \code{lambda} was created to
  13659. the point where the \code{lambda} is applied. An efficient solution to
  13660. the problem, due to \citet{Cardelli:1983aa}, is to bundle the values
  13661. of the free variables together with a function pointer into a tuple,
  13662. an arrangement called a \emph{flat closure} (which we shorten to just
  13663. ``closure'').\index{subject}{closure}\index{subject}{flat closure}
  13664. %
  13665. Fortunately, we have all the ingredients to make closures:
  13666. Chapter~\ref{ch:Lvec} gave us tuples and Chapter~\ref{ch:Lfun} gave us
  13667. function pointers. The function pointer resides at index $0$ and the
  13668. values for the free variables fill in the rest of the tuple.
  13669. Let us revisit the example in Figure~\ref{fig:lexical-scoping} to see
  13670. how closures work. It's a three-step dance. The program calls function
  13671. \code{f}, which creates a closure for the \code{lambda}. The closure
  13672. is a tuple whose first element is a pointer to the top-level function
  13673. that we will generate for the \code{lambda}, the second element is the
  13674. value of \code{x}, which is \code{5}, and the third element is
  13675. \code{4}, the value of \code{y}. The closure does not contain an
  13676. element for \code{z} because \code{z} is not a free variable of the
  13677. \code{lambda}. Creating the closure is step 1 of the dance. The
  13678. closure is returned from \code{f} and bound to \code{g}, as shown in
  13679. Figure~\ref{fig:closures}.
  13680. %
  13681. The second call to \code{f} creates another closure, this time with
  13682. \code{3} in the second slot (for \code{x}). This closure is also
  13683. returned from \code{f} but bound to \code{h}, which is also shown in
  13684. Figure~\ref{fig:closures}.
  13685. \begin{figure}[tbp]
  13686. \centering \includegraphics[width=0.6\textwidth]{figs/closures}
  13687. \caption{Flat closure representations for the two functions
  13688. produced by the \key{lambda} in Figure~\ref{fig:lexical-scoping}.}
  13689. \label{fig:closures}
  13690. \end{figure}
  13691. Continuing with the example, consider the application of \code{g} to
  13692. \code{11} in Figure~\ref{fig:lexical-scoping}. To apply a closure, we
  13693. obtain the function pointer in the first element of the closure and
  13694. call it, passing in the closure itself and then the regular arguments,
  13695. in this case \code{11}. This technique for applying a closure is step
  13696. 2 of the dance.
  13697. %
  13698. But doesn't this \code{lambda} only take 1 argument, for parameter
  13699. \code{z}? The third and final step of the dance is generating a
  13700. top-level function for a \code{lambda}. We add an additional
  13701. parameter for the closure and we insert an initialization at the beginning
  13702. of the function for each free variable, to bind those variables to the
  13703. appropriate elements from the closure parameter.
  13704. %
  13705. This three-step dance is known as \emph{closure conversion}. We
  13706. discuss the details of closure conversion in
  13707. Section~\ref{sec:closure-conversion} and the code generated from the
  13708. example in Section~\ref{sec:example-lambda}. But first we define the
  13709. syntax and semantics of \LangLam{} in Section~\ref{sec:r5}.
  13710. \section{The \LangLam{} Language}
  13711. \label{sec:r5}
  13712. The concrete and abstract syntax for \LangLam{}, a language with anonymous
  13713. functions and lexical scoping, is defined in
  13714. Figures~\ref{fig:Rlam-concrete-syntax} and \ref{fig:Rlam-syntax}. It adds
  13715. the \key{lambda} form to the grammar for \LangFun{}, which already has
  13716. syntax for function application.
  13717. %
  13718. \python{The syntax also includes an assignment statement that includes
  13719. a type annotation for the variable on the left-hand side, which
  13720. facilitates the type checking of \code{lambda} expressions that we
  13721. discuss later in this section.}
  13722. %
  13723. \python{The \code{arity} operation returns the number of parameters of
  13724. a given function, an operation that we need for the translation
  13725. of dynamic typing in Chapter~\ref{ch:Ldyn}.
  13726. The \code{arity} operation is not in Python, but the same functionality
  13727. is available in a more complex form. We include \code{arity} in the
  13728. \LangLam{} source language to enable testing.}
  13729. \newcommand{\LlambdaGrammarRacket}{
  13730. \begin{array}{lcl}
  13731. \Exp &::=& \LP \key{procedure-arity}~\Exp\RP \\
  13732. &\MID& \CLAMBDA{\LP\LS\Var \key{:} \Type\RS\ldots\RP}{\Type}{\Exp}
  13733. \end{array}
  13734. }
  13735. \newcommand{\LlambdaASTRacket}{
  13736. \begin{array}{lcl}
  13737. \itm{op} &::=& \code{procedure-arity} \\
  13738. \Exp &::=& \LAMBDA{\LP\LS\Var\code{:}\Type\RS\ldots\RP}{\Type}{\Exp}
  13739. \end{array}
  13740. }
  13741. \newcommand{\LlambdaGrammarPython}{
  13742. \begin{array}{lcl}
  13743. \Exp &::=& \CLAMBDA{\Var\code{, }\ldots}{\Exp} \MID \CARITY{\Exp} \\
  13744. \Stmt &::=& \CANNASSIGN{\Var}{\Type}{\Exp}
  13745. \end{array}
  13746. }
  13747. \newcommand{\LlambdaASTPython}{
  13748. \begin{array}{lcl}
  13749. \Exp &::=& \LAMBDA{\Var^{*}}{\Exp} \MID \ARITY{\Exp} \\
  13750. \Stmt &::=& \ANNASSIGN{\Var}{\Type}{\Exp}
  13751. \end{array}
  13752. }
  13753. % include AnnAssign in ASTPython
  13754. \begin{figure}[tp]
  13755. \centering
  13756. \fbox{
  13757. \begin{minipage}{0.96\textwidth}
  13758. \small
  13759. {\if\edition\racketEd
  13760. \[
  13761. \begin{array}{l}
  13762. \gray{\LintGrammarRacket{}} \\ \hline
  13763. \gray{\LvarGrammarRacket{}} \\ \hline
  13764. \gray{\LifGrammarRacket{}} \\ \hline
  13765. \gray{\LwhileGrammarRacket} \\ \hline
  13766. \gray{\LtupGrammarRacket} \\ \hline
  13767. \gray{\LfunGrammarRacket} \\ \hline
  13768. \LlambdaGrammarRacket \\
  13769. \begin{array}{lcl}
  13770. \LangLamM{} &::=& \Def\ldots \; \Exp
  13771. \end{array}
  13772. \end{array}
  13773. \]
  13774. \fi}
  13775. {\if\edition\pythonEd
  13776. \[
  13777. \begin{array}{l}
  13778. \gray{\LintGrammarPython{}} \\ \hline
  13779. \gray{\LvarGrammarPython{}} \\ \hline
  13780. \gray{\LifGrammarPython{}} \\ \hline
  13781. \gray{\LwhileGrammarPython} \\ \hline
  13782. \gray{\LtupGrammarPython} \\ \hline
  13783. \gray{\LfunGrammarPython} \\ \hline
  13784. \LlambdaGrammarPython \\
  13785. \begin{array}{lcl}
  13786. \LangFunM{} &::=& \Def\ldots \Stmt\ldots
  13787. \end{array}
  13788. \end{array}
  13789. \]
  13790. \fi}
  13791. \end{minipage}
  13792. }
  13793. \caption{The concrete syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-concrete-syntax})
  13794. with \key{lambda}.}
  13795. \label{fig:Rlam-concrete-syntax}
  13796. \end{figure}
  13797. \begin{figure}[tp]
  13798. \centering
  13799. \fbox{
  13800. \begin{minipage}{0.96\textwidth}
  13801. \small
  13802. {\if\edition\racketEd
  13803. \[
  13804. \begin{array}{l}
  13805. \gray{\LintOpAST} \\ \hline
  13806. \gray{\LvarASTRacket{}} \\ \hline
  13807. \gray{\LifASTRacket{}} \\ \hline
  13808. \gray{\LwhileASTRacket{}} \\ \hline
  13809. \gray{\LtupASTRacket{}} \\ \hline
  13810. \gray{\LfunASTRacket} \\ \hline
  13811. \LlambdaASTRacket \\
  13812. \begin{array}{lcl}
  13813. \LangLamM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  13814. \end{array}
  13815. \end{array}
  13816. \]
  13817. \fi}
  13818. {\if\edition\pythonEd
  13819. \[
  13820. \begin{array}{l}
  13821. \gray{\LintASTPython} \\ \hline
  13822. \gray{\LvarASTPython{}} \\ \hline
  13823. \gray{\LifASTPython{}} \\ \hline
  13824. \gray{\LwhileASTPython{}} \\ \hline
  13825. \gray{\LtupASTPython{}} \\ \hline
  13826. \gray{\LfunASTPython} \\ \hline
  13827. \LlambdaASTPython \\
  13828. \begin{array}{lcl}
  13829. \LangLamM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  13830. \end{array}
  13831. \end{array}
  13832. \]
  13833. \fi}
  13834. \end{minipage}
  13835. }
  13836. \caption{The abstract syntax of \LangLam{}, extending \LangFun{} (Figure~\ref{fig:Rfun-syntax}).}
  13837. \label{fig:Rlam-syntax}
  13838. \end{figure}
  13839. \index{subject}{interpreter}
  13840. \label{sec:interp-Rlambda}
  13841. Figure~\ref{fig:interp-Rlambda} shows the definitional interpreter for
  13842. \LangLam{}. The case for \key{Lambda} saves the current environment
  13843. inside the returned function value. Recall that during function
  13844. application, the environment stored in the function value, extended
  13845. with the mapping of parameters to argument values, is used to
  13846. interpret the body of the function.
  13847. \begin{figure}[tbp]
  13848. {\if\edition\racketEd
  13849. \begin{lstlisting}
  13850. (define interp-Rlambda_class
  13851. (class interp-Rfun_class
  13852. (super-new)
  13853. (define/override (interp-op op)
  13854. (match op
  13855. ['procedure-arity
  13856. (lambda (v)
  13857. (match v
  13858. [`(function (,xs ...) ,body ,lam-env) (length xs)]
  13859. [else (error 'interp-op "expected a function, not ~a" v)]))]
  13860. [else (super interp-op op)]))
  13861. (define/override ((interp-exp env) e)
  13862. (define recur (interp-exp env))
  13863. (match e
  13864. [(Lambda (list `[,xs : ,Ts] ...) rT body)
  13865. `(function ,xs ,body ,env)]
  13866. [else ((super interp-exp env) e)]))
  13867. ))
  13868. (define (interp-Rlambda p)
  13869. (send (new interp-Rlambda_class) interp-program p))
  13870. \end{lstlisting}
  13871. \fi}
  13872. {\if\edition\pythonEd
  13873. \begin{lstlisting}
  13874. class InterpLlambda(InterpLfun):
  13875. def arity(self, v):
  13876. match v:
  13877. case Function(name, params, body, env):
  13878. return len(params)
  13879. case _:
  13880. raise Exception('Llambda arity unexpected ' + repr(v))
  13881. def interp_exp(self, e, env):
  13882. match e:
  13883. case Call(Name('arity'), [fun]):
  13884. f = self.interp_exp(fun, env)
  13885. return self.arity(f)
  13886. case Lambda(params, body):
  13887. return Function('lambda', params, [Return(body)], env)
  13888. case _:
  13889. return super().interp_exp(e, env)
  13890. def interp_stmts(self, ss, env):
  13891. if len(ss) == 0:
  13892. return
  13893. match ss[0]:
  13894. case AnnAssign(lhs, typ, value, simple):
  13895. env[lhs.id] = self.interp_exp(value, env)
  13896. return self.interp_stmts(ss[1:], env)
  13897. case _:
  13898. return super().interp_stmts(ss, env)
  13899. \end{lstlisting}
  13900. \fi}
  13901. \caption{Interpreter for \LangLam{}.}
  13902. \label{fig:interp-Rlambda}
  13903. \end{figure}
  13904. \label{sec:type-check-r5}
  13905. \index{subject}{type checking}
  13906. {\if\edition\racketEd
  13907. %
  13908. Figure~\ref{fig:type-check-Llambda} shows how to type check the new
  13909. \key{lambda} form. The body of the \key{lambda} is checked in an
  13910. environment that includes the current environment (because it is
  13911. lexically scoped) and also includes the \key{lambda}'s parameters. We
  13912. require the body's type to match the declared return type.
  13913. %
  13914. \fi}
  13915. {\if\edition\pythonEd
  13916. %
  13917. Figures~\ref{fig:type-check-Llambda} and
  13918. \ref{fig:type-check-Llambda-part2} define the type checker for
  13919. \LangLam{}, which is more complex than one might expect. The reason
  13920. for the added complexity is that the syntax of \key{lambda} does not
  13921. include type annotations for the parameters or return type. Instead
  13922. they must be inferred. There are many approaches of type inference to
  13923. choose from of varying degrees of complexity. We choose one of the
  13924. simpler approaches, bidirectional type inference~\citep{Dunfield:2021}
  13925. (aka. local type inference~\citep{Pierce:2000}), because the focus of
  13926. this book is compilation, not type inference.
  13927. The main idea of bidirectional type inference is to add an auxilliary
  13928. function, here named \code{check\_exp}, that takes an expected type
  13929. and checks whether the given expression is of that type. Thus, in
  13930. \code{check\_exp}, type information flows in a top-down manner with
  13931. respect to the AST, in contrast to the regular \code{type\_check\_exp}
  13932. function, where type information flows in a primarily bottom-up
  13933. manner.
  13934. %
  13935. The idea then is to use \code{check\_exp} in all the places where we
  13936. already know what the type of an expression should be, such as in the
  13937. \code{return} statement of a top-level function definition, or on the
  13938. right-hand side of an annotated assignment statement.
  13939. Getting back to \code{lambda}, it is straightforward to check a
  13940. \code{lambda} inside \code{check\_exp} because the expected type
  13941. provides the parameter types and the return type. On the other hand,
  13942. inside \code{type\_check\_exp} we disallow \code{lambda}, which means
  13943. that we do not allow \code{lambda} in contexts where we don't already
  13944. know its type. This restriction does not incur a loss of
  13945. expressiveness for \LangLam{} because it is straightforward to modify
  13946. a program to sidestep the restriction, for example, by using an
  13947. annotated assignment statement to assign the \code{lambda} to a
  13948. temporary variable.
  13949. Note that for the \code{Name} and \code{Lambda} AST nodes, the type
  13950. checker records their type in a \code{has\_type} field. This type
  13951. information is used later in this chapter.
  13952. %
  13953. \fi}
  13954. \begin{figure}[tbp]
  13955. {\if\edition\racketEd
  13956. \begin{lstlisting}
  13957. (define (type-check-Rlambda env)
  13958. (lambda (e)
  13959. (match e
  13960. [(Lambda (and params `([,xs : ,Ts] ...)) rT body)
  13961. (define-values (new-body bodyT)
  13962. ((type-check-exp (append (map cons xs Ts) env)) body))
  13963. (define ty `(,@Ts -> ,rT))
  13964. (cond
  13965. [(equal? rT bodyT)
  13966. (values (HasType (Lambda params rT new-body) ty) ty)]
  13967. [else
  13968. (error "mismatch in return type" bodyT rT)])]
  13969. ...
  13970. )))
  13971. \end{lstlisting}
  13972. \fi}
  13973. {\if\edition\pythonEd
  13974. \begin{lstlisting}
  13975. class TypeCheckLlambda(TypeCheckLfun):
  13976. def type_check_exp(self, e, env):
  13977. match e:
  13978. case Name(id):
  13979. e.has_type = env[id]
  13980. return env[id]
  13981. case Lambda(params, body):
  13982. raise Exception('cannot synthesize a type for a lambda')
  13983. case Call(Name('arity'), [func]):
  13984. func_t = self.type_check_exp(func, env)
  13985. match func_t:
  13986. case FunctionType(params_t, return_t):
  13987. return IntType()
  13988. case _:
  13989. raise Exception('in arity, unexpected ' + repr(func_t))
  13990. case _:
  13991. return super().type_check_exp(e, env)
  13992. def check_exp(self, e, ty, env):
  13993. match e:
  13994. case Lambda(params, body):
  13995. e.has_type = ty
  13996. match ty:
  13997. case FunctionType(params_t, return_t):
  13998. new_env = env.copy().update(zip(params, params_t))
  13999. self.check_exp(body, return_t, new_env)
  14000. case _:
  14001. raise Exception('lambda does not have type ' + str(ty))
  14002. case Call(func, args):
  14003. func_t = self.type_check_exp(func, env)
  14004. match func_t:
  14005. case FunctionType(params_t, return_t):
  14006. for (arg, param_t) in zip(args, params_t):
  14007. self.check_exp(arg, param_t, env)
  14008. self.check_type_equal(return_t, ty, e)
  14009. case _:
  14010. raise Exception('type_check_exp: in call, unexpected ' + \
  14011. repr(func_t))
  14012. case _:
  14013. t = self.type_check_exp(e, env)
  14014. self.check_type_equal(t, ty, e)
  14015. \end{lstlisting}
  14016. \fi}
  14017. \caption{Type checking \LangLam{}\python{, part 1}.}
  14018. \label{fig:type-check-Llambda}
  14019. \end{figure}
  14020. {\if\edition\pythonEd
  14021. \begin{figure}[tbp]
  14022. \begin{lstlisting}
  14023. def check_stmts(self, ss, return_ty, env):
  14024. if len(ss) == 0:
  14025. return
  14026. match ss[0]:
  14027. case FunctionDef(name, params, body, dl, returns, comment):
  14028. new_env = env.copy().update(params)
  14029. rt = self.check_stmts(body, returns, new_env)
  14030. self.check_stmts(ss[1:], return_ty, env)
  14031. case Return(value):
  14032. self.check_exp(value, return_ty, env)
  14033. case Assign([Name(id)], value):
  14034. if id in env:
  14035. self.check_exp(value, env[id], env)
  14036. else:
  14037. env[id] = self.type_check_exp(value, env)
  14038. self.check_stmts(ss[1:], return_ty, env)
  14039. case Assign([Subscript(tup, Constant(index), Store())], value):
  14040. tup_t = self.type_check_exp(tup, env)
  14041. match tup_t:
  14042. case TupleType(ts):
  14043. self.check_exp(value, ts[index], env)
  14044. case _:
  14045. raise Exception('expected a tuple, not ' + repr(tup_t))
  14046. self.check_stmts(ss[1:], return_ty, env)
  14047. case AnnAssign(Name(id), ty_annot, value, simple):
  14048. ss[0].annotation = ty_annot
  14049. if id in env:
  14050. self.check_type_equal(env[id], ty_annot)
  14051. else:
  14052. env[id] = ty_annot
  14053. self.check_exp(value, ty_annot, env)
  14054. self.check_stmts(ss[1:], return_ty, env)
  14055. case _:
  14056. self.type_check_stmts(ss, env)
  14057. def type_check(self, p):
  14058. match p:
  14059. case Module(body):
  14060. env = {}
  14061. for s in body:
  14062. match s:
  14063. case FunctionDef(name, params, bod, dl, returns, comment):
  14064. params_t = [t for (x,t) in params]
  14065. env[name] = FunctionType(params_t, returns)
  14066. self.check_stmts(body, int, env)
  14067. \end{lstlisting}
  14068. \caption{Type checking the \key{lambda}'s in \LangLam{}, part 2.}
  14069. \label{fig:type-check-Llambda-part2}
  14070. \end{figure}
  14071. \fi}
  14072. \clearpage
  14073. \section{Assignment and Lexically Scoped Functions}
  14074. \label{sec:assignment-scoping}
  14075. The combination of lexically-scoped functions and assignment to
  14076. variables raises a challenge with our approach to implementing
  14077. lexically-scoped functions. Consider the following example in which
  14078. function \code{f} has a free variable \code{x} that is changed after
  14079. \code{f} is created but before the call to \code{f}.
  14080. % loop_test_11.rkt
  14081. {\if\edition\racketEd
  14082. \begin{lstlisting}
  14083. (let ([x 0])
  14084. (let ([y 0])
  14085. (let ([z 20])
  14086. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14087. (begin
  14088. (set! x 10)
  14089. (set! y 12)
  14090. (f y))))))
  14091. \end{lstlisting}
  14092. \fi}
  14093. {\if\edition\pythonEd
  14094. % box_free_assign.py
  14095. \begin{lstlisting}
  14096. def g(z : int) -> int:
  14097. x = 0
  14098. y = 0
  14099. f : Callable[[int],int] = lambda a: a + x + z
  14100. x = 10
  14101. y = 12
  14102. return f(y)
  14103. print( g(20) )
  14104. \end{lstlisting}
  14105. \fi}
  14106. The correct output for this example is \code{42} because the call to
  14107. \code{f} is required to use the current value of \code{x} (which is
  14108. \code{10}). Unfortunately, the closure conversion pass
  14109. (Section~\ref{sec:closure-conversion}) generates code for the
  14110. \code{lambda} that copies the old value of \code{x} into a
  14111. closure. Thus, if we naively add support for assignment to our current
  14112. compiler, the output of this program would be \code{32}.
  14113. A first attempt at solving this problem would be to save a pointer to
  14114. \code{x} in the closure and change the occurrences of \code{x} inside
  14115. the lambda to dereference the pointer. Of course, this would require
  14116. assigning \code{x} to the stack and not to a register. However, the
  14117. problem goes a bit deeper.
  14118. %% Consider the following example in which we
  14119. %% create a counter abstraction by creating a pair of functions that
  14120. %% share the free variable \code{x}.
  14121. Consider the following example that returns a function that refers to
  14122. a local variable of the enclosing function.
  14123. \begin{center}
  14124. \begin{minipage}{\textwidth}
  14125. {\if\edition\racketEd
  14126. % similar to loop_test_10.rkt
  14127. %% \begin{lstlisting}
  14128. %% (define (f [x : Integer]) : (Vector ( -> Integer) ( -> Void))
  14129. %% (vector
  14130. %% (lambda: () : Integer x)
  14131. %% (lambda: () : Void (set! x (+ 1 x)))))
  14132. %% (let ([counter (f 0)])
  14133. %% (let ([get (vector-ref counter 0)])
  14134. %% (let ([inc (vector-ref counter 1)])
  14135. %% (begin
  14136. %% (inc)
  14137. %% (get)))))
  14138. %% \end{lstlisting}
  14139. \begin{lstlisting}
  14140. (define (f []) : Integer
  14141. (let ([x 0])
  14142. (let ([g (lambda: () : Integer x)])
  14143. (begin
  14144. (set! x 42)
  14145. g))))
  14146. ((f))
  14147. \end{lstlisting}
  14148. \fi}
  14149. {\if\edition\pythonEd
  14150. % counter.py
  14151. \begin{lstlisting}
  14152. def f():
  14153. x = 0
  14154. g = lambda: x
  14155. x = 42
  14156. return g
  14157. print( f()() )
  14158. \end{lstlisting}
  14159. \fi}
  14160. \end{minipage}
  14161. \end{center}
  14162. In this example, the lifetime of \code{x} extends beyond the lifetime
  14163. of the call to \code{f}. Thus, if we were to store \code{x} on the
  14164. stack frame for the call to \code{f}, it would be gone by the time we
  14165. call \code{g}, leaving us with dangling pointers for
  14166. \code{x}. This example demonstrates that when a variable occurs free
  14167. inside a function, its lifetime becomes indefinite. Thus, the value of
  14168. the variable needs to live on the heap. The verb
  14169. \emph{box}\index{subject}{box} is often used for allocating a single
  14170. value on the heap, producing a pointer, and
  14171. \emph{unbox}\index{subject}{unbox} for dereferencing the pointer.
  14172. %% {\if\edition\racketEd
  14173. %% We recommend solving these problems by boxing the local variables that
  14174. %% are in the intersection of 1) variables that appear on the
  14175. %% left-hand-side of a \code{set!} and 2) variables that occur free
  14176. %% inside a \code{lambda}.
  14177. %% \fi}
  14178. %% {\if\edition\pythonEd
  14179. %% We recommend solving these problems by boxing the local variables that
  14180. %% are in the intersection of 1) variables whose values may change and 2)
  14181. %% variables that occur free inside a \code{lambda}.
  14182. %% \fi}
  14183. We shall introduce a new pass named
  14184. \code{convert\_assignments} in Section~\ref{sec:convert-assignments}
  14185. to address this challenge.
  14186. %
  14187. \racket{But before diving into the compiler passes, we have one more
  14188. problem to discuss.}
  14189. \if\edition\pythonEd
  14190. \section{Uniquify Variables}
  14191. \label{sec:uniquify-lambda}
  14192. With the addition of \code{lambda} we have a complication to deal
  14193. with: name shadowing. Consider the following program with a function
  14194. \code{f} that has a parameter \code{x}. Inside \code{f} there are two
  14195. \code{lambda} expressions. The first \code{lambda} has a parameter
  14196. that is also named \code{x}.
  14197. \begin{lstlisting}
  14198. def f(x:int, y:int) -> Callable[[int], int]:
  14199. g : Callable[[int],int] = (lambda x: x + y)
  14200. h : Callable[[int],int] = (lambda y: x + y)
  14201. x = input_int()
  14202. return g
  14203. print(f(0, 10)(32))
  14204. \end{lstlisting}
  14205. Many of our compiler passes rely on being able to connect variable
  14206. uses with their definitions using just the name of the variable,
  14207. including new passes in this chapter. However, in the above example
  14208. the name of the variable does not uniquely determine its
  14209. definition. To solve this problem we recommend implementing a pass
  14210. named \code{uniquify} that renames every variable in the program to
  14211. make sure they are all unique.
  14212. The following shows the result of \code{uniquify} for the above
  14213. example. The \code{x} parameter of \code{f} is renamed to \code{x\_0}
  14214. and the \code{x} parameter of the \code{lambda} is renamed to
  14215. \code{x\_4}.
  14216. \begin{lstlisting}
  14217. def f(x_0:int, y_1:int) -> Callable[[int], int] :
  14218. g_2 : Callable[[int], int] = (lambda x_4: x_4 + y_1)
  14219. h_3 : Callable[[int], int] = (lambda y_5: x_0 + y_5)
  14220. x_0 = input_int()
  14221. return g_2
  14222. def main() -> int :
  14223. print(f(0, 10)(32))
  14224. return 0
  14225. \end{lstlisting}
  14226. \fi
  14227. %% \section{Reveal Functions}
  14228. %% \label{sec:reveal-functions-r5}
  14229. %% \racket{To support the \code{procedure-arity} operator we need to
  14230. %% communicate the arity of a function to the point of closure
  14231. %% creation.}
  14232. %% %
  14233. %% \python{In Chapter~\ref{ch:Ldyn} we need to access the arity of a
  14234. %% function at runtime. Thus, we need to communicate the arity of a
  14235. %% function to the point of closure creation.}
  14236. %% %
  14237. %% We can accomplish this by replacing the $\FUNREF{\Var}{\Int}$ AST node with
  14238. %% one that has a second field for the arity: $\FUNREFARITY{\Var}{\Int}$.
  14239. %% \[
  14240. %% \begin{array}{lcl}
  14241. %% \Exp &::=& \FUNREFARITY{\Var}{\Int}
  14242. %% \end{array}
  14243. %% \]
  14244. \section{Assignment Conversion}
  14245. \label{sec:convert-assignments}
  14246. The purpose of the \code{convert\_assignments} pass is to address the
  14247. challenge posed in Section~\ref{sec:assignment-scoping} regarding the
  14248. interaction between variable assignments and closure conversion.
  14249. First we identify which variables need to be boxed, then we transform
  14250. the program to box those variables. In general, boxing introduces
  14251. runtime overhead that we would like to avoid, so we should box as few
  14252. variables as possible. We recommend boxing the variables in the
  14253. intersection of the following two sets of variables:
  14254. \begin{enumerate}
  14255. \item The variables that are free in a \code{lambda}.
  14256. \item The variables that appear on the left-hand side of an
  14257. assignment.
  14258. \end{enumerate}
  14259. The first condition is a must, but the second condition is quite conservative and it is possible to
  14260. develop a more liberal condition.
  14261. Consider again the first example from
  14262. Section~\ref{sec:assignment-scoping}:
  14263. %
  14264. {\if\edition\racketEd
  14265. \begin{lstlisting}
  14266. (let ([x 0])
  14267. (let ([y 0])
  14268. (let ([z 20])
  14269. (let ([f (lambda: ([a : Integer]) : Integer (+ a (+ x z)))])
  14270. (begin
  14271. (set! x 10)
  14272. (set! y 12)
  14273. (f y))))))
  14274. \end{lstlisting}
  14275. \fi}
  14276. {\if\edition\pythonEd
  14277. \begin{lstlisting}
  14278. def g(z : int) -> int:
  14279. x = 0
  14280. y = 0
  14281. f : Callable[[int],int] = lambda a: a + x + z
  14282. x = 10
  14283. y = 12
  14284. return f(y)
  14285. print( g(20) )
  14286. \end{lstlisting}
  14287. \fi}
  14288. %
  14289. \noindent The variables \code{x} and \code{y} are assigned-to. The
  14290. variables \code{x} and \code{z} occur free inside the
  14291. \code{lambda}. Thus, variable \code{x} needs to be boxed but not
  14292. \code{y} or \code{z}. The boxing of \code{x} consists of three
  14293. transformations: initialize \code{x} with a tuple whose elements are uninitialized,
  14294. replace reads from \code{x} with tuple reads, and replace each assignment to \code{x}
  14295. with a tuple write. The output of \code{convert\_assignments} for
  14296. this example is as follows.
  14297. %
  14298. {\if\edition\racketEd
  14299. \begin{lstlisting}
  14300. (define (main) : Integer
  14301. (let ([x0 (vector 0)])
  14302. (let ([y1 0])
  14303. (let ([z2 20])
  14304. (let ([f4 (lambda: ([a3 : Integer]) : Integer
  14305. (+ a3 (+ (vector-ref x0 0) z2)))])
  14306. (begin
  14307. (vector-set! x0 0 10)
  14308. (set! y1 12)
  14309. (f4 y1)))))))
  14310. \end{lstlisting}
  14311. \fi}
  14312. %
  14313. {\if\edition\pythonEd
  14314. \begin{lstlisting}
  14315. def g(z : int)-> int:
  14316. x = (uninitialized(int),)
  14317. x[0] = 0
  14318. y = 0
  14319. f : Callable[[int], int] = (lambda a: a + x[0] + z)
  14320. x[0] = 10
  14321. y = 12
  14322. return f(y)
  14323. def main() -> int:
  14324. print(g(20))
  14325. return 0
  14326. \end{lstlisting}
  14327. \fi}
  14328. To compute the free variables of all the \code{lambda} expressions, we
  14329. recommend defining two auxiliary functions:
  14330. \begin{enumerate}
  14331. \item \code{free\_variables} computes the free variables of an expression, and
  14332. \item \code{free\_in\_lambda} collects all of the variables that are
  14333. free in any of the \code{lambda} expressions, using
  14334. \code{free\_variables} in the case for each \code{lambda}.
  14335. \end{enumerate}
  14336. {\if\edition\racketEd
  14337. %
  14338. To compute the variables that are assigned-to, we recommend using the
  14339. \code{collect-set!} function that we introduced in
  14340. Section~\ref{sec:uncover-get-bang}, but updated to include the new AST
  14341. forms such as \code{Lambda}.
  14342. %
  14343. \fi}
  14344. {\if\edition\pythonEd
  14345. %
  14346. To compute the variables that are assigned-to, we recommend defining
  14347. an auxiliary function named \code{assigned\_vars\_stmt} that returns
  14348. the set of variables that occur in the left-hand side of an assignment
  14349. statement, and otherwise returns the empty set.
  14350. %
  14351. \fi}
  14352. Let $\mathit{AF}$ be the intersection of the set of variables that are
  14353. free in a \code{lambda} and that are assigned-to in the enclosing
  14354. function definition.
  14355. Next we discuss the \code{convert\_assignments} pass. In the case for
  14356. $\VAR{x}$, if $x$ is in $\mathit{AF}$, then unbox it by translating
  14357. $\VAR{x}$ to a tuple read.
  14358. %
  14359. {\if\edition\racketEd
  14360. \begin{lstlisting}
  14361. (Var |$x$|)
  14362. |$\Rightarrow$|
  14363. (Prim 'vector-ref (list (Var |$x$|) (Int 0)))
  14364. \end{lstlisting}
  14365. \fi}
  14366. %
  14367. {\if\edition\pythonEd
  14368. \begin{lstlisting}
  14369. Name(|$x$|)
  14370. |$\Rightarrow$|
  14371. Subscript(Name(|$x$|), Constant(0), Load())
  14372. \end{lstlisting}
  14373. \fi}
  14374. %
  14375. %
  14376. In the case for assignment, recursively process the right-hand side
  14377. \itm{rhs} to obtain \itm{rhs'}. If $x$ is in $\mathit{AF}$, translate
  14378. the assignment into a tuple-write as follows.
  14379. %
  14380. {\if\edition\racketEd
  14381. \begin{lstlisting}
  14382. (SetBang |$x$| |$\itm{rhs}$|)
  14383. |$\Rightarrow$|
  14384. (Prim 'vector-set! (list (Var |$x$|) (Int 0) |$\itm{rhs'}$|))
  14385. \end{lstlisting}
  14386. \fi}
  14387. {\if\edition\pythonEd
  14388. \begin{lstlisting}
  14389. Assign([Name(|$x$|)],|$\itm{rhs}$|)
  14390. |$\Rightarrow$|
  14391. Assign([Subscript(Name(|$x$|), Constant(0), Store())], |$\itm{rhs'}$|)
  14392. \end{lstlisting}
  14393. \fi}
  14394. %
  14395. {\if\edition\racketEd
  14396. The case for \code{Lambda} is non-trivial, but it is similar to the
  14397. case for function definitions, which we discuss next.
  14398. \fi}
  14399. To translate a function definition, we first compute $\mathit{AF}$,
  14400. the intersection of the variables that are free in a \code{lambda} and
  14401. that are assigned-to. We then apply assignment conversion to the body
  14402. of the function definition. Finally, we box the parameters of this
  14403. function definition that are in $\mathit{AF}$. For example,
  14404. the parameter \code{x} of the following function \code{g}
  14405. needs to be boxed.
  14406. {\if\edition\racketEd
  14407. \begin{lstlisting}
  14408. (define (g [x : Integer]) : Integer
  14409. (let ([f (lambda: ([a : Integer]) : Integer (+ a x))])
  14410. (begin
  14411. (set! x 10)
  14412. (f 32))))
  14413. \end{lstlisting}
  14414. \fi}
  14415. %
  14416. {\if\edition\pythonEd
  14417. \begin{lstlisting}
  14418. def g(x : int) -> int:
  14419. f : Callable[[int],int] = lambda a: a + x
  14420. x = 10
  14421. return f(32)
  14422. \end{lstlisting}
  14423. \fi}
  14424. %
  14425. \noindent We box parameter \code{x} by creating a local variable named
  14426. \code{x} that is initialized to a tuple whose contents is the value of
  14427. the parameter, which we has been renamed.
  14428. %
  14429. {\if\edition\racketEd
  14430. \begin{lstlisting}
  14431. (define (g [x_0 : Integer]) : Integer
  14432. (let ([x (vector x_0)])
  14433. (let ([f (lambda: ([a : Integer]) : Integer
  14434. (+ a (vector-ref x 0)))])
  14435. (begin
  14436. (vector-set! x 0 10)
  14437. (f 32)))))
  14438. \end{lstlisting}
  14439. \fi}
  14440. %
  14441. {\if\edition\pythonEd
  14442. \begin{lstlisting}
  14443. def g(x_0 : int)-> int:
  14444. x = (x_0,)
  14445. f : Callable[[int], int] = (lambda a: a + x[0])
  14446. x[0] = 10
  14447. return f(32)
  14448. \end{lstlisting}
  14449. \fi}
  14450. %% Recall the second example in Section~\ref{sec:assignment-scoping}
  14451. %% involving a counter abstraction. The following is the output of
  14452. %% assignment version for function \code{f}.
  14453. %% \begin{lstlisting}
  14454. %% (define (f0 [x1 : Integer]) : (Vector ( -> Integer) ( -> Void))
  14455. %% (vector
  14456. %% (lambda: () : Integer x1)
  14457. %% (lambda: () : Void (set! x1 (+ 1 x1)))))
  14458. %% |$\Rightarrow$|
  14459. %% (define (f0 [param_x1 : Integer]) : (Vector (-> Integer) (-> Void))
  14460. %% (let ([x1 (vector param_x1)])
  14461. %% (vector (lambda: () : Integer (vector-ref x1 0))
  14462. %% (lambda: () : Void
  14463. %% (vector-set! x1 0 (+ 1 (vector-ref x1 0)))))))
  14464. %% \end{lstlisting}
  14465. \section{Closure Conversion}
  14466. \label{sec:closure-conversion}
  14467. \index{subject}{closure conversion}
  14468. The compiling of lexically-scoped functions into top-level function
  14469. definitions is accomplished in the pass \code{convert\_to\_closures}
  14470. that comes after \code{reveal\_functions} and before
  14471. \code{limit\_functions}.
  14472. As usual, we implement the pass as a recursive function over the
  14473. AST. The interesting cases are the ones for \key{lambda} and function
  14474. application. We transform a \key{lambda} expression into an expression
  14475. that creates a closure, that is, a tuple whose first element is a
  14476. function pointer and the rest of the elements are the values of the
  14477. free variables of the \key{lambda}.
  14478. %
  14479. However, we use the \code{Closure} AST node instead of using a tuple
  14480. so that we can record the arity.
  14481. %
  14482. In the generated code below, \itm{fvs} is the free variables of the
  14483. lambda and \itm{name} is a unique symbol generated to identify the lambda.
  14484. %
  14485. \racket{The \itm{arity} is the number of parameters (the length of
  14486. \itm{ps}).}
  14487. %
  14488. {\if\edition\racketEd
  14489. \begin{lstlisting}
  14490. (Lambda |\itm{ps}| |\itm{rt}| |\itm{body}|)
  14491. |$\Rightarrow$|
  14492. (Closure |\itm{arity}| (cons (FunRef |\itm{name}| |\itm{arity}|) |\itm{fvs}|))
  14493. \end{lstlisting}
  14494. \fi}
  14495. %
  14496. {\if\edition\pythonEd
  14497. \begin{lstlisting}
  14498. Lambda([|$x_1,\ldots,x_n$|], |\itm{body}|)
  14499. |$\Rightarrow$|
  14500. Closure(|$n$|, [FunRef(|\itm{name}|, |$n$|), |\itm{fvs}, \ldots|])
  14501. \end{lstlisting}
  14502. \fi}
  14503. %
  14504. In addition to transforming each \key{Lambda} AST node into a
  14505. tuple, we create a top-level function definition for each
  14506. \key{Lambda}, as shown below.\\
  14507. \begin{minipage}{0.8\textwidth}
  14508. {\if\edition\racketEd
  14509. \begin{lstlisting}
  14510. (Def |\itm{name}| ([clos : (Vector _ |\itm{fvts}| ...)] |\itm{ps'}| ...) |\itm{rt'}|
  14511. (Let |$\itm{fvs}_1$| (Prim 'vector-ref (list (Var clos) (Int 1)))
  14512. ...
  14513. (Let |$\itm{fvs}_n$| (Prim 'vector-ref (list (Var clos) (Int |$n$|)))
  14514. |\itm{body'}|)...))
  14515. \end{lstlisting}
  14516. \fi}
  14517. {\if\edition\pythonEd
  14518. \begin{lstlisting}
  14519. def |\itm{name}|(clos : |\itm{closTy}|, |\itm{ps'}, \ldots|) -> |\itm{rt'}|:
  14520. |$\itm{fvs}_1$| = clos[1]
  14521. |$\ldots$|
  14522. |$\itm{fvs}_n$| = clos[|$n$|]
  14523. |\itm{body'}|
  14524. \end{lstlisting}
  14525. \fi}
  14526. \end{minipage}\\
  14527. The \code{clos} parameter refers to the closure. Translate the type
  14528. annotations in \itm{ps} and the return type \itm{rt}, as discussed in
  14529. the next paragraph, to obtain \itm{ps'} and \itm{rt'}. The type
  14530. \itm{closTy} is a tuple type whose first element type is
  14531. \python{\code{Bottom()}}\racket{\code{\_} (the dummy type)} and the rest of
  14532. the element types are the types of the free variables in the
  14533. lambda. We use \python{\code{Bottom()}}\racket{\code{\_}} because it
  14534. is non-trivial to give a type to the function in the closure's type.%
  14535. %
  14536. \footnote{To give an accurate type to a closure, we would need to add
  14537. existential types to the type checker~\citep{Minamide:1996ys}.}
  14538. %
  14539. %% The dummy type is considered to be equal to any other type during type
  14540. %% checking.
  14541. The free variables become local variables that are initialized with
  14542. their values in the closure.
  14543. Closure conversion turns every function into a tuple, so the type
  14544. annotations in the program must also be translated. We recommend
  14545. defining an auxiliary recursive function for this purpose. Function
  14546. types should be translated as follows.
  14547. %
  14548. {\if\edition\racketEd
  14549. \begin{lstlisting}
  14550. (|$T_1, \ldots, T_n$| -> |$T_r$|)
  14551. |$\Rightarrow$|
  14552. (Vector ((Vector) |$T'_1, \ldots, T'_n$| -> |$T'_r$|))
  14553. \end{lstlisting}
  14554. \fi}
  14555. {\if\edition\pythonEd
  14556. \begin{lstlisting}
  14557. FunctionType([|$T_1, \ldots, T_n$|], |$T_r$|)
  14558. |$\Rightarrow$|
  14559. TupleType([FunctionType([TupleType([]), |$T'_1, \ldots, T'_n$|], |$T'_r$|)])
  14560. \end{lstlisting}
  14561. \fi}
  14562. %
  14563. The above type says that the first thing in the tuple is a
  14564. function. The first parameter of the function is a tuple (a closure)
  14565. and the rest of the parameters are the ones from the original
  14566. function, with types $T'_1, \ldots, T'_n$. The type for the closure
  14567. omits the types of the free variables because 1) those types are not
  14568. available in this context and 2) we do not need them in the code that
  14569. is generated for function application. So this type only describes the
  14570. first component of the closure tuple. At runtime the tuple may have
  14571. more components, but we ignore them at this point.
  14572. We transform function application into code that retrieves the
  14573. function from the closure and then calls the function, passing the
  14574. closure as the first argument. We place $e'$ in a temporary variable
  14575. to avoid code duplication.
  14576. \begin{center}
  14577. \begin{minipage}{\textwidth}
  14578. {\if\edition\racketEd
  14579. \begin{lstlisting}
  14580. (Apply |$e$| |$\itm{es}$|)
  14581. |$\Rightarrow$|
  14582. (Let |$\itm{tmp}$| |$e'$|
  14583. (Apply (Prim 'vector-ref (list (Var |$\itm{tmp}$|) (Int 0))) (cons |$\itm{tmp}$| |$\itm{es'}$|)))
  14584. \end{lstlisting}
  14585. \fi}
  14586. %
  14587. {\if\edition\pythonEd
  14588. \begin{lstlisting}
  14589. Call(|$e$|, [|$e_1, \ldots, e_n$|])
  14590. |$\Rightarrow$|
  14591. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  14592. Call(Subscript(Name(|$\itm{tmp}$|), Constant(0)),
  14593. [|$\itm{tmp}$|, |$e'_1, \ldots, e'_n$|]))
  14594. \end{lstlisting}
  14595. \fi}
  14596. \end{minipage}
  14597. \end{center}
  14598. There is also the question of what to do with references to top-level
  14599. function definitions. To maintain a uniform translation of function
  14600. application, we turn function references into closures.
  14601. \begin{tabular}{lll}
  14602. \begin{minipage}{0.3\textwidth}
  14603. {\if\edition\racketEd
  14604. \begin{lstlisting}
  14605. (FunRef |$f$| |$n$|)
  14606. \end{lstlisting}
  14607. \fi}
  14608. {\if\edition\pythonEd
  14609. \begin{lstlisting}
  14610. FunRef(|$f$|, |$n$|)
  14611. \end{lstlisting}
  14612. \fi}
  14613. \end{minipage}
  14614. &
  14615. $\Rightarrow$
  14616. &
  14617. \begin{minipage}{0.5\textwidth}
  14618. {\if\edition\racketEd
  14619. \begin{lstlisting}
  14620. (Closure |$n$| (FunRef |$f$| |$n$|) '())
  14621. \end{lstlisting}
  14622. \fi}
  14623. {\if\edition\pythonEd
  14624. \begin{lstlisting}
  14625. Closure(|$n$|, [FunRef(|$f$| |$n$|)])
  14626. \end{lstlisting}
  14627. \fi}
  14628. \end{minipage}
  14629. \end{tabular} \\
  14630. We no longer need the annotated assignment statement \code{AnnAssign}
  14631. to support the type checking of \code{lambda} expressions, so we
  14632. translate it to a regular \code{Assign} statement.
  14633. The top-level function definitions need to be updated to take an extra
  14634. closure parameter.
  14635. \section{An Example Translation}
  14636. \label{sec:example-lambda}
  14637. Figure~\ref{fig:lexical-functions-example} shows the result of
  14638. \code{reveal\_functions} and \code{convert\_to\_closures} for the example
  14639. program demonstrating lexical scoping that we discussed at the
  14640. beginning of this chapter.
  14641. \begin{figure}[tbp]
  14642. \begin{minipage}{0.8\textwidth}
  14643. {\if\edition\racketEd
  14644. % tests/lambda_test_6.rkt
  14645. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14646. (define (f6 [x7 : Integer]) : (Integer -> Integer)
  14647. (let ([y8 4])
  14648. (lambda: ([z9 : Integer]) : Integer
  14649. (+ x7 (+ y8 z9)))))
  14650. (define (main) : Integer
  14651. (let ([g0 ((fun-ref f6 1) 5)])
  14652. (let ([h1 ((fun-ref f6 1) 3)])
  14653. (+ (g0 11) (h1 15)))))
  14654. \end{lstlisting}
  14655. $\Rightarrow$
  14656. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  14657. (define (f6 [fvs4 : _] [x7 : Integer]) : (Vector ((Vector _) Integer -> Integer))
  14658. (let ([y8 4])
  14659. (closure 1 (list (fun-ref lambda2 1) x7 y8))))
  14660. (define (lambda2 [fvs3 : (Vector _ Integer Integer)] [z9 : Integer]) : Integer
  14661. (let ([x7 (vector-ref fvs3 1)])
  14662. (let ([y8 (vector-ref fvs3 2)])
  14663. (+ x7 (+ y8 z9)))))
  14664. (define (main) : Integer
  14665. (let ([g0 (let ([clos5 (closure 1 (list (fun-ref f6 1)))])
  14666. ((vector-ref clos5 0) clos5 5))])
  14667. (let ([h1 (let ([clos6 (closure 1 (list (fun-ref f6 1)))])
  14668. ((vector-ref clos6 0) clos6 3))])
  14669. (+ ((vector-ref g0 0) g0 11) ((vector-ref h1 0) h1 15)))))
  14670. \end{lstlisting}
  14671. \fi}
  14672. %
  14673. {\if\edition\pythonEd
  14674. % free_var.py
  14675. \begin{lstlisting}
  14676. def f(x : int) -> Callable[[int], int]:
  14677. y = 4
  14678. return lambda z: x + y + z
  14679. g = f(5)
  14680. h = f(3)
  14681. print( g(11) + h(15) )
  14682. \end{lstlisting}
  14683. $\Rightarrow$
  14684. \begin{lstlisting}
  14685. def lambda_0(fvs_1:tuple[bot,int,tuple[int]],z:int) -> int:
  14686. x = fvs_1[1]
  14687. y = fvs_1[2]
  14688. return x + y[0] + z
  14689. def f(fvs_2:bot, x:int) -> tuple[Callable[[tuple[],int], int]]
  14690. y = (777,)
  14691. y[0] = 4
  14692. return (lambda_0, x, y)
  14693. def main() -> int:
  14694. g = (let clos_3 = (f,) in clos_3[0](clos_3, 5))
  14695. h = (let clos_4 = (f,) in clos_4[0](clos_4, 3))
  14696. print((let clos_5 = g in clos_5[0](clos_5, 11))
  14697. + (let clos_6 = h in clos_6[0](clos_6, 15)))
  14698. return 0
  14699. \end{lstlisting}
  14700. \fi}
  14701. \end{minipage}
  14702. \caption{Example of closure conversion.}
  14703. \label{fig:lexical-functions-example}
  14704. \end{figure}
  14705. \begin{exercise}\normalfont\normalsize
  14706. Expand your compiler to handle \LangLam{} as outlined in this chapter.
  14707. Create 5 new programs that use \key{lambda} functions and make use of
  14708. lexical scoping. Test your compiler on these new programs and all of
  14709. your previously created test programs.
  14710. \end{exercise}
  14711. \section{Expose Allocation}
  14712. \label{sec:expose-allocation-r5}
  14713. Compile the $\CLOSURE{\itm{arity}}{\Exp^{*}}$ form into code
  14714. that allocates and initializes a tuple, similar to the translation of
  14715. the tuple creation in Section~\ref{sec:expose-allocation}.
  14716. The only difference is replacing the use of
  14717. \ALLOC{\itm{len}}{\itm{type}} with
  14718. \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}}.
  14719. \section{Explicate Control and \LangCLam{}}
  14720. \label{sec:explicate-r5}
  14721. The output language of \code{explicate\_control} is \LangCLam{} whose
  14722. abstract syntax is defined in Figure~\ref{fig:Clam-syntax}.
  14723. %
  14724. \racket{The only difference with respect to \LangCFun{} is the
  14725. addition of the \code{AllocateClosure} form to the grammar for
  14726. $\Exp$. The handling of \code{AllocateClosure} in the
  14727. \code{explicate\_control} pass is similar to the handling of other
  14728. expressions such as primitive operators.}
  14729. %
  14730. \python{The differences with respect to \LangCFun{} are the
  14731. additions of \code{Uninitialized}, \code{AllocateClosure},
  14732. and \code{arity} to the grammar for $\Exp$. The handling of them in the
  14733. \code{explicate\_control} pass is similar to the handling of other
  14734. expressions such as primitive operators.}
  14735. \newcommand{\ClambdaASTPython}{
  14736. \begin{array}{lcl}
  14737. \Exp &::=& \key{Uninitialized}\LP \Type \RP
  14738. \MID \key{AllocateClosure}\LP\itm{len},\Type, \itm{arity}\RP \\
  14739. &\MID& \ARITY{\Atm}
  14740. \end{array}
  14741. }
  14742. \begin{figure}[tp]
  14743. \fbox{
  14744. \begin{minipage}{0.96\textwidth}
  14745. \small
  14746. {\if\edition\racketEd
  14747. \[
  14748. \begin{array}{lcl}
  14749. \Exp &::= & \ldots
  14750. \MID \ALLOCCLOS{\Int}{\Type}{\Int} \\
  14751. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  14752. \MID \LP\key{Collect} \,\itm{int}\RP } \\
  14753. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  14754. \MID \GOTO{\itm{label}} } \\
  14755. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  14756. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} } \\
  14757. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  14758. \LangCLamM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  14759. \end{array}
  14760. \]
  14761. \fi}
  14762. {\if\edition\pythonEd
  14763. \[
  14764. \begin{array}{l}
  14765. \gray{\CifASTPython} \\ \hline
  14766. \gray{\CtupASTPython} \\ \hline
  14767. \gray{\CfunASTPython} \\ \hline
  14768. \ClambdaASTPython \\
  14769. \begin{array}{lcl}
  14770. \LangCLamM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  14771. \end{array}
  14772. \end{array}
  14773. \]
  14774. \fi}
  14775. \end{minipage}
  14776. }
  14777. \caption{The abstract syntax of \LangCLam{}, extending \LangCFun{} (Figure~\ref{fig:c3-syntax}).}
  14778. \label{fig:Clam-syntax}
  14779. \end{figure}
  14780. \section{Select Instructions}
  14781. \label{sec:select-instructions-Rlambda}
  14782. Compile \ALLOCCLOS{\itm{len}}{\itm{type}}{\itm{arity}} in almost the
  14783. same way as the \ALLOC{\itm{len}}{\itm{type}} form
  14784. (Section~\ref{sec:select-instructions-gc}). The only difference is
  14785. that you should place the \itm{arity} in the tag that is stored at
  14786. position $0$ of the vector. Recall that in
  14787. Section~\ref{sec:select-instructions-gc} a portion of the 64-bit tag
  14788. was not used. We store the arity in the $5$ bits starting at position
  14789. $58$.
  14790. \racket{Compile the \code{procedure-arity} operator into a sequence of
  14791. instructions that access the tag from position $0$ of the vector and
  14792. extract the $5$-bits starting at position $58$ from the tag.}
  14793. %
  14794. \python{Compile a call to the \code{arity} operator to a sequence of
  14795. instructions that access the tag from position $0$ of the tuple
  14796. (representing a closure) and extract the $5$-bits starting at position
  14797. $58$ from the tag.}
  14798. \begin{figure}[p]
  14799. \begin{tikzpicture}[baseline=(current bounding box.center)]
  14800. \node (Rfun) at (0,2) {\large \LangLam{}};
  14801. \node (Rfun-2) at (3,2) {\large \LangLam{}};
  14802. \node (Rfun-3) at (6,2) {\large \LangLam{}};
  14803. \node (F1-0) at (9,2) {\large \LangLamFunRef{}};
  14804. \node (F1-1) at (12,0) {\large \LangLamFunRef{}};
  14805. \node (F1-2) at (9,0) {\large \LangFunRef{}};
  14806. \node (F1-3) at (6,0) {\large \LangFunRef{}};
  14807. \node (F1-4) at (3,0) {\large \LangFunRefAlloc{}};
  14808. \node (F1-5) at (0,0) {\large \LangFunANF{}};
  14809. \node (C3-2) at (3,-2) {\large \LangCFun{}};
  14810. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  14811. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  14812. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  14813. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  14814. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  14815. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  14816. \path[->,bend left=15] (Rfun) edge [above] node
  14817. {\ttfamily\footnotesize shrink} (Rfun-2);
  14818. \path[->,bend left=15] (Rfun-2) edge [above] node
  14819. {\ttfamily\footnotesize uniquify} (Rfun-3);
  14820. \path[->,bend left=15] (Rfun-3) edge [above] node
  14821. {\ttfamily\footnotesize reveal\_functions} (F1-0);
  14822. \path[->,bend left=15] (F1-0) edge [right] node
  14823. {\ttfamily\footnotesize convert\_assign.} (F1-1);
  14824. \path[->,bend left=15] (F1-1) edge [below] node
  14825. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  14826. \path[->,bend right=15] (F1-2) edge [above] node
  14827. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  14828. \path[->,bend right=15] (F1-3) edge [above] node
  14829. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  14830. \path[->,bend right=15] (F1-4) edge [above] node
  14831. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  14832. \path[->,bend right=15] (F1-5) edge [right] node
  14833. {\ttfamily\footnotesize explicate\_control} (C3-2);
  14834. \path[->,bend left=15] (C3-2) edge [left] node
  14835. {\ttfamily\footnotesize select\_instr.} (x86-2);
  14836. \path[->,bend right=15] (x86-2) edge [left] node
  14837. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  14838. \path[->,bend right=15] (x86-2-1) edge [below] node
  14839. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  14840. \path[->,bend right=15] (x86-2-2) edge [left] node
  14841. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  14842. \path[->,bend left=15] (x86-3) edge [above] node
  14843. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  14844. \path[->,bend left=15] (x86-4) edge [right] node
  14845. {\ttfamily\footnotesize print\_x86} (x86-5);
  14846. \end{tikzpicture}
  14847. \caption{Diagram of the passes for \LangLam{}, a language with lexically-scoped
  14848. functions.}
  14849. \label{fig:Rlambda-passes}
  14850. \end{figure}
  14851. Figure~\ref{fig:Rlambda-passes} provides an overview of all the passes needed
  14852. for the compilation of \LangLam{}.
  14853. \clearpage
  14854. \section{Challenge: Optimize Closures}
  14855. \label{sec:optimize-closures}
  14856. In this chapter we compiled lexically-scoped functions into a
  14857. relatively efficient representation: flat closures. However, even this
  14858. representation comes with some overhead. For example, consider the
  14859. following program with a function \code{tail\_sum} that does not have
  14860. any free variables and where all the uses of \code{tail\_sum} are in
  14861. applications where we know that only \code{tail\_sum} is being applied
  14862. (and not any other functions).
  14863. \begin{center}
  14864. \begin{minipage}{0.95\textwidth}
  14865. {\if\edition\racketEd
  14866. \begin{lstlisting}
  14867. (define (tail_sum [n : Integer] [s : Integer]) : Integer
  14868. (if (eq? n 0)
  14869. s
  14870. (tail_sum (- n 1) (+ n s))))
  14871. (+ (tail_sum 3 0) 36)
  14872. \end{lstlisting}
  14873. \fi}
  14874. {\if\edition\pythonEd
  14875. \begin{lstlisting}
  14876. def tail_sum(n : int, s : int) -> int:
  14877. if n == 0:
  14878. return s
  14879. else:
  14880. return tail_sum(n - 1, n + s)
  14881. print( tail_sum(3, 0) + 36)
  14882. \end{lstlisting}
  14883. \fi}
  14884. \end{minipage}
  14885. \end{center}
  14886. As described in this chapter, we uniformly apply closure conversion to
  14887. all functions, obtaining the following output for this program.
  14888. \begin{center}
  14889. \begin{minipage}{0.95\textwidth}
  14890. {\if\edition\racketEd
  14891. \begin{lstlisting}
  14892. (define (tail_sum1 [fvs5 : _] [n2 : Integer] [s3 : Integer]) : Integer
  14893. (if (eq? n2 0)
  14894. s3
  14895. (let ([clos4 (closure (list (fun-ref tail_sum1 2)))])
  14896. ((vector-ref clos4 0) clos4 (+ n2 -1) (+ n2 s3)))))
  14897. (define (main) : Integer
  14898. (+ (let ([clos6 (closure (list (fun-ref tail_sum1 2)))])
  14899. ((vector-ref clos6 0) clos6 3 0)) 27))
  14900. \end{lstlisting}
  14901. \fi}
  14902. {\if\edition\pythonEd
  14903. \begin{lstlisting}
  14904. def tail_sum(fvs_3:bot,n_0:int,s_1:int) -> int :
  14905. if n_0 == 0:
  14906. return s_1
  14907. else:
  14908. return (let clos_2 = (tail_sum,)
  14909. in clos_2[0](clos_2, n_0 - 1, n_0 + s_1))
  14910. def main() -> int :
  14911. print((let clos_4 = (tail_sum,)
  14912. in clos_4[0](clos_4, 3, 0)) + 36)
  14913. return 0
  14914. \end{lstlisting}
  14915. \fi}
  14916. \end{minipage}
  14917. \end{center}
  14918. In the previous chapter, there would be no allocation in the program
  14919. and the calls to \code{tail\_sum} would be direct calls. In contrast,
  14920. the above program allocates memory for each closure and the calls to
  14921. \code{tail\_sum} are indirect. These two differences incur
  14922. considerable overhead in a program such as this one, where the
  14923. allocations and indirect calls occur inside a tight loop.
  14924. One might think that this problem is trivial to solve: can't we just
  14925. recognize calls of the form \APPLY{\FUNREF{$f$}{$n$}}{$\mathit{args}$}
  14926. and compile them to direct calls instead of treating it like a call to
  14927. a closure? We would also drop the new \code{fvs} parameter of
  14928. \code{tail\_sum}.
  14929. %
  14930. However, this problem is not so trivial because a global function may
  14931. ``escape'' and become involved in applications that also involve
  14932. closures. Consider the following example in which the application
  14933. \CAPPLY{\code{f}}{\code{41}} needs to be compiled into a closure
  14934. application, because the \code{lambda} may flow into \code{f}, but the
  14935. \code{inc} function might also flow into \code{f}.
  14936. \begin{center}
  14937. \begin{minipage}{\textwidth}
  14938. % lambda_test_30.rkt
  14939. {\if\edition\racketEd
  14940. \begin{lstlisting}
  14941. (define (inc [x : Integer]) : Integer
  14942. (+ x 1))
  14943. (let ([y (read)])
  14944. (let ([f (if (eq? (read) 0)
  14945. inc
  14946. (lambda: ([x : Integer]) : Integer (- x y)))])
  14947. (f 41)))
  14948. \end{lstlisting}
  14949. \fi}
  14950. {\if\edition\pythonEd
  14951. \begin{lstlisting}
  14952. def add1(x : int) -> int:
  14953. return x + 1
  14954. y = input_int()
  14955. g : Callable[[int], int] = lambda x: x - y
  14956. f = add1 if input_int() == 0 else g
  14957. print( f(41) )
  14958. \end{lstlisting}
  14959. \fi}
  14960. \end{minipage}
  14961. \end{center}
  14962. If a global function name is used in any way other than as the
  14963. operator in a direct call, then we say that the function
  14964. \emph{escapes}. If a global function does not escape, then we do not
  14965. need to perform closure conversion on the function.
  14966. \begin{exercise}\normalfont\normalsize
  14967. Implement an auxiliary function for detecting which global
  14968. functions escape. Using that function, implement an improved version
  14969. of closure conversion that does not apply closure conversion to
  14970. global functions that do not escape but instead compiles them as
  14971. regular functions. Create several new test cases that check whether
  14972. you properly detect whether global functions escape or not.
  14973. \end{exercise}
  14974. So far we have reduced the overhead of calling global functions, but
  14975. it would also be nice to reduce the overhead of calling a
  14976. \code{lambda} when we can determine at compile time which
  14977. \code{lambda} will be called. We refer to such calls as \emph{known
  14978. calls}. Consider the following example in which a \code{lambda} is
  14979. bound to \code{f} and then applied.
  14980. {\if\edition\racketEd
  14981. % lambda_test_9.rkt
  14982. \begin{lstlisting}
  14983. (let ([y (read)])
  14984. (let ([f (lambda: ([x : Integer]) : Integer
  14985. (+ x y))])
  14986. (f 21)))
  14987. \end{lstlisting}
  14988. \fi}
  14989. {\if\edition\pythonEd
  14990. \begin{lstlisting}
  14991. y = input_int()
  14992. f : Callable[[int],int] = lambda x: x + y
  14993. print( f(21) )
  14994. \end{lstlisting}
  14995. \fi}
  14996. %
  14997. \noindent Closure conversion compiles the application
  14998. \CAPPLY{\code{f}}{\code{21}} into an indirect call:
  14999. %
  15000. {\if\edition\racketEd
  15001. \begin{lstlisting}
  15002. (define (lambda5 [fvs6 : (Vector _ Integer)] [x3 : Integer]) : Integer
  15003. (let ([y2 (vector-ref fvs6 1)])
  15004. (+ x3 y2)))
  15005. (define (main) : Integer
  15006. (let ([y2 (read)])
  15007. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15008. ((vector-ref f4 0) f4 21))))
  15009. \end{lstlisting}
  15010. \fi}
  15011. {\if\edition\pythonEd
  15012. \begin{lstlisting}
  15013. def lambda_3(fvs_4:tuple[bot,tuple[int]], x_2:int) -> int:
  15014. y_1 = fvs_4[1]
  15015. return x_2 + y_1[0]
  15016. def main() -> int:
  15017. y_1 = (777,)
  15018. y_1[0] = input_int()
  15019. f_0 = (lambda_3, y_1)
  15020. print((let clos_5 = f_0 in clos_5[0](clos_5, 21)))
  15021. return 0
  15022. \end{lstlisting}
  15023. \fi}
  15024. %
  15025. \noindent but we can instead compile the application
  15026. \CAPPLY{\code{f}}{\code{21}} into a direct call:
  15027. %
  15028. {\if\edition\racketEd
  15029. \begin{lstlisting}
  15030. (define (main) : Integer
  15031. (let ([y2 (read)])
  15032. (let ([f4 (Closure 1 (list (fun-ref lambda5 1) y2))])
  15033. ((fun-ref lambda5 1) f4 21))))
  15034. \end{lstlisting}
  15035. \fi}
  15036. {\if\edition\pythonEd
  15037. \begin{lstlisting}
  15038. def main() -> int:
  15039. y_1 = (777,)
  15040. y_1[0] = input_int()
  15041. f_0 = (lambda_3, y_1)
  15042. print(lambda_3(f_0, 21))
  15043. return 0
  15044. \end{lstlisting}
  15045. \fi}
  15046. The problem of determining which \code{lambda} will be called from a
  15047. particular application is quite challenging in general and the topic
  15048. of considerable research~\citep{Shivers:1988aa,Gilray:2016aa}. For the
  15049. following exercise we recommend that you compile an application to a
  15050. direct call when the operator is a variable and \racket{the variable
  15051. is \code{let}-bound to a closure} \python{the previous assignment to
  15052. the variable is a closure}. This can be accomplished by maintaining
  15053. an environment mapping variables to function names. Extend the
  15054. environment whenever you encounter a closure on the right-hand side of
  15055. a \racket{\code{let}}\python{assignment}, mapping the variable to the
  15056. name of the global function for the closure. This pass should come
  15057. after closure conversion.
  15058. \begin{exercise}\normalfont\normalsize
  15059. Implement a compiler pass, named \code{optimize\_known\_calls}, that
  15060. compiles known calls into direct calls. Verify that your compiler is
  15061. successful in this regard on several example programs.
  15062. \end{exercise}
  15063. These exercises only scratches the surface of optimizing of
  15064. closures. A good next step for the interested reader is to look at the
  15065. work of \citet{Keep:2012ab}.
  15066. \section{Further Reading}
  15067. The notion of lexically scoped functions predates modern computers by
  15068. about a decade. They were invented by \citet{Church:1932aa}, who
  15069. proposed the lambda calculus as a foundation for logic. Anonymous
  15070. functions were included in the LISP~\citep{McCarthy:1960dz}
  15071. programming language but were initially dynamically scoped. The Scheme
  15072. dialect of LISP adopted lexical scoping and
  15073. \citet{Guy-L.-Steele:1978yq} demonstrated how to efficiently compile
  15074. Scheme programs. However, environments were represented as linked
  15075. lists, so variable lookup was linear in the size of the
  15076. environment. \citet{Appel91} gives a detailed description of several
  15077. closure representations. In this chapter we represent environments
  15078. using flat closures, which were invented by
  15079. \citet{Cardelli:1983aa,Cardelli:1984aa} for the purposes of compiling
  15080. the ML language~\citep{Gordon:1978aa,Milner:1990fk}. With flat
  15081. closures, variable lookup is constant time but the time to create a
  15082. closure is proportional to the number of its free variables. Flat
  15083. closures were reinvented by \citet{Dybvig:1987ab} in his Ph.D. thesis
  15084. and used in Chez Scheme version 1~\citep{Dybvig:2006aa}.
  15085. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  15086. \chapter{Dynamic Typing}
  15087. \label{ch:Ldyn}
  15088. \index{subject}{dynamic typing}
  15089. In this chapter we discuss the compilation of \LangDyn{}, a
  15090. dynamically typed language that is a subset of
  15091. \racket{Racket}\python{Python}. The dynamic typing is in contrast to
  15092. the previous chapters, which have studied the compilation of
  15093. statically typed languages. In dynamically typed languages such as
  15094. \LangDyn{}, a particular expression may produce a value of a different
  15095. type each time it is executed. Consider the following example with a
  15096. conditional \code{if} expression that may return a Boolean or an
  15097. integer depending on the input to the program.
  15098. % part of dynamic_test_25.rkt
  15099. {\if\edition\racketEd
  15100. \begin{lstlisting}
  15101. (not (if (eq? (read) 1) #f 0))
  15102. \end{lstlisting}
  15103. \fi}
  15104. {\if\edition\pythonEd
  15105. \begin{lstlisting}
  15106. not (False if input_int() == 1 else 0)
  15107. \end{lstlisting}
  15108. \fi}
  15109. Languages that allow expressions to produce different kinds of values
  15110. are called \emph{polymorphic}, a word composed of the Greek roots
  15111. ``poly'', meaning ``many'', and ``morphos'', meaning ``form''. There
  15112. are several kinds of polymorphism in programming languages, such as
  15113. subtype polymorphism and parametric
  15114. polymorphism~\citep{Cardelli:1985kx}. The kind of polymorphism we
  15115. study in this chapter does not have a special name but it is the kind
  15116. that arises in dynamically typed languages.
  15117. Another characteristic of dynamically typed languages is that
  15118. primitive operations, such as \code{not}, are often defined to operate
  15119. on many different types of values. In fact, in
  15120. \racket{Racket}\python{Python}, the \code{not} operator produces a
  15121. result for any kind of value: given \FALSE{} it returns \TRUE{} and
  15122. given anything else it returns \FALSE{}.
  15123. Furthermore, even when primitive operations restrict their inputs to
  15124. values of a certain type, this restriction is enforced at runtime
  15125. instead of during compilation. For example, the tuple read
  15126. operation
  15127. \racket{\code{(vector-ref \#t 0)}}
  15128. \python{\code{True[0]}}
  15129. results in a run-time error because the first argument must
  15130. be a tuple, not a Boolean.
  15131. \begin{figure}[tp]
  15132. \centering
  15133. \fbox{
  15134. \begin{minipage}{0.97\textwidth}
  15135. {\if\edition\racketEd
  15136. \[
  15137. \begin{array}{rcl}
  15138. \itm{cmp} &::= & \key{eq?} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \\
  15139. \Exp &::=& \Int \MID \CREAD{} \MID \CNEG{\Exp}
  15140. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} \\
  15141. &\MID& \Var \MID \CLET{\Var}{\Exp}{\Exp} \\
  15142. &\MID& \key{\#t} \MID \key{\#f}
  15143. \MID \CBINOP{\key{and}}{\Exp}{\Exp}
  15144. \MID \CBINOP{\key{or}}{\Exp}{\Exp}
  15145. \MID \CUNIOP{\key{not}}{\Exp} \\
  15146. &\MID& \LP\itm{cmp}\;\Exp\;\Exp\RP \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15147. &\MID& \LP\key{vector}\;\Exp\ldots\RP \MID
  15148. \LP\key{vector-ref}\;\Exp\;\Exp\RP \\
  15149. &\MID& \LP\key{vector-set!}\;\Exp\;\Exp\;\Exp\RP \MID \LP\key{void}\RP \\
  15150. &\MID& \LP\Exp \; \Exp\ldots\RP
  15151. \MID \LP\key{lambda}\;\LP\Var\ldots\RP\;\Exp\RP \\
  15152. & \MID & \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP\\
  15153. & \MID & \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \MID \LP\key{void?}\;\Exp\RP \\
  15154. \Def &::=& \LP\key{define}\; \LP\Var \; \Var\ldots\RP \; \Exp\RP \\
  15155. \LangDynM{} &::=& \Def\ldots\; \Exp
  15156. \end{array}
  15157. \]
  15158. \fi}
  15159. {\if\edition\pythonEd
  15160. \[
  15161. \begin{array}{rcl}
  15162. \itm{cmp} &::= & \key{==} \MID \key{!=} \MID \key{<} \MID \key{<=} \MID \key{>} \MID \key{>=} \MID \key{is} \\
  15163. \Exp &::=& \Int \MID \key{input\_int}\LP\RP \MID \key{-}\;\Exp \MID \Exp \; \key{+} \; \Exp \MID \Exp \; \key{-} \; \Exp \MID \LP\Exp\RP \\
  15164. &\MID& \Var{} \MID \TRUE \MID \FALSE \MID \CAND{\Exp}{\Exp}
  15165. \MID \COR{\Exp}{\Exp} \MID \key{not}~\Exp \\
  15166. &\MID& \CCMP{\itm{cmp}}{\Exp}{\Exp}
  15167. \MID \CIF{\Exp}{\Exp}{\Exp} \\
  15168. &\MID& \Exp \key{,} \ldots \key{,} \Exp \MID \CGET{\Exp}{\Exp}
  15169. \MID \CLEN{\Exp} \\
  15170. &\MID& \CAPPLY{\Exp}{\Exp\code{,} \ldots}
  15171. \MID \CLAMBDA{\Var\code{, }\ldots}{\Exp}\\
  15172. \Stmt &::=& \key{print}\LP \Exp \RP \MID \Exp
  15173. \MID \Var\mathop{\key{=}}\Exp \\
  15174. &\MID& \key{if}~ \Exp \key{:}~ \Stmt^{+} ~\key{else:}~ \Stmt^{+}
  15175. \MID \key{while}~ \Exp \key{:}~ \Stmt^{+} \\
  15176. &\MID& \CRETURN{\Exp} \\
  15177. \Def &::=& \CDEFU{\Var}{\Var{,} \ldots}{\Stmt^{+}} \\
  15178. \LangDynM{} &::=& \Def\ldots \Stmt\ldots
  15179. \end{array}
  15180. \]
  15181. \fi}
  15182. \end{minipage}
  15183. }
  15184. \caption{Syntax of \LangDyn{}, an untyped language (a subset of \racket{Racket}\python{Python}).}
  15185. \label{fig:r7-concrete-syntax}
  15186. \end{figure}
  15187. \begin{figure}[tp]
  15188. \centering
  15189. \fbox{
  15190. \begin{minipage}{0.96\textwidth}
  15191. \small
  15192. {\if\edition\racketEd
  15193. \[
  15194. \begin{array}{lcl}
  15195. \Exp &::=& \INT{\Int} \MID \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} \\
  15196. &\MID& \PRIM{\itm{op}}{\Exp\ldots} \\
  15197. &\MID& \BOOL{\itm{bool}}
  15198. \MID \IF{\Exp}{\Exp}{\Exp} \\
  15199. &\MID& \VOID{} \MID \APPLY{\Exp}{\Exp\ldots} \\
  15200. &\MID& \LAMBDA{\LP\Var\ldots\RP}{\code{'Any}}{\Exp}\\
  15201. \Def &::=& \FUNDEF{\Var}{\LP\Var\ldots\RP}{\code{'Any}}{\code{'()}}{\Exp} \\
  15202. \LangDynM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15203. \end{array}
  15204. \]
  15205. \fi}
  15206. {\if\edition\pythonEd
  15207. \[
  15208. \begin{array}{rcl}
  15209. \itm{binaryop} &::= & \code{Add()} \MID \code{Sub()} \\
  15210. \itm{unaryop} &::= & \code{USub()} \MID \code{Not()} \\
  15211. \itm{boolop} &::=& \code{And()} \MID \code{Or()} \\
  15212. \itm{cmp} &::= & \code{Eq()} \MID \code{NotEq()} \MID \code{Lt()}
  15213. \MID \code{LtE()} \MID \code{Gt()} \MID \code{GtE()} \\
  15214. &\MID & \code{Is()} \\
  15215. \itm{bool} &::=& \code{True} \MID \code{False} \\
  15216. \Exp{} &::=& \INT{\Int} \MID \READ{} \\
  15217. &\MID& \UNIOP{\itm{unaryop}}{\Exp}
  15218. \MID \BINOP{\Exp}{\itm{binaryop}}{\Exp}
  15219. \MID \VAR{\Var{}} \\
  15220. &\MID& \BOOL{\itm{bool}}
  15221. \MID \BOOLOP{\itm{boolop}}{\Exp}{\Exp}\\
  15222. &\MID& \CMP{\Exp}{\itm{cmp}}{\Exp} \MID \IF{\Exp}{\Exp}{\Exp} \\
  15223. &\MID& \TUPLE{\Exp^{+}} \MID \GET{\Exp}{\Exp} \\
  15224. &\MID& \LEN{\Exp} \\
  15225. &\MID& \CALL{\Exp}{\Exp^{*}} \MID \LAMBDA{\Var^{*}}{\Exp} \\
  15226. \Stmt{} &::=& \PRINT{\Exp} \MID \EXPR{\Exp} \\
  15227. &\MID& \ASSIGN{\VAR{\Var}}{\Exp}\\
  15228. &\MID& \IFSTMT{\Exp}{\Stmt^{+}}{\Stmt^{+}}
  15229. \MID \WHILESTMT{\Exp}{\Stmt^{+}}\\
  15230. &\MID& \RETURN{\Exp} \\
  15231. \Params &::=& \LP\Var\key{,}\code{AnyType()}\RP^* \\
  15232. \Def &::=& \FUNDEF{\Var}{\Params}{\code{AnyType()}}{}{\Stmt^{+}} \\
  15233. \LangDynM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15234. \end{array}
  15235. \]
  15236. \fi}
  15237. \end{minipage}
  15238. }
  15239. \caption{The abstract syntax of \LangDyn{}.}
  15240. \label{fig:r7-syntax}
  15241. \end{figure}
  15242. The concrete and abstract syntax of \LangDyn{} is defined in
  15243. Figures~\ref{fig:r7-concrete-syntax} and \ref{fig:r7-syntax}.
  15244. %
  15245. There is no type checker for \LangDyn{} because dynamically typed
  15246. languages check types at runtime.
  15247. The definitional interpreter for \LangDyn{} is presented in
  15248. \racket{Figure~\ref{fig:interp-Ldyn}}
  15249. \python{Figures~\ref{fig:interp-Ldyn} and \ref{fig:interp-Ldyn-2}}
  15250. and its auxiliary functions are defined in
  15251. Figure~\ref{fig:interp-Ldyn-aux}. Consider the match case for
  15252. \INT{n}. Instead of simply returning the integer \code{n} (as
  15253. in the interpreter for \LangVar{} in Figure~\ref{fig:interp-Lvar}), the
  15254. interpreter for \LangDyn{} creates a \emph{tagged value}\index{subject}{tagged
  15255. value} that combines an underlying value with a tag that identifies
  15256. what kind of value it is. We define the following \racket{struct}\python{class}
  15257. to represented tagged values.
  15258. %
  15259. {\if\edition\racketEd
  15260. \begin{lstlisting}
  15261. (struct Tagged (value tag) #:transparent)
  15262. \end{lstlisting}
  15263. \fi}
  15264. {\if\edition\pythonEd
  15265. \begin{minipage}{\textwidth}
  15266. \begin{lstlisting}
  15267. @dataclass(eq=True)
  15268. class Tagged(Value):
  15269. value : Value
  15270. tag : str
  15271. def __str__(self):
  15272. return str(self.value)
  15273. \end{lstlisting}
  15274. \end{minipage}
  15275. \fi}
  15276. %
  15277. \racket{The tags are \code{Integer}, \code{Boolean}, \code{Void},
  15278. \code{Vector}, and \code{Procedure}.}
  15279. %
  15280. \python{The tags are \code{'int'}, \code{'bool'}, \code{'none'},
  15281. \code{'tuple'}, and \code{'function'}.}
  15282. %
  15283. Tags are closely related to types but don't always capture all the
  15284. information that a type does.
  15285. %
  15286. \racket{For example, a vector of type \code{(Vector Any Any)} is
  15287. tagged with \code{Vector} and a procedure of type \code{(Any Any ->
  15288. Any)} is tagged with \code{Procedure}.}
  15289. %
  15290. \python{For example, a tuple of type \code{TupleType([AnyType(),AnyType()])}
  15291. is tagged with \code{'tuple'} and a function of type
  15292. \code{FunctionType([AnyType(), AnyType()], AnyType())}
  15293. is tagged with \code{'function'}.}
  15294. Next consider the match case for accessing the element of a tuple.
  15295. The \racket{\code{check-tag}}\python{\code{untag}} auxiliary function
  15296. (Figure~\ref{fig:interp-Ldyn-aux}) is used to ensure that the first
  15297. argument is a tuple and the second is an integer.
  15298. \racket{
  15299. If they are not, a \code{trapped-error} is raised. Recall from
  15300. Section~\ref{sec:interp_Lint} that when a definition interpreter
  15301. raises a \code{trapped-error} error, the compiled code must also
  15302. signal an error by exiting with return code \code{255}. A
  15303. \code{trapped-error} is also raised if the index is not less than the
  15304. length of the vector.
  15305. }
  15306. %
  15307. \python{If they are not, an exception is raised. The compiled code
  15308. must also signal an error by exiting with return code \code{255}. A
  15309. exception is also raised if the index is not less than the length of the
  15310. tuple or if it is negative.}
  15311. \begin{figure}[tbp]
  15312. {\if\edition\racketEd
  15313. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15314. (define ((interp-Rdyn-exp env) ast)
  15315. (define recur (interp-Rdyn-exp env))
  15316. (match ast
  15317. [(Var x) (lookup x env)]
  15318. [(Int n) (Tagged n 'Integer)]
  15319. [(Bool b) (Tagged b 'Boolean)]
  15320. [(Lambda xs rt body)
  15321. (Tagged `(function ,xs ,body ,env) 'Procedure)]
  15322. [(Prim 'vector es)
  15323. (Tagged (apply vector (for/list ([e es]) (recur e))) 'Vector)]
  15324. [(Prim 'vector-ref (list e1 e2))
  15325. (define vec (recur e1)) (define i (recur e2))
  15326. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15327. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15328. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15329. (vector-ref (Tagged-value vec) (Tagged-value i))]
  15330. [(Prim 'vector-set! (list e1 e2 e3))
  15331. (define vec (recur e1)) (define i (recur e2)) (define arg (recur e3))
  15332. (check-tag vec 'Vector ast) (check-tag i 'Integer ast)
  15333. (unless (< (Tagged-value i) (vector-length (Tagged-value vec)))
  15334. (error 'trapped-error "index ~a too big\nin ~v" (Tagged-value i) ast))
  15335. (vector-set! (Tagged-value vec) (Tagged-value i) arg)
  15336. (Tagged (void) 'Void)]
  15337. [(Let x e body) ((interp-Rdyn-exp (cons (cons x (recur e)) env)) body)]
  15338. [(Prim 'and (list e1 e2)) (recur (If e1 e2 (Bool #f)))]
  15339. [(Prim 'or (list e1 e2))
  15340. (define v1 (recur e1))
  15341. (match (Tagged-value v1) [#f (recur e2)] [else v1])]
  15342. [(Prim 'eq? (list l r)) (Tagged (equal? (recur l) (recur r)) 'Boolean)]
  15343. [(Prim op (list e1))
  15344. #:when (set-member? type-predicates op)
  15345. (tag-value ((interp-op op) (Tagged-value (recur e1))))]
  15346. [(Prim op es)
  15347. (define args (map recur es))
  15348. (define tags (for/list ([arg args]) (Tagged-tag arg)))
  15349. (unless (for/or ([expected-tags (op-tags op)])
  15350. (equal? expected-tags tags))
  15351. (error 'trapped-error "illegal argument tags ~a\nin ~v" tags ast))
  15352. (tag-value
  15353. (apply (interp-op op) (for/list ([a args]) (Tagged-value a))))]
  15354. [(If q t f)
  15355. (match (Tagged-value (recur q)) [#f (recur f)] [else (recur t)])]
  15356. [(Apply f es)
  15357. (define new-f (recur f)) (define args (map recur es))
  15358. (check-tag new-f 'Procedure ast) (define f-val (Tagged-value new-f))
  15359. (match f-val
  15360. [`(function ,xs ,body ,lam-env)
  15361. (unless (eq? (length xs) (length args))
  15362. (error 'trapped-error "~a != ~a\nin ~v" (length args) (length xs) ast))
  15363. (define new-env (append (map cons xs args) lam-env))
  15364. ((interp-Rdyn-exp new-env) body)]
  15365. [else (error "interp-Rdyn-exp, expected function, not" f-val)])]))
  15366. \end{lstlisting}
  15367. \fi}
  15368. {\if\edition\pythonEd
  15369. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15370. class InterpLdyn(InterpLlambda):
  15371. def interp_exp(self, e, env):
  15372. match e:
  15373. case Constant(n):
  15374. return self.tag(super().interp_exp(e, env))
  15375. case Tuple(es, Load()):
  15376. return self.tag(super().interp_exp(e, env))
  15377. case Lambda(params, body):
  15378. return self.tag(super().interp_exp(e, env))
  15379. case Call(Name('input_int'), []):
  15380. return self.tag(super().interp_exp(e, env))
  15381. case BinOp(left, Add(), right):
  15382. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15383. return self.tag(self.untag(l, 'int', e) + self.untag(r, 'int', e))
  15384. case BinOp(left, Sub(), right):
  15385. l = self.interp_exp(left, env); r = self.interp_exp(right, env)
  15386. return self.tag(self.untag(l, 'int', e) - self.untag(r, 'int', e))
  15387. case UnaryOp(USub(), e1):
  15388. v = self.interp_exp(e1, env)
  15389. return self.tag(- self.untag(v, 'int', e))
  15390. case IfExp(test, body, orelse):
  15391. v = self.interp_exp(test, env)
  15392. if self.untag(v, 'bool', e):
  15393. return self.interp_exp(body, env)
  15394. else:
  15395. return self.interp_exp(orelse, env)
  15396. case UnaryOp(Not(), e1):
  15397. v = self.interp_exp(e1, env)
  15398. return self.tag(not self.untag(v, 'bool', e))
  15399. case BoolOp(And(), values):
  15400. left = values[0]; right = values[1]
  15401. l = self.interp_exp(left, env)
  15402. if self.untag(l, 'bool', e):
  15403. return self.interp_exp(right, env)
  15404. else:
  15405. return self.tag(False)
  15406. case BoolOp(Or(), values):
  15407. left = values[0]; right = values[1]
  15408. l = self.interp_exp(left, env)
  15409. if self.untag(l, 'bool', e):
  15410. return self.tag(True)
  15411. else:
  15412. return self.interp_exp(right, env)
  15413. case Compare(left, [cmp], [right]):
  15414. l = self.interp_exp(left, env)
  15415. r = self.interp_exp(right, env)
  15416. if l.tag == r.tag:
  15417. return self.tag(self.interp_cmp(cmp)(l.value, r.value))
  15418. else:
  15419. raise Exception('interp Compare unexpected ' \
  15420. + repr(l) + ' ' + repr(r))
  15421. case Subscript(tup, index, Load()):
  15422. t = self.interp_exp(tup, env)
  15423. n = self.interp_exp(index, env)
  15424. return self.untag(t, 'tuple', e)[self.untag(n, 'int', e)]
  15425. case Call(Name('len'), [tup]):
  15426. t = self.interp_exp(tup, env)
  15427. return self.tag(len(self.untag(t, 'tuple', e)))
  15428. case _:
  15429. return self.tag(super().interp_exp(e, env))
  15430. \end{lstlisting}
  15431. \fi}
  15432. \caption{Interpreter for the \LangDyn{} language\python{, part 1}.}
  15433. \label{fig:interp-Ldyn}
  15434. \end{figure}
  15435. \begin{figure}[tbp]
  15436. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15437. class InterpLdyn(InterpLlambda):
  15438. def interp_stmts(self, ss, env):
  15439. if len(ss) == 0:
  15440. return
  15441. match ss[0]:
  15442. case If(test, body, orelse):
  15443. v = self.interp_exp(test, env)
  15444. if self.untag(v, 'bool', ss[0]):
  15445. return self.interp_stmts(body + ss[1:], env)
  15446. else:
  15447. return self.interp_stmts(orelse + ss[1:], env)
  15448. case While(test, body, []):
  15449. while self.untag(self.interp_exp(test, env), 'bool', ss[0]):
  15450. self.interp_stmts(body, env)
  15451. return self.interp_stmts(ss[1:], env)
  15452. case Assign([Subscript(tup, index)], value):
  15453. tup = self.interp_exp(tup, env)
  15454. index = self.interp_exp(index, env)
  15455. tup_v = self.untag(tup, 'tuple', ss[0])
  15456. index_v = self.untag(index, 'int', ss[0])
  15457. tup_v[index_v] = self.interp_exp(value, env)
  15458. return self.interp_stmts(ss[1:], env)
  15459. case FunctionDef(name, params, bod, dl, returns, comment):
  15460. ps = [x for (x,t) in params]
  15461. env[name] = self.tag(Function(name, ps, bod, env))
  15462. return self.interp_stmts(ss[1:], env)
  15463. case _:
  15464. return super().interp_stmts(ss, env)
  15465. \end{lstlisting}
  15466. \caption{Interpreter for the \LangDyn{} language\python{, part 2}.}
  15467. \label{fig:interp-Ldyn-2}
  15468. \end{figure}
  15469. \begin{figure}[tbp]
  15470. {\if\edition\racketEd
  15471. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15472. (define (interp-op op)
  15473. (match op
  15474. ['+ fx+]
  15475. ['- fx-]
  15476. ['read read-fixnum]
  15477. ['not (lambda (v) (match v [#t #f] [#f #t]))]
  15478. ['< (lambda (v1 v2)
  15479. (cond [(and (fixnum? v1) (fixnum? v2)) (< v1 v2)]))]
  15480. ['<= (lambda (v1 v2)
  15481. (cond [(and (fixnum? v1) (fixnum? v2)) (<= v1 v2)]))]
  15482. ['> (lambda (v1 v2)
  15483. (cond [(and (fixnum? v1) (fixnum? v2)) (> v1 v2)]))]
  15484. ['>= (lambda (v1 v2)
  15485. (cond [(and (fixnum? v1) (fixnum? v2)) (>= v1 v2)]))]
  15486. ['boolean? boolean?]
  15487. ['integer? fixnum?]
  15488. ['void? void?]
  15489. ['vector? vector?]
  15490. ['vector-length vector-length]
  15491. ['procedure? (match-lambda
  15492. [`(functions ,xs ,body ,env) #t] [else #f])]
  15493. [else (error 'interp-op "unknown operator" op)]))
  15494. (define (op-tags op)
  15495. (match op
  15496. ['+ '((Integer Integer))]
  15497. ['- '((Integer Integer) (Integer))]
  15498. ['read '(())]
  15499. ['not '((Boolean))]
  15500. ['< '((Integer Integer))]
  15501. ['<= '((Integer Integer))]
  15502. ['> '((Integer Integer))]
  15503. ['>= '((Integer Integer))]
  15504. ['vector-length '((Vector))]))
  15505. (define type-predicates
  15506. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15507. (define (tag-value v)
  15508. (cond [(boolean? v) (Tagged v 'Boolean)]
  15509. [(fixnum? v) (Tagged v 'Integer)]
  15510. [(procedure? v) (Tagged v 'Procedure)]
  15511. [(vector? v) (Tagged v 'Vector)]
  15512. [(void? v) (Tagged v 'Void)]
  15513. [else (error 'tag-value "unidentified value ~a" v)]))
  15514. (define (check-tag val expected ast)
  15515. (define tag (Tagged-tag val))
  15516. (unless (eq? tag expected)
  15517. (error 'trapped-error "expected ~a, not ~a\nin ~v" expected tag ast)))
  15518. \end{lstlisting}
  15519. \fi}
  15520. {\if\edition\pythonEd
  15521. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15522. class InterpLdyn(InterpLlambda):
  15523. def tag(self, v):
  15524. if v is True or v is False:
  15525. return Tagged(v, 'bool')
  15526. elif isinstance(v, int):
  15527. return Tagged(v, 'int')
  15528. elif isinstance(v, Function):
  15529. return Tagged(v, 'function')
  15530. elif isinstance(v, tuple):
  15531. return Tagged(v, 'tuple')
  15532. elif isinstance(v, type(None)):
  15533. return Tagged(v, 'none')
  15534. else:
  15535. raise Exception('tag: unexpected ' + repr(v))
  15536. def untag(self, v, expected_tag, ast):
  15537. match v:
  15538. case Tagged(val, tag) if tag == expected_tag:
  15539. return val
  15540. case _:
  15541. raise Exception('expected Tagged value with ' + expected_tag + ', not ' + ' ' + repr(v))
  15542. def apply_fun(self, fun, args, e):
  15543. f = self.untag(fun, 'function', e)
  15544. return super().apply_fun(f, args, e)
  15545. \end{lstlisting}
  15546. \fi}
  15547. \caption{Auxiliary functions for the \LangDyn{} interpreter.}
  15548. \label{fig:interp-Ldyn-aux}
  15549. \end{figure}
  15550. \clearpage
  15551. \section{Representation of Tagged Values}
  15552. The interpreter for \LangDyn{} introduced a new kind of value, a tagged
  15553. value. To compile \LangDyn{} to x86 we must decide how to represent tagged
  15554. values at the bit level. Because almost every operation in \LangDyn{}
  15555. involves manipulating tagged values, the representation must be
  15556. efficient. Recall that all of our values are 64 bits. We shall steal
  15557. the 3 right-most bits to encode the tag. We use $001$ to identify
  15558. integers, $100$ for Booleans, $010$ for vectors, $011$ for procedures,
  15559. and $101$ for the void value\python{, \key{None}}. We define the following auxiliary
  15560. function for mapping types to tag codes.
  15561. {\if\edition\racketEd
  15562. \begin{align*}
  15563. \itm{tagof}(\key{Integer}) &= 001 \\
  15564. \itm{tagof}(\key{Boolean}) &= 100 \\
  15565. \itm{tagof}((\key{Vector} \ldots)) &= 010 \\
  15566. \itm{tagof}((\ldots \key{->} \ldots)) &= 011 \\
  15567. \itm{tagof}(\key{Void}) &= 101
  15568. \end{align*}
  15569. \fi}
  15570. {\if\edition\pythonEd
  15571. \begin{align*}
  15572. \itm{tagof}(\key{IntType()}) &= 001 \\
  15573. \itm{tagof}(\key{BoolType()}) &= 100 \\
  15574. \itm{tagof}(\key{TupleType(ts)}) &= 010 \\
  15575. \itm{tagof}(\key{FunctionType(ps, rt)}) &= 011 \\
  15576. \itm{tagof}(\key{type(None)}) &= 101
  15577. \end{align*}
  15578. \fi}
  15579. This stealing of 3 bits comes at some price: integers are now restricted
  15580. to the range from $-2^{60}$ to $2^{60}$. The stealing does not adversely
  15581. affect vectors and procedures because those values are addresses, and
  15582. our addresses are 8-byte aligned so the rightmost 3 bits are unused,
  15583. they are always $000$. Thus, we do not lose information by overwriting
  15584. the rightmost 3 bits with the tag and we can simply zero-out the tag
  15585. to recover the original address.
  15586. To make tagged values into first-class entities, we can give them a
  15587. type, called \racket{\code{Any}}\python{\code{AnyType()}}, and define operations
  15588. such as \code{Inject} and \code{Project} for creating and using them,
  15589. yielding the \LangAny{} intermediate language. We describe how to
  15590. compile \LangDyn{} to \LangAny{} in Section~\ref{sec:compile-r7}
  15591. but first we describe the \LangAny{} language in greater detail.
  15592. \section{The \LangAny{} Language}
  15593. \label{sec:Rany-lang}
  15594. \newcommand{\LanyASTRacket}{
  15595. \begin{array}{lcl}
  15596. \Type &::= & \key{Any} \\
  15597. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  15598. \MID \LP\key{Vector}\; \key{Any}\ldots\RP \\
  15599. &\MID& \LP\key{Any}\ldots \; \key{->}\; \key{Any}\RP\\
  15600. \itm{op} &::= & \code{any-vector-length}
  15601. \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15602. &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15603. \MID \code{procedure?} \MID \code{void?} \\
  15604. \Exp &::=& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType}
  15605. \end{array}
  15606. }
  15607. \newcommand{\LanyASTPython}{
  15608. \begin{array}{lcl}
  15609. \Type &::= & \key{AnyType()} \\
  15610. \FType &::=& \key{IntType()} \MID \key{BoolType()} \MID \key{VoidType()}
  15611. \MID \key{TupleType}\LS\key{AnyType()}^+\RS \\
  15612. &\MID& \key{FunctionType}\LP \key{AnyType()}^{*}\key{, }\key{AnyType()}\RP \\
  15613. \Exp & ::= & \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15614. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS\Exp\key{, }\INT{n}\RS}\\
  15615. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS\Exp\RS}
  15616. %% &\MID& \CALL{\VAR{\key{'is\_int'}}}{\Exp}
  15617. %% \MID \CALL{\VAR{\key{'is\_bool'}}}{\Exp} \\
  15618. %% &\MID& \CALL{\VAR{\key{'is\_none'}}}{\Exp}
  15619. %% \MID \CALL{\VAR{\key{'is\_tuple'}}}{\Exp} \\
  15620. %% &\MID& \CALL{\VAR{\key{'is\_function'}}}{\Exp}
  15621. \end{array}
  15622. }
  15623. \begin{figure}[tp]
  15624. \centering
  15625. \fbox{
  15626. \begin{minipage}{0.96\textwidth}
  15627. \small
  15628. {\if\edition\racketEd
  15629. \[
  15630. \begin{array}{l}
  15631. \gray{\LintOpAST} \\ \hline
  15632. \gray{\LvarASTRacket{}} \\ \hline
  15633. \gray{\LifASTRacket{}} \\ \hline
  15634. \gray{\LwhileASTRacket{}} \\ \hline
  15635. \gray{\LtupASTRacket{}} \\ \hline
  15636. \gray{\LfunASTRacket} \\ \hline
  15637. \gray{\LlambdaASTRacket} \\ \hline
  15638. \LanyASTRacket \\
  15639. \begin{array}{lcl}
  15640. %% \Type &::= & \ldots \MID \key{Any} \\
  15641. %% \itm{op} &::= & \ldots \MID \code{any-vector-length}
  15642. %% \MID \code{any-vector-ref} \MID \code{any-vector-set!}\\
  15643. %% &\MID& \code{boolean?} \MID \code{integer?} \MID \code{vector?}
  15644. %% \MID \code{procedure?} \MID \code{void?} \\
  15645. %% \Exp &::=& \ldots
  15646. %% \MID \gray{ \PRIM{\itm{op}}{\Exp\ldots} } \\
  15647. %% &\MID& \INJECT{\Exp}{\FType} \MID \PROJECT{\Exp}{\FType} \\
  15648. %% \Def &::=& \gray{ \FUNDEF{\Var}{\LP[\Var \code{:} \Type]\ldots\RP}{\Type}{\code{'()}}{\Exp} }\\
  15649. \LangAnyM{} &::=& \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp}
  15650. \end{array}
  15651. \end{array}
  15652. \]
  15653. \fi}
  15654. {\if\edition\pythonEd
  15655. \[
  15656. \begin{array}{l}
  15657. \gray{\LintASTPython} \\ \hline
  15658. \gray{\LvarASTPython{}} \\ \hline
  15659. \gray{\LifASTPython{}} \\ \hline
  15660. \gray{\LwhileASTPython{}} \\ \hline
  15661. \gray{\LtupASTPython{}} \\ \hline
  15662. \gray{\LfunASTPython} \\ \hline
  15663. \gray{\LlambdaASTPython} \\ \hline
  15664. \LanyASTPython \\
  15665. \begin{array}{lcl}
  15666. \LangAnyM{} &::=& \PROGRAM{}{\LS \Def \ldots \Stmt \ldots \RS}
  15667. \end{array}
  15668. \end{array}
  15669. \]
  15670. \fi}
  15671. \end{minipage}
  15672. }
  15673. \caption{The abstract syntax of \LangAny{}, extending \LangLam{} (Figure~\ref{fig:Rlam-syntax}).}
  15674. \label{fig:Rany-syntax}
  15675. \end{figure}
  15676. The abstract syntax of \LangAny{} is defined in Figure~\ref{fig:Rany-syntax}.
  15677. \racket{(The concrete syntax of \LangAny{} is in the Appendix,
  15678. Figure~\ref{fig:Rany-concrete-syntax}.)} The $\INJECT{e}{T}$ form
  15679. converts the value produced by expression $e$ of type $T$ into a
  15680. tagged value. The $\PROJECT{e}{T}$ form converts the tagged value
  15681. produced by expression $e$ into a value of type $T$ or halts the
  15682. program if the type tag does not match $T$.
  15683. %
  15684. Note that in both \code{Inject} and \code{Project}, the type $T$ is
  15685. restricted to a flat type $\FType$, which simplifies the
  15686. implementation and corresponds with the needs for compiling \LangDyn{}.
  15687. The \racket{\code{any-vector}} operators
  15688. \python{\code{any\_tuple\_load} and \code{any\_len}}
  15689. adapt the tuple operations so that they can be applied to a value of
  15690. type \racket{\code{Any}}\python{\code{AnyType}}. They also generalize the
  15691. tuple operations in that the index is not restricted to be a literal
  15692. integer in the grammar but is allowed to be any expression.
  15693. \racket{The type predicates such as
  15694. \racket{\key{boolean?}}\python{\key{is\_bool}} expect their argument
  15695. to produce a tagged value; they return {\TRUE} if the tag corresponds to
  15696. the predicate and they return {\FALSE} otherwise.}
  15697. The type checker for \LangAny{} is shown in
  15698. Figure~\ref{fig:type-check-Rany}
  15699. %
  15700. \racket{ and uses the auxiliary functions in
  15701. Figure~\ref{fig:type-check-Rany-aux}}.
  15702. %
  15703. The interpreter for \LangAny{} is in Figure~\ref{fig:interp-Rany} and
  15704. its auxiliary functions are in Figure~\ref{fig:interp-Rany-aux}.
  15705. \begin{figure}[btp]
  15706. {\if\edition\racketEd
  15707. \begin{lstlisting}[basicstyle=\ttfamily\small]
  15708. (define type-check-Rany_class
  15709. (class type-check-Rlambda_class
  15710. (super-new)
  15711. (inherit check-type-equal?)
  15712. (define/override (type-check-exp env)
  15713. (lambda (e)
  15714. (define recur (type-check-exp env))
  15715. (match e
  15716. [(Inject e1 ty)
  15717. (unless (flat-ty? ty)
  15718. (error 'type-check "may only inject from flat type, not ~a" ty))
  15719. (define-values (new-e1 e-ty) (recur e1))
  15720. (check-type-equal? e-ty ty e)
  15721. (values (Inject new-e1 ty) 'Any)]
  15722. [(Project e1 ty)
  15723. (unless (flat-ty? ty)
  15724. (error 'type-check "may only project to flat type, not ~a" ty))
  15725. (define-values (new-e1 e-ty) (recur e1))
  15726. (check-type-equal? e-ty 'Any e)
  15727. (values (Project new-e1 ty) ty)]
  15728. [(Prim 'any-vector-length (list e1))
  15729. (define-values (e1^ t1) (recur e1))
  15730. (check-type-equal? t1 'Any e)
  15731. (values (Prim 'any-vector-length (list e1^)) 'Integer)]
  15732. [(Prim 'any-vector-ref (list e1 e2))
  15733. (define-values (e1^ t1) (recur e1))
  15734. (define-values (e2^ t2) (recur e2))
  15735. (check-type-equal? t1 'Any e)
  15736. (check-type-equal? t2 'Integer e)
  15737. (values (Prim 'any-vector-ref (list e1^ e2^)) 'Any)]
  15738. [(Prim 'any-vector-set! (list e1 e2 e3))
  15739. (define-values (e1^ t1) (recur e1))
  15740. (define-values (e2^ t2) (recur e2))
  15741. (define-values (e3^ t3) (recur e3))
  15742. (check-type-equal? t1 'Any e)
  15743. (check-type-equal? t2 'Integer e)
  15744. (check-type-equal? t3 'Any e)
  15745. (values (Prim 'any-vector-set! (list e1^ e2^ e3^)) 'Void)]
  15746. [(ValueOf e ty)
  15747. (define-values (new-e e-ty) (recur e))
  15748. (values (ValueOf new-e ty) ty)]
  15749. [(Prim pred (list e1))
  15750. #:when (set-member? (type-predicates) pred)
  15751. (define-values (new-e1 e-ty) (recur e1))
  15752. (check-type-equal? e-ty 'Any e)
  15753. (values (Prim pred (list new-e1)) 'Boolean)]
  15754. [(If cnd thn els)
  15755. (define-values (cnd^ Tc) (recur cnd))
  15756. (define-values (thn^ Tt) (recur thn))
  15757. (define-values (els^ Te) (recur els))
  15758. (check-type-equal? Tc 'Boolean cnd)
  15759. (check-type-equal? Tt Te e)
  15760. (values (If cnd^ thn^ els^) (combine-types Tt Te))]
  15761. [(Exit) (values (Exit) '_)]
  15762. [(Prim 'eq? (list arg1 arg2))
  15763. (define-values (e1 t1) (recur arg1))
  15764. (define-values (e2 t2) (recur arg2))
  15765. (match* (t1 t2)
  15766. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (void)]
  15767. [(other wise) (check-type-equal? t1 t2 e)])
  15768. (values (Prim 'eq? (list e1 e2)) 'Boolean)]
  15769. [else ((super type-check-exp env) e)])))
  15770. ))
  15771. \end{lstlisting}
  15772. \fi}
  15773. {\if\edition\pythonEd
  15774. \begin{lstlisting}
  15775. class TypeCheckLany(TypeCheckLlambda):
  15776. def type_check_exp(self, e, env):
  15777. match e:
  15778. case Inject(value, typ):
  15779. self.check_exp(value, typ, env)
  15780. return AnyType()
  15781. case Project(value, typ):
  15782. self.check_exp(value, AnyType(), env)
  15783. return typ
  15784. case Call(Name('any_tuple_load'), [tup, index]):
  15785. self.check_exp(tup, AnyType(), env)
  15786. return AnyType()
  15787. case Call(Name('any_len'), [tup]):
  15788. self.check_exp(tup, AnyType(), env)
  15789. return IntType()
  15790. case Call(Name('arity'), [fun]):
  15791. ty = self.type_check_exp(fun, env)
  15792. match ty:
  15793. case FunctionType(ps, rt):
  15794. return IntType()
  15795. case TupleType([FunctionType(ps,rs)]):
  15796. return IntType()
  15797. case _:
  15798. raise Exception('type_check_exp arity unexpected ' + repr(ty))
  15799. case Call(Name('make_any'), [value, tag]):
  15800. self.type_check_exp(value, env)
  15801. self.check_exp(tag, IntType(), env)
  15802. return AnyType()
  15803. case ValueOf(value, typ):
  15804. self.check_exp(value, AnyType(), env)
  15805. return typ
  15806. case TagOf(value):
  15807. self.check_exp(value, AnyType(), env)
  15808. return IntType()
  15809. case Call(Name('exit'), []):
  15810. return Bottom()
  15811. case AnnLambda(params, returns, body):
  15812. new_env = {x:t for (x,t) in env.items()}
  15813. for (x,t) in params:
  15814. new_env[x] = t
  15815. return_t = self.type_check_exp(body, new_env)
  15816. self.check_type_equal(returns, return_t, e)
  15817. return FunctionType([t for (x,t) in params], return_t)
  15818. case _:
  15819. return super().type_check_exp(e, env)
  15820. \end{lstlisting}
  15821. \fi}
  15822. \caption{Type checker for the \LangAny{} language.}
  15823. \label{fig:type-check-Rany}
  15824. \end{figure}
  15825. {\if\edition\racketEd
  15826. \begin{figure}[tbp]
  15827. {\if\edition\racketEd
  15828. \begin{lstlisting}
  15829. (define/override (operator-types)
  15830. (append
  15831. '((integer? . ((Any) . Boolean))
  15832. (vector? . ((Any) . Boolean))
  15833. (procedure? . ((Any) . Boolean))
  15834. (void? . ((Any) . Boolean))
  15835. (tag-of-any . ((Any) . Integer))
  15836. (make-any . ((_ Integer) . Any)))
  15837. (super operator-types)))
  15838. (define/public (type-predicates)
  15839. (set 'boolean? 'integer? 'vector? 'procedure? 'void?))
  15840. (define/public (combine-types t1 t2)
  15841. (match (list t1 t2)
  15842. [(list '_ t2) t2]
  15843. [(list t1 '_) t1]
  15844. [(list `(Vector ,ts1 ...)
  15845. `(Vector ,ts2 ...))
  15846. `(Vector ,@(for/list ([t1 ts1] [t2 ts2])
  15847. (combine-types t1 t2)))]
  15848. [(list `(,ts1 ... -> ,rt1)
  15849. `(,ts2 ... -> ,rt2))
  15850. `(,@(for/list ([t1 ts1] [t2 ts2])
  15851. (combine-types t1 t2))
  15852. -> ,(combine-types rt1 rt2))]
  15853. [else t1]))
  15854. (define/public (flat-ty? ty)
  15855. (match ty
  15856. [(or `Integer `Boolean '_ `Void) #t]
  15857. [`(Vector ,ts ...) (for/and ([t ts]) (eq? t 'Any))]
  15858. [`(,ts ... -> ,rt)
  15859. (and (eq? rt 'Any) (for/and ([t ts]) (eq? t 'Any)))]
  15860. [else #f]))
  15861. \end{lstlisting}
  15862. \fi}
  15863. \caption{Auxiliary methods for type checking \LangAny{}.}
  15864. \label{fig:type-check-Rany-aux}
  15865. \end{figure}
  15866. \fi}
  15867. \begin{figure}[btp]
  15868. {\if\edition\racketEd
  15869. \begin{lstlisting}
  15870. (define interp-Rany_class
  15871. (class interp-Rlambda_class
  15872. (super-new)
  15873. (define/override (interp-op op)
  15874. (match op
  15875. ['boolean? (match-lambda
  15876. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Boolean))]
  15877. [else #f])]
  15878. ['integer? (match-lambda
  15879. [`(tagged ,v1 ,tg) (equal? tg (any-tag 'Integer))]
  15880. [else #f])]
  15881. ['vector? (match-lambda
  15882. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Vector Any)))]
  15883. [else #f])]
  15884. ['procedure? (match-lambda
  15885. [`(tagged ,v1 ,tg) (equal? tg (any-tag `(Any -> Any)))]
  15886. [else #f])]
  15887. ['eq? (match-lambda*
  15888. [`((tagged ,v1^ ,tg1) (tagged ,v2^ ,tg2))
  15889. (and (eq? v1^ v2^) (equal? tg1 tg2))]
  15890. [ls (apply (super interp-op op) ls)])]
  15891. ['any-vector-ref (lambda (v i)
  15892. (match v [`(tagged ,v^ ,tg) (vector-ref v^ i)]))]
  15893. ['any-vector-set! (lambda (v i a)
  15894. (match v [`(tagged ,v^ ,tg) (vector-set! v^ i a)]))]
  15895. ['any-vector-length (lambda (v)
  15896. (match v [`(tagged ,v^ ,tg) (vector-length v^)]))]
  15897. [else (super interp-op op)]))
  15898. (define/override ((interp-exp env) e)
  15899. (define recur (interp-exp env))
  15900. (match e
  15901. [(Inject e ty) `(tagged ,(recur e) ,(any-tag ty))]
  15902. [(Project e ty2) (apply-project (recur e) ty2)]
  15903. [else ((super interp-exp env) e)]))
  15904. ))
  15905. (define (interp-Rany p)
  15906. (send (new interp-Rany_class) interp-program p))
  15907. \end{lstlisting}
  15908. \fi}
  15909. {\if\edition\pythonEd
  15910. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  15911. class InterpLany(InterpLlambda):
  15912. def interp_exp(self, e, env):
  15913. match e:
  15914. case Inject(value, typ):
  15915. v = self.interp_exp(value, env)
  15916. return Tagged(v, self.type_to_tag(typ))
  15917. case Project(value, typ):
  15918. v = self.interp_exp(value, env)
  15919. match v:
  15920. case Tagged(val, tag) if self.type_to_tag(typ) == tag:
  15921. return val
  15922. case _:
  15923. raise Exception('interp project to ' + repr(typ) \
  15924. + ' unexpected ' + repr(v))
  15925. case Call(Name('any_tuple_load'), [tup, index]):
  15926. tv = self.interp_exp(tup, env)
  15927. n = self.interp_exp(index, env)
  15928. match tv:
  15929. case Tagged(v, tag):
  15930. return v[n]
  15931. case _:
  15932. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15933. case Call(Name('any_tuple_store'), [tup, index, value]):
  15934. tv = self.interp_exp(tup, env)
  15935. n = self.interp_exp(index, env)
  15936. val = self.interp_exp(value, env)
  15937. match tv:
  15938. case Tagged(v, tag):
  15939. v[n] = val
  15940. return None
  15941. case _:
  15942. raise Exception('interp any_tuple_load unexpected ' + repr(tv))
  15943. case Call(Name('any_len'), [value]):
  15944. v = self.interp_exp(value, env)
  15945. match v:
  15946. case Tagged(value, tag):
  15947. return len(value)
  15948. case _:
  15949. raise Exception('interp any_len unexpected ' + repr(v))
  15950. case Call(Name('make_any'), [value, tag]):
  15951. v = self.interp_exp(value, env)
  15952. t = self.interp_exp(tag, env)
  15953. return Tagged(v, t)
  15954. case Call(Name('arity'), [fun]):
  15955. f = self.interp_exp(fun, env)
  15956. return self.arity(f)
  15957. case Call(Name('exit'), []):
  15958. trace('exiting!')
  15959. exit(0)
  15960. case TagOf(value):
  15961. v = self.interp_exp(value, env)
  15962. match v:
  15963. case Tagged(val, tag):
  15964. return tag
  15965. case _:
  15966. raise Exception('interp TagOf unexpected ' + repr(v))
  15967. case ValueOf(value, typ):
  15968. v = self.interp_exp(value, env)
  15969. match v:
  15970. case Tagged(val, tag):
  15971. return val
  15972. case _:
  15973. raise Exception('interp ValueOf unexpected ' + repr(v))
  15974. case AnnLambda(params, returns, body):
  15975. return Function('lambda', [x for (x,t) in params], [Return(body)], env)
  15976. case _:
  15977. return super().interp_exp(e, env)
  15978. \end{lstlisting}
  15979. \fi}
  15980. \caption{Interpreter for \LangAny{}.}
  15981. \label{fig:interp-Rany}
  15982. \end{figure}
  15983. \begin{figure}[tbp]
  15984. {\if\edition\racketEd
  15985. \begin{lstlisting}
  15986. (define/public (apply-inject v tg) (Tagged v tg))
  15987. (define/public (apply-project v ty2)
  15988. (define tag2 (any-tag ty2))
  15989. (match v
  15990. [(Tagged v1 tag1)
  15991. (cond
  15992. [(eq? tag1 tag2)
  15993. (match ty2
  15994. [`(Vector ,ts ...)
  15995. (define l1 ((interp-op 'vector-length) v1))
  15996. (cond
  15997. [(eq? l1 (length ts)) v1]
  15998. [else (error 'apply-project "vector length mismatch, ~a != ~a"
  15999. l1 (length ts))])]
  16000. [`(,ts ... -> ,rt)
  16001. (match v1
  16002. [`(function ,xs ,body ,env)
  16003. (cond [(eq? (length xs) (length ts)) v1]
  16004. [else
  16005. (error 'apply-project "arity mismatch ~a != ~a"
  16006. (length xs) (length ts))])]
  16007. [else (error 'apply-project "expected function not ~a" v1)])]
  16008. [else v1])]
  16009. [else (error 'apply-project "tag mismatch ~a != ~a" tag1 tag2)])]
  16010. [else (error 'apply-project "expected tagged value, not ~a" v)]))
  16011. \end{lstlisting}
  16012. \fi}
  16013. {\if\edition\pythonEd
  16014. \begin{lstlisting}
  16015. class InterpLany(InterpLlambda):
  16016. def type_to_tag(self, typ):
  16017. match typ:
  16018. case FunctionType(params, rt):
  16019. return 'function'
  16020. case TupleType(fields):
  16021. return 'tuple'
  16022. case t if t == int:
  16023. return 'int'
  16024. case t if t == bool:
  16025. return 'bool'
  16026. case IntType():
  16027. return 'int'
  16028. case BoolType():
  16029. return 'int'
  16030. case _:
  16031. raise Exception('type_to_tag unexpected ' + repr(typ))
  16032. def arity(self, v):
  16033. match v:
  16034. case Function(name, params, body, env):
  16035. return len(params)
  16036. case ClosureTuple(args, arity):
  16037. return arity
  16038. case _:
  16039. raise Exception('Lany arity unexpected ' + repr(v))
  16040. \end{lstlisting}
  16041. \fi}
  16042. \caption{Auxiliary functions for interpreting \LangAny{}.}
  16043. \label{fig:interp-Rany-aux}
  16044. \end{figure}
  16045. \clearpage
  16046. \section{Cast Insertion: Compiling \LangDyn{} to \LangAny{}}
  16047. \label{sec:compile-r7}
  16048. The \code{cast\_insert} pass compiles from \LangDyn{} to \LangAny{}.
  16049. Figure~\ref{fig:compile-r7-Rany} shows the compilation of many of the
  16050. \LangDyn{} forms into \LangAny{}. An important invariant of this pass is that
  16051. given a subexpression $e$ in the \LangDyn{} program, the pass will produce
  16052. an expression $e'$ in \LangAny{} that has type \ANYTY{}. For example, the
  16053. first row in Figure~\ref{fig:compile-r7-Rany} shows the compilation of
  16054. the Boolean \TRUE{}, which must be injected to produce an
  16055. expression of type \ANYTY{}.
  16056. %
  16057. The second row of Figure~\ref{fig:compile-r7-Rany}, the compilation of
  16058. addition, is representative of compilation for many primitive
  16059. operations: the arguments have type \ANYTY{} and must be projected to
  16060. \INTTYPE{} before the addition can be performed.
  16061. The compilation of \key{lambda} (third row of
  16062. Figure~\ref{fig:compile-r7-Rany}) shows what happens when we need to
  16063. produce type annotations: we simply use \ANYTY{}.
  16064. %
  16065. % TODO:update the following for python, and the tests and interpreter. -Jeremy
  16066. \racket{The compilation of \code{if} and \code{eq?} demonstrate how
  16067. this pass has to account for some differences in behavior between
  16068. \LangDyn{} and \LangAny{}. The \LangDyn{} language is more
  16069. permissive than \LangAny{} regarding what kind of values can be used
  16070. in various places. For example, the condition of an \key{if} does
  16071. not have to be a Boolean. For \key{eq?}, the arguments need not be
  16072. of the same type (in that case the result is \code{\#f}).}
  16073. \begin{figure}[btp]
  16074. \centering
  16075. {\if\edition\racketEd
  16076. \begin{tabular}{|lll|} \hline
  16077. \begin{minipage}{0.27\textwidth}
  16078. \begin{lstlisting}
  16079. #t
  16080. \end{lstlisting}
  16081. \end{minipage}
  16082. &
  16083. $\Rightarrow$
  16084. &
  16085. \begin{minipage}{0.65\textwidth}
  16086. \begin{lstlisting}
  16087. (inject #t Boolean)
  16088. \end{lstlisting}
  16089. \end{minipage}
  16090. \\[2ex]\hline
  16091. \begin{minipage}{0.27\textwidth}
  16092. \begin{lstlisting}
  16093. (+ |$e_1$| |$e_2$|)
  16094. \end{lstlisting}
  16095. \end{minipage}
  16096. &
  16097. $\Rightarrow$
  16098. &
  16099. \begin{minipage}{0.65\textwidth}
  16100. \begin{lstlisting}
  16101. (inject
  16102. (+ (project |$e'_1$| Integer)
  16103. (project |$e'_2$| Integer))
  16104. Integer)
  16105. \end{lstlisting}
  16106. \end{minipage}
  16107. \\[2ex]\hline
  16108. \begin{minipage}{0.27\textwidth}
  16109. \begin{lstlisting}
  16110. (lambda (|$x_1 \ldots x_n$|) |$e$|)
  16111. \end{lstlisting}
  16112. \end{minipage}
  16113. &
  16114. $\Rightarrow$
  16115. &
  16116. \begin{minipage}{0.65\textwidth}
  16117. \begin{lstlisting}
  16118. (inject
  16119. (lambda: ([|$x_1$|:Any]|$\ldots$|[|$x_n$|:Any]):Any |$e'$|)
  16120. (Any|$\ldots$|Any -> Any))
  16121. \end{lstlisting}
  16122. \end{minipage}
  16123. \\[2ex]\hline
  16124. \begin{minipage}{0.27\textwidth}
  16125. \begin{lstlisting}
  16126. (|$e_0$| |$e_1 \ldots e_n$|)
  16127. \end{lstlisting}
  16128. \end{minipage}
  16129. &
  16130. $\Rightarrow$
  16131. &
  16132. \begin{minipage}{0.65\textwidth}
  16133. \begin{lstlisting}
  16134. ((project |$e'_0$| (Any|$\ldots$|Any -> Any)) |$e'_1 \ldots e'_n$|)
  16135. \end{lstlisting}
  16136. \end{minipage}
  16137. \\[2ex]\hline
  16138. \begin{minipage}{0.27\textwidth}
  16139. \begin{lstlisting}
  16140. (vector-ref |$e_1$| |$e_2$|)
  16141. \end{lstlisting}
  16142. \end{minipage}
  16143. &
  16144. $\Rightarrow$
  16145. &
  16146. \begin{minipage}{0.65\textwidth}
  16147. \begin{lstlisting}
  16148. (any-vector-ref |$e_1'$| |$e_2'$|)
  16149. \end{lstlisting}
  16150. \end{minipage}
  16151. \\[2ex]\hline
  16152. \begin{minipage}{0.27\textwidth}
  16153. \begin{lstlisting}
  16154. (if |$e_1$| |$e_2$| |$e_3$|)
  16155. \end{lstlisting}
  16156. \end{minipage}
  16157. &
  16158. $\Rightarrow$
  16159. &
  16160. \begin{minipage}{0.65\textwidth}
  16161. \begin{lstlisting}
  16162. (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16163. \end{lstlisting}
  16164. \end{minipage}
  16165. \\[2ex]\hline
  16166. \begin{minipage}{0.27\textwidth}
  16167. \begin{lstlisting}
  16168. (eq? |$e_1$| |$e_2$|)
  16169. \end{lstlisting}
  16170. \end{minipage}
  16171. &
  16172. $\Rightarrow$
  16173. &
  16174. \begin{minipage}{0.65\textwidth}
  16175. \begin{lstlisting}
  16176. (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16177. \end{lstlisting}
  16178. \end{minipage}
  16179. \\[2ex]\hline
  16180. \begin{minipage}{0.27\textwidth}
  16181. \begin{lstlisting}
  16182. (not |$e_1$|)
  16183. \end{lstlisting}
  16184. \end{minipage}
  16185. &
  16186. $\Rightarrow$
  16187. &
  16188. \begin{minipage}{0.65\textwidth}
  16189. \begin{lstlisting}
  16190. (if (eq? |$e'_1$| (inject #f Boolean))
  16191. (inject #t Boolean) (inject #f Boolean))
  16192. \end{lstlisting}
  16193. \end{minipage}
  16194. \\[2ex]\hline
  16195. \end{tabular}
  16196. \fi}
  16197. {\if\edition\pythonEd
  16198. \begin{tabular}{|lll|} \hline
  16199. \begin{minipage}{0.22\textwidth}
  16200. \begin{lstlisting}
  16201. True
  16202. \end{lstlisting}
  16203. \end{minipage}
  16204. &
  16205. $\Rightarrow$
  16206. &
  16207. \begin{minipage}{0.7\textwidth}
  16208. \begin{lstlisting}
  16209. Inject(True, BoolType())
  16210. \end{lstlisting}
  16211. \end{minipage}
  16212. \\[2ex]\hline
  16213. \begin{minipage}{0.22\textwidth}
  16214. \begin{lstlisting}
  16215. |$e_1$| + |$e_2$|
  16216. \end{lstlisting}
  16217. \end{minipage}
  16218. &
  16219. $\Rightarrow$
  16220. &
  16221. \begin{minipage}{0.7\textwidth}
  16222. \begin{lstlisting}
  16223. Inject(Project(|$e'_1$|, IntType())
  16224. + Project(|$e'_2$|, IntType()),
  16225. IntType())
  16226. \end{lstlisting}
  16227. \end{minipage}
  16228. \\[2ex]\hline
  16229. \begin{minipage}{0.22\textwidth}
  16230. \begin{lstlisting}
  16231. lambda |$x_1 \ldots x_n$|: |$e$|
  16232. \end{lstlisting}
  16233. \end{minipage}
  16234. &
  16235. $\Rightarrow$
  16236. &
  16237. \begin{minipage}{0.7\textwidth}
  16238. \begin{lstlisting}
  16239. Inject(Lambda([(|$x_1$|,AnyType),|$\ldots$|,(|$x_n$|,AnyType)], |$e'$|)
  16240. FunctionType([AnyType(),|$\ldots$|], AnyType()))
  16241. \end{lstlisting}
  16242. \end{minipage}
  16243. \\[2ex]\hline
  16244. \begin{minipage}{0.22\textwidth}
  16245. \begin{lstlisting}
  16246. |$e_0$|(|$e_1 \ldots e_n$|)
  16247. \end{lstlisting}
  16248. \end{minipage}
  16249. &
  16250. $\Rightarrow$
  16251. &
  16252. \begin{minipage}{0.7\textwidth}
  16253. \begin{lstlisting}
  16254. Call(Project(|$e'_0$|, FunctionType([AnyType(),|$\ldots$|],
  16255. AnyType())), |$e'_1, \ldots, e'_n$|)
  16256. \end{lstlisting}
  16257. \end{minipage}
  16258. \\[2ex]\hline
  16259. \begin{minipage}{0.22\textwidth}
  16260. \begin{lstlisting}
  16261. |$e_1$|[|$e_2$|]
  16262. \end{lstlisting}
  16263. \end{minipage}
  16264. &
  16265. $\Rightarrow$
  16266. &
  16267. \begin{minipage}{0.7\textwidth}
  16268. \begin{lstlisting}
  16269. Call(Name('any_tuple_load'),[|$e_1'$|, |$e_2'$|])
  16270. \end{lstlisting}
  16271. \end{minipage}
  16272. \\[2ex]\hline
  16273. %% \begin{minipage}{0.22\textwidth}
  16274. %% \begin{lstlisting}
  16275. %% |$e_2$| if |$e_1$| else |$e_3$|
  16276. %% \end{lstlisting}
  16277. %% \end{minipage}
  16278. %% &
  16279. %% $\Rightarrow$
  16280. %% &
  16281. %% \begin{minipage}{0.7\textwidth}
  16282. %% \begin{lstlisting}
  16283. %% (if (eq? |$e'_1$| (inject #f Boolean)) |$e'_3$| |$e'_2$|)
  16284. %% \end{lstlisting}
  16285. %% \end{minipage}
  16286. %% \\[2ex]\hline
  16287. %% \begin{minipage}{0.22\textwidth}
  16288. %% \begin{lstlisting}
  16289. %% (eq? |$e_1$| |$e_2$|)
  16290. %% \end{lstlisting}
  16291. %% \end{minipage}
  16292. %% &
  16293. %% $\Rightarrow$
  16294. %% &
  16295. %% \begin{minipage}{0.7\textwidth}
  16296. %% \begin{lstlisting}
  16297. %% (inject (eq? |$e'_1$| |$e'_2$|) Boolean)
  16298. %% \end{lstlisting}
  16299. %% \end{minipage}
  16300. %% \\[2ex]\hline
  16301. %% \begin{minipage}{0.22\textwidth}
  16302. %% \begin{lstlisting}
  16303. %% (not |$e_1$|)
  16304. %% \end{lstlisting}
  16305. %% \end{minipage}
  16306. %% &
  16307. %% $\Rightarrow$
  16308. %% &
  16309. %% \begin{minipage}{0.7\textwidth}
  16310. %% \begin{lstlisting}
  16311. %% (if (eq? |$e'_1$| (inject #f Boolean))
  16312. %% (inject #t Boolean) (inject #f Boolean))
  16313. %% \end{lstlisting}
  16314. %% \end{minipage}
  16315. %% \\[2ex]\hline
  16316. \end{tabular}
  16317. \fi}
  16318. \caption{Cast Insertion}
  16319. \label{fig:compile-r7-Rany}
  16320. \end{figure}
  16321. \section{Reveal Casts}
  16322. \label{sec:reveal-casts-Rany}
  16323. % TODO: define R'_6
  16324. In the \code{reveal\_casts} pass we recommend compiling \code{Project}
  16325. into a conditional expression that checks whether the value's tag
  16326. matches the target type; if it does, the value is converted to a value
  16327. of the target type by removing the tag; if it does not, the program
  16328. exits.
  16329. %
  16330. {\if\edition\racketEd
  16331. %
  16332. To perform these actions we need a new primitive operation,
  16333. \code{tag-of-any}, and two new forms, \code{ValueOf} and \code{Exit}.
  16334. The \code{tag-of-any} operation retrieves the type tag from a tagged
  16335. value of type \code{Any}. The \code{ValueOf} form retrieves the
  16336. underlying value from a tagged value. The \code{ValueOf} form
  16337. includes the type for the underlying value which is used by the type
  16338. checker. Finally, the \code{Exit} form ends the execution of the
  16339. program.
  16340. %
  16341. \fi}
  16342. %
  16343. {\if\edition\pythonEd
  16344. %
  16345. To perform these actions we need the \code{exit} function (from the C
  16346. standard library) and two new AST classes: \code{TagOf} and
  16347. \code{ValueOf}. The \code{exit} function ends the execution of the
  16348. program. The \code{TagOf} operation retrieves the type tag from a
  16349. tagged value of type \ANYTY{}. The \code{ValueOf} operation retrieves
  16350. the underlying value from a tagged value. The \code{ValueOf}
  16351. operation includes the type for the underlying value which is used by
  16352. the type checker.
  16353. %
  16354. \fi}
  16355. If the target type of the projection is \BOOLTY{} or \INTTY{}, then
  16356. \code{Project} can be translated as follows.
  16357. \begin{center}
  16358. \begin{minipage}{1.0\textwidth}
  16359. {\if\edition\racketEd
  16360. \begin{lstlisting}
  16361. (Project |$e$| |$\FType$|)
  16362. |$\Rightarrow$|
  16363. (Let |$\itm{tmp}$| |$e'$|
  16364. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$\itm{tmp}$|)))
  16365. (Int |$\itm{tagof}(\FType)$|)))
  16366. (ValueOf |$\itm{tmp}$| |$\FType$|)
  16367. (Exit)))
  16368. \end{lstlisting}
  16369. \fi}
  16370. {\if\edition\pythonEd
  16371. \begin{lstlisting}
  16372. Project(|$e$|, |$\FType$|)
  16373. |$\Rightarrow$|
  16374. Begin([Assign([|$\itm{tmp}$|], |$e'$|)],
  16375. IfExp(Compare(TagOf(|$\itm{tmp}$|),[Eq()],
  16376. [Constant(|$\itm{tagof}(\FType)$|)]),
  16377. ValueOf(|$\itm{tmp}$|, |$\FType$|)
  16378. Call(Name('exit'), [])))
  16379. \end{lstlisting}
  16380. \fi}
  16381. \end{minipage}
  16382. \end{center}
  16383. If the target type of the projection is a tuple or function type, then
  16384. there is a bit more work to do. For tuples, check that the length of
  16385. the tuple type matches the length of the tuple. For functions, check
  16386. that the number of parameters in the function type matches the
  16387. function's arity.
  16388. Regarding \code{Inject}, we recommend compiling it to a slightly
  16389. lower-level primitive operation named \code{make\_any}. This operation
  16390. takes a tag instead of a type.
  16391. \begin{center}
  16392. \begin{minipage}{1.0\textwidth}
  16393. {\if\edition\racketEd
  16394. \begin{lstlisting}
  16395. (Inject |$e$| |$\FType$|)
  16396. |$\Rightarrow$|
  16397. (Prim 'make-any (list |$e'$| (Int |$\itm{tagof}(\FType)$|)))
  16398. \end{lstlisting}
  16399. \fi}
  16400. {\if\edition\pythonEd
  16401. \begin{lstlisting}
  16402. Inject(|$e$|, |$\FType$|)
  16403. |$\Rightarrow$|
  16404. Call(Name('make_any'), [|$e'$|, Constant(|$\itm{tagof}(\FType)$|)])
  16405. \end{lstlisting}
  16406. \fi}
  16407. \end{minipage}
  16408. \end{center}
  16409. {\if\edition\pythonEd
  16410. %
  16411. The introduction of \code{make\_any} makes it difficult to use
  16412. bidirectional type checking because we no longer have an expected type
  16413. to use for type checking the expression $e'$. Thus, we run into
  16414. difficulty if $e'$ is a \code{Lambda} expression. We recommend
  16415. translating \code{Lambda} to a new AST class \code{AnnLambda} (for
  16416. annotated lambda) whose parameters have type annotations and that
  16417. records the return type.
  16418. %
  16419. \fi}
  16420. \racket{The type predicates (\code{boolean?}, etc.) can be translated into
  16421. uses of \code{tag-of-any} and \code{eq?} in a similar way as in the
  16422. translation of \code{Project}.}
  16423. {\if\edition\racketEd
  16424. The \code{any-vector-ref} and \code{any-vector-set!} operations
  16425. combine the projection action with the vector operation. Also, the
  16426. read and write operations allow arbitrary expressions for the index so
  16427. the type checker for \LangAny{} (Figure~\ref{fig:type-check-Rany})
  16428. cannot guarantee that the index is within bounds. Thus, we insert code
  16429. to perform bounds checking at runtime. The translation for
  16430. \code{any-vector-ref} is as follows and the other two operations are
  16431. translated in a similar way.
  16432. \begin{lstlisting}
  16433. (Prim 'any-vector-ref (list |$e_1$| |$e_2$|))
  16434. |$\Rightarrow$|
  16435. (Let |$v$| |$e'_1$|
  16436. (Let |$i$| |$e'_2$|
  16437. (If (Prim 'eq? (list (Prim 'tag-of-any (list (Var |$v$|))) (Int 2)))
  16438. (If (Prim '< (list (Var |$i$|)
  16439. (Prim 'any-vector-length (list (Var |$v$|)))))
  16440. (Prim 'any-vector-ref (list (Var |$v$|) (Var |$i$|)))
  16441. (Exit))
  16442. (Exit))))
  16443. \end{lstlisting}
  16444. \fi}
  16445. %
  16446. {\if\edition\pythonEd
  16447. %
  16448. The \code{any\_tuple\_load} operation combines the projection action
  16449. with the load operation. Also, the load operation allows arbitrary
  16450. expressions for the index so the type checker for \LangAny{}
  16451. (Figure~\ref{fig:type-check-Rany}) cannot guarantee that the index is
  16452. within bounds. Thus, we insert code to perform bounds checking at
  16453. runtime. The translation for \code{any\_tuple\_load} is as follows.
  16454. \begin{lstlisting}
  16455. Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|])
  16456. |$\Rightarrow$|
  16457. Block([Assign([|$t$|], |$e'_1$|), Assign([|$i$|], |$e'_2$|)],
  16458. IfExp(Compare(TagOf(|$t$|), [Eq()], [Constant(2)]),
  16459. IfExp(Compare(|$i$|, [Lt()], [Call(Name('any_len'), [|$t$|])]),
  16460. Call(Name('any_tuple_load'), [|$t$|, |$i$|]),
  16461. Call(Name('exit'), [])),
  16462. Call(Name('exit'), [])))
  16463. \end{lstlisting}
  16464. \fi}
  16465. {\if\edition\pythonEd
  16466. \section{Assignment Conversion}
  16467. \label{sec:convert-assignments-Lany}
  16468. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16469. \code{AnnLambda} AST classes.
  16470. \section{Closure Conversion}
  16471. \label{sec:closure-conversion-Lany}
  16472. Update this pass to handle the \code{TagOf}, \code{ValueOf}, and
  16473. \code{AnnLambda} AST classes.
  16474. \fi}
  16475. \section{Remove Complex Operands}
  16476. \label{sec:rco-Rany}
  16477. \racket{The \code{ValueOf} and \code{Exit} forms are both complex
  16478. expressions. The subexpression of \code{ValueOf} must be atomic.}
  16479. %
  16480. \python{The \code{ValueOf} and \code{TagOf} operations are both
  16481. complex expressions. Their subexpressions must be atomic.}
  16482. \section{Explicate Control and \LangCAny{}}
  16483. \label{sec:explicate-Rany}
  16484. The output of \code{explicate\_control} is the \LangCAny{} language
  16485. whose syntax is defined in Figure~\ref{fig:c5-syntax}.
  16486. %
  16487. \racket{The \code{ValueOf} form that we added to \LangAny{} remains an
  16488. expression and the \code{Exit} expression becomes a $\Tail$. Also,
  16489. note that the index argument of \code{vector-ref} and
  16490. \code{vector-set!} is an $\Atm$ instead of an integer, as in
  16491. \LangCVec{} (Figure~\ref{fig:c2-syntax}).}
  16492. %
  16493. \python{
  16494. Update the auxiliary functions \code{explicate\_tail}, \code{explicate\_effect},
  16495. and \code{explicate\_pred} as appropriately to handle the new expressions
  16496. in \LangCAny{}.
  16497. }
  16498. \newcommand{\CanyASTPython}{
  16499. \begin{array}{lcl}
  16500. \Exp &::=& \CALL{\VAR{\key{'make\_any'}}}{\LS \Atm,\Atm \RS}\\
  16501. &\MID& \key{TagOf}\LP \Atm \RP
  16502. \MID \key{ValueOf}\LP \Atm , \FType \RP \\
  16503. &\MID& \CALL{\VAR{\key{'any\_tuple\_load'}}}{\LS \Atm,\Atm \RS}\\
  16504. &\MID& \CALL{\VAR{\key{'any\_tuple\_store'}}}{\LS \Atm,\Atm,\Atm \RS}\\
  16505. &\MID& \CALL{\VAR{\key{'any\_len'}}}{\LS \Atm \RS} \\
  16506. &\MID& \CALL{\VAR{\key{'exit'}}}{\LS\RS}
  16507. \end{array}
  16508. }
  16509. \begin{figure}[tp]
  16510. \fbox{
  16511. \begin{minipage}{0.96\textwidth}
  16512. \small
  16513. {\if\edition\racketEd
  16514. \[
  16515. \begin{array}{lcl}
  16516. \Exp &::= & \ldots
  16517. \MID \BINOP{\key{'any-vector-ref}}{\Atm}{\Atm} \\
  16518. &\MID& (\key{Prim}~\key{'any-vector-set!}\,(\key{list}\,\Atm\,\Atm\,\Atm))\\
  16519. &\MID& \VALUEOF{\Exp}{\FType} \\
  16520. \Stmt &::=& \gray{ \ASSIGN{\VAR{\Var}}{\Exp}
  16521. \MID \LP\key{Collect} \,\itm{int}\RP }\\
  16522. \Tail &::= & \gray{ \RETURN{\Exp} \MID \SEQ{\Stmt}{\Tail}
  16523. \MID \GOTO{\itm{label}} } \\
  16524. &\MID& \gray{ \IFSTMT{\BINOP{\itm{cmp}}{\Atm}{\Atm}}{\GOTO{\itm{label}}}{\GOTO{\itm{label}}} }\\
  16525. &\MID& \gray{ \TAILCALL{\Atm}{\Atm\ldots} }
  16526. \MID \LP\key{Exit}\RP \\
  16527. \Def &::=& \gray{ \DEF{\itm{label}}{\LP[\Var\key{:}\Type]\ldots\RP}{\Type}{\itm{info}}{\LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP} }\\
  16528. \LangCAnyM{} & ::= & \gray{ \PROGRAMDEFS{\itm{info}}{\LP\Def\ldots\RP} }
  16529. \end{array}
  16530. \]
  16531. \fi}
  16532. {\if\edition\pythonEd
  16533. \[
  16534. \begin{array}{l}
  16535. \gray{\CifASTPython} \\ \hline
  16536. \gray{\CtupASTPython} \\ \hline
  16537. \gray{\CfunASTPython} \\ \hline
  16538. \gray{\ClambdaASTPython} \\ \hline
  16539. \CanyASTPython \\
  16540. \begin{array}{lcl}
  16541. \LangCAnyM{} & ::= & \CPROGRAMDEFS{\LS\Def\code{,}\ldots\RS}
  16542. \end{array}
  16543. \end{array}
  16544. \]
  16545. \fi}
  16546. \end{minipage}
  16547. }
  16548. \caption{The abstract syntax of \LangCAny{}, extending \LangCLam{} (Figure~\ref{fig:Clam-syntax}).}
  16549. \label{fig:c5-syntax}
  16550. \end{figure}
  16551. \section{Select Instructions}
  16552. \label{sec:select-Rany}
  16553. In the \code{select\_instructions} pass we translate the primitive
  16554. operations on the \ANYTY{} type to x86 instructions that manipulate
  16555. the 3 tag bits of the tagged value. In the following descriptions,
  16556. given an atom $e$ we use a primed variable $e'$ to refer to the result
  16557. of translating $e$ into an x86 argument.
  16558. \paragraph{\code{make\_any}}
  16559. We recommend compiling the \code{make\_any} operation as follows if
  16560. the tag is for \INTTY{} or \BOOLTY{}. The \key{salq} instruction
  16561. shifts the destination to the left by the number of bits specified its
  16562. source argument (in this case $3$, the length of the tag) and it
  16563. preserves the sign of the integer. We use the \key{orq} instruction to
  16564. combine the tag and the value to form the tagged value. \\
  16565. %
  16566. {\if\edition\racketEd
  16567. \begin{lstlisting}
  16568. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16569. |$\Rightarrow$|
  16570. movq |$e'$|, |\itm{lhs'}|
  16571. salq $3, |\itm{lhs'}|
  16572. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16573. \end{lstlisting}
  16574. \fi}
  16575. %
  16576. {\if\edition\pythonEd
  16577. \begin{lstlisting}
  16578. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16579. |$\Rightarrow$|
  16580. movq |$e'$|, |\itm{lhs'}|
  16581. salq $3, |\itm{lhs'}|
  16582. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16583. \end{lstlisting}
  16584. \fi}
  16585. %
  16586. The instruction selection for tuples and procedures is different
  16587. because their is no need to shift them to the left. The rightmost 3
  16588. bits are already zeros so we simply combine the value and the tag
  16589. using \key{orq}. \\
  16590. %
  16591. {\if\edition\racketEd
  16592. \begin{lstlisting}
  16593. (Assign |\itm{lhs}| (Prim 'make-any (list |$e$| (Int |$\itm{tag}$|))))
  16594. |$\Rightarrow$|
  16595. movq |$e'$|, |\itm{lhs'}|
  16596. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16597. \end{lstlisting}
  16598. \fi}
  16599. %
  16600. {\if\edition\pythonEd
  16601. \begin{lstlisting}
  16602. Assign([|\itm{lhs}|], Call(Name('make_any'), [|$e$|, Constant(|$\itm{tag}$|)]))
  16603. |$\Rightarrow$|
  16604. movq |$e'$|, |\itm{lhs'}|
  16605. orq $|$\itm{tag}$|, |\itm{lhs'}|
  16606. \end{lstlisting}
  16607. \fi}
  16608. \paragraph{\code{TagOf}}
  16609. Recall that the \code{TagOf} operation extracts the type tag from a
  16610. value of type \ANYTY{}. The type tag is the bottom three bits, so we
  16611. obtain the tag by taking the bitwise-and of the value with $111$ ($7$
  16612. in decimal).
  16613. %
  16614. {\if\edition\racketEd
  16615. \begin{lstlisting}
  16616. (Assign |\itm{lhs}| (Prim 'tag-of-any (list |$e$|)))
  16617. |$\Rightarrow$|
  16618. movq |$e'$|, |\itm{lhs'}|
  16619. andq $7, |\itm{lhs'}|
  16620. \end{lstlisting}
  16621. \fi}
  16622. %
  16623. {\if\edition\pythonEd
  16624. \begin{lstlisting}
  16625. Assign([|\itm{lhs}|], TagOf(|$e$|))
  16626. |$\Rightarrow$|
  16627. movq |$e'$|, |\itm{lhs'}|
  16628. andq $7, |\itm{lhs'}|
  16629. \end{lstlisting}
  16630. \fi}
  16631. \paragraph{\code{ValueOf}}
  16632. Like \code{make\_any}, the instructions for \key{ValueOf} are
  16633. different depending on whether the type $T$ is a pointer (tuple or
  16634. function) or not (integer or Boolean). The following shows the
  16635. instruction selection for integers and Booleans. We produce an
  16636. untagged value by shifting it to the right by 3 bits.
  16637. %
  16638. {\if\edition\racketEd
  16639. \begin{lstlisting}
  16640. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16641. |$\Rightarrow$|
  16642. movq |$e'$|, |\itm{lhs'}|
  16643. sarq $3, |\itm{lhs'}|
  16644. \end{lstlisting}
  16645. \fi}
  16646. %
  16647. {\if\edition\pythonEd
  16648. \begin{lstlisting}
  16649. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16650. |$\Rightarrow$|
  16651. movq |$e'$|, |\itm{lhs'}|
  16652. sarq $3, |\itm{lhs'}|
  16653. \end{lstlisting}
  16654. \fi}
  16655. %
  16656. In the case for tuples and procedures, we just need to zero-out the
  16657. rightmost 3 bits. We accomplish this by creating the bit pattern
  16658. $\ldots 0111$ ($7$ in decimal) and apply bitwise-not to obtain $\ldots
  16659. 11111000$ (-8 in decimal) which we \code{movq} into the destination
  16660. $\itm{lhs'}$. Finally, we apply \code{andq} with the tagged value to
  16661. get the desired result.
  16662. %
  16663. {\if\edition\racketEd
  16664. \begin{lstlisting}
  16665. (Assign |\itm{lhs}| (ValueOf |$e$| |$T$|))
  16666. |$\Rightarrow$|
  16667. movq $|$-8$|, |\itm{lhs'}|
  16668. andq |$e'$|, |\itm{lhs'}|
  16669. \end{lstlisting}
  16670. \fi}
  16671. %
  16672. {\if\edition\pythonEd
  16673. \begin{lstlisting}
  16674. Assign([|\itm{lhs}|], ValueOf(|$e$|, |$T$|))
  16675. |$\Rightarrow$|
  16676. movq $|$-8$|, |\itm{lhs'}|
  16677. andq |$e'$|, |\itm{lhs'}|
  16678. \end{lstlisting}
  16679. \fi}
  16680. %% \paragraph{Type Predicates} We leave it to the reader to
  16681. %% devise a sequence of instructions to implement the type predicates
  16682. %% \key{boolean?}, \key{integer?}, \key{vector?}, and \key{procedure?}.
  16683. \paragraph{\racket{Any-vector-length}\python{\code{any\_len}}}
  16684. The \racket{\code{any-vector-length}}\python{\code{any\_len}}
  16685. operation combines the effect of \code{ValueOf} with accessing the
  16686. length of a tuple from the tag stored at the zero index of the tuple.
  16687. {\if\edition\racketEd
  16688. \begin{lstlisting}
  16689. (Assign |$\itm{lhs}$| (Prim 'any-vector-length (list |$e_1$|)))
  16690. |$\Longrightarrow$|
  16691. movq $|$-8$|, %r11
  16692. andq |$e_1'$|, %r11
  16693. movq 0(%r11), %r11
  16694. andq $126, %r11
  16695. sarq $1, %r11
  16696. movq %r11, |$\itm{lhs'}$|
  16697. \end{lstlisting}
  16698. \fi}
  16699. {\if\edition\pythonEd
  16700. \begin{lstlisting}
  16701. Assign([|$\itm{lhs}$|], Call(Name('any_len'), [|$e_1$|]))
  16702. |$\Longrightarrow$|
  16703. movq $|$-8$|, %r11
  16704. andq |$e_1'$|, %r11
  16705. movq 0(%r11), %r11
  16706. andq $126, %r11
  16707. sarq $1, %r11
  16708. movq %r11, |$\itm{lhs'}$|
  16709. \end{lstlisting}
  16710. \fi}
  16711. \paragraph{\racket{Any-vector-ref}\python{\code{\code{any\_tuple\_load}}}}
  16712. This operation combines the effect of \code{ValueOf} with reading an
  16713. element of the tuple (see
  16714. Section~\ref{sec:select-instructions-gc}). However, the index may be
  16715. an arbitrary atom so instead of computing the offset at compile time,
  16716. we must generate instructions to compute the offset at runtime as
  16717. follows. Note the use of the new instruction \code{imulq}.
  16718. \begin{center}
  16719. \begin{minipage}{0.96\textwidth}
  16720. {\if\edition\racketEd
  16721. \begin{lstlisting}
  16722. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  16723. |$\Longrightarrow$|
  16724. movq |$\neg 111$|, %r11
  16725. andq |$e_1'$|, %r11
  16726. movq |$e_2'$|, %rax
  16727. addq $1, %rax
  16728. imulq $8, %rax
  16729. addq %rax, %r11
  16730. movq 0(%r11) |$\itm{lhs'}$|
  16731. \end{lstlisting}
  16732. \fi}
  16733. %
  16734. {\if\edition\pythonEd
  16735. \begin{lstlisting}
  16736. Assign([|$\itm{lhs}$|], Call(Name('any_tuple_load'), [|$e_1$|,|$e_2$|]))
  16737. |$\Longrightarrow$|
  16738. movq $|$-8$|, %r11
  16739. andq |$e_1'$|, %r11
  16740. movq |$e_2'$|, %rax
  16741. addq $1, %rax
  16742. imulq $8, %rax
  16743. addq %rax, %r11
  16744. movq 0(%r11) |$\itm{lhs'}$|
  16745. \end{lstlisting}
  16746. \fi}
  16747. \end{minipage}
  16748. \end{center}
  16749. \paragraph{\racket{Any-vector-set!}\python{\code{any\_tuple\_store}}}
  16750. The code generation for
  16751. \racket{\code{any-vector-set!}}\python{\code{any\_tuple\_store}} is
  16752. analogous to the above translation for reading from a tuple.
  16753. \section{Register Allocation for \LangAny{}}
  16754. \label{sec:register-allocation-Rany}
  16755. \index{subject}{register allocation}
  16756. There is an interesting interaction between tagged values and garbage
  16757. collection that has an impact on register allocation. A variable of
  16758. type \ANYTY{} might refer to a tuple and therefore it might be a root
  16759. that needs to be inspected and copied during garbage collection. Thus,
  16760. we need to treat variables of type \ANYTY{} in a similar way to
  16761. variables of tuple type for purposes of register allocation. In
  16762. particular,
  16763. \begin{itemize}
  16764. \item If a variable of type \ANYTY{} is live during a function call,
  16765. then it must be spilled. This can be accomplished by changing
  16766. \code{build\_interference} to mark all variables of type \ANYTY{}
  16767. that are live after a \code{callq} as interfering with all the
  16768. registers.
  16769. \item If a variable of type \ANYTY{} is spilled, it must be spilled to
  16770. the root stack instead of the normal procedure call stack.
  16771. \end{itemize}
  16772. Another concern regarding the root stack is that the garbage collector
  16773. needs to differentiate between (1) plain old pointers to tuples, (2) a
  16774. tagged value that points to a tuple, and (3) a tagged value that is
  16775. not a tuple. We enable this differentiation by choosing not to use the
  16776. tag $000$ in the $\itm{tagof}$ function. Instead, that bit pattern is
  16777. reserved for identifying plain old pointers to tuples. That way, if
  16778. one of the first three bits is set, then we have a tagged value and
  16779. inspecting the tag can differentiate between tuples ($010$) and the
  16780. other kinds of values.
  16781. %% \begin{exercise}\normalfont
  16782. %% Expand your compiler to handle \LangAny{} as discussed in the last few
  16783. %% sections. Create 5 new programs that use the \ANYTY{} type and the
  16784. %% new operations (\code{Inject}, \code{Project}, etc.). Test your
  16785. %% compiler on these new programs and all of your previously created test
  16786. %% programs.
  16787. %% \end{exercise}
  16788. \begin{exercise}\normalfont\normalsize
  16789. Expand your compiler to handle \LangDyn{} as outlined in this chapter.
  16790. Create tests for \LangDyn{} by adapting ten of your previous test programs
  16791. by removing type annotations. Add 5 more tests programs that
  16792. specifically rely on the language being dynamically typed. That is,
  16793. they should not be legal programs in a statically typed language, but
  16794. nevertheless, they should be valid \LangDyn{} programs that run to
  16795. completion without error.
  16796. \end{exercise}
  16797. \begin{figure}[p]
  16798. \begin{tikzpicture}[baseline=(current bounding box.center)]
  16799. \node (Rfun) at (0,4) {\large \LangDyn{}};
  16800. \node (Rfun-2) at (3,4) {\large \LangDyn{}};
  16801. \node (Rfun-3) at (6,4) {\large \LangDyn{}};
  16802. \node (Rfun-4) at (9,4) {\large \LangDynFunRef{}};
  16803. \node (Rfun-5) at (9,2) {\large \LangAnyFunRef{}};
  16804. \node (Rfun-6) at (12,2) {\large \LangAnyFunRef{}};
  16805. \node (Rfun-7) at (12,0) {\large \LangAnyFunRef{}};
  16806. \node (F1-2) at (9,0) {\large \LangAnyFunRef{}};
  16807. \node (F1-3) at (6,0) {\large \LangAnyFunRef{}};
  16808. \node (F1-4) at (3,0) {\large \LangAnyAlloc{}};
  16809. \node (F1-5) at (0,0) {\large \LangAnyAlloc{}};
  16810. \node (C3-2) at (3,-2) {\large \LangCAny{}};
  16811. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  16812. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  16813. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  16814. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  16815. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  16816. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  16817. \path[->,bend left=15] (Rfun) edge [above] node
  16818. {\ttfamily\footnotesize shrink} (Rfun-2);
  16819. \path[->,bend left=15] (Rfun-2) edge [above] node
  16820. {\ttfamily\footnotesize uniquify} (Rfun-3);
  16821. \path[->,bend left=15] (Rfun-3) edge [above] node
  16822. {\ttfamily\footnotesize reveal\_functions} (Rfun-4);
  16823. \path[->,bend right=15] (Rfun-4) edge [left] node
  16824. {\ttfamily\footnotesize cast\_insert} (Rfun-5);
  16825. \path[->,bend left=15] (Rfun-5) edge [above] node
  16826. {\ttfamily\footnotesize reveal\_casts} (Rfun-6);
  16827. \path[->,bend left=15] (Rfun-6) edge [left] node
  16828. {\ttfamily\footnotesize convert\_assign.} (Rfun-7);
  16829. \path[->,bend left=15] (Rfun-7) edge [below] node
  16830. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  16831. \path[->,bend right=15] (F1-2) edge [above] node
  16832. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  16833. \path[->,bend right=15] (F1-3) edge [above] node
  16834. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  16835. \path[->,bend right=15] (F1-4) edge [above] node
  16836. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  16837. \path[->,bend right=15] (F1-5) edge [right] node
  16838. {\ttfamily\footnotesize explicate\_control} (C3-2);
  16839. \path[->,bend left=15] (C3-2) edge [left] node
  16840. {\ttfamily\footnotesize select\_instr.} (x86-2);
  16841. \path[->,bend right=15] (x86-2) edge [left] node
  16842. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  16843. \path[->,bend right=15] (x86-2-1) edge [below] node
  16844. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  16845. \path[->,bend right=15] (x86-2-2) edge [left] node
  16846. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  16847. \path[->,bend left=15] (x86-3) edge [above] node
  16848. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  16849. \path[->,bend left=15] (x86-4) edge [right] node
  16850. {\ttfamily\footnotesize print\_x86} (x86-5);
  16851. \end{tikzpicture}
  16852. \caption{Diagram of the passes for \LangDyn{}, a dynamically typed language.}
  16853. \label{fig:Rdyn-passes}
  16854. \end{figure}
  16855. Figure~\ref{fig:Rdyn-passes} provides an overview of all the passes needed
  16856. for the compilation of \LangDyn{}.
  16857. % Further Reading
  16858. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16859. %% {\if\edition\pythonEd
  16860. %% \chapter{Objects}
  16861. %% \label{ch:Lobject}
  16862. %% \index{subject}{objects}
  16863. %% \index{subject}{classes}
  16864. %% \fi}
  16865. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  16866. \chapter{Gradual Typing}
  16867. \label{ch:Lgrad}
  16868. \index{subject}{gradual typing}
  16869. \if\edition\pythonEd
  16870. UNDER CONSTRUCTION
  16871. \fi
  16872. \if\edition\racketEd
  16873. This chapter studies a language, \LangGrad{}, in which the programmer
  16874. can choose between static and dynamic type checking in different parts
  16875. of a program, thereby mixing the statically typed \LangLoop{} language
  16876. with the dynamically typed \LangDyn{}. There are several approaches to
  16877. mixing static and dynamic typing, including multi-language
  16878. integration~\citep{Tobin-Hochstadt:2006fk,Matthews:2007zr} and hybrid
  16879. type checking~\citep{Flanagan:2006mn,Gronski:2006uq}. In this chapter
  16880. we focus on \emph{gradual typing}\index{subject}{gradual typing}, in which the
  16881. programmer controls the amount of static versus dynamic checking by
  16882. adding or removing type annotations on parameters and
  16883. variables~\citep{Anderson:2002kd,Siek:2006bh}.
  16884. %
  16885. The concrete syntax of \LangGrad{} is defined in
  16886. Figure~\ref{fig:Rgrad-concrete-syntax} and its abstract syntax is defined
  16887. in Figure~\ref{fig:Rgrad-syntax}. The main syntactic difference between
  16888. \LangLoop{} and \LangGrad{} is the additional \itm{param} and \itm{ret}
  16889. non-terminals that make type annotations optional. The return types
  16890. are not optional in the abstract syntax; the parser fills in
  16891. \code{Any} when the return type is not specified in the concrete
  16892. syntax.
  16893. \begin{figure}[tp]
  16894. \centering
  16895. \fbox{
  16896. \begin{minipage}{0.96\textwidth}
  16897. \small
  16898. \[
  16899. \begin{array}{lcl}
  16900. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16901. \itm{ret} &::=& \epsilon \MID \key{:} \Type \\
  16902. \Exp &::=& \gray{ \Int \MID \CREAD{} \MID \CNEG{\Exp}
  16903. \MID \CADD{\Exp}{\Exp} \MID \CSUB{\Exp}{\Exp} } \\
  16904. &\MID& \gray{ \Var \MID \CLET{\Var}{\Exp}{\Exp} }\\
  16905. &\MID& \gray{\key{\#t} \MID \key{\#f}
  16906. \MID (\key{and}\;\Exp\;\Exp)
  16907. \MID (\key{or}\;\Exp\;\Exp)
  16908. \MID (\key{not}\;\Exp) } \\
  16909. &\MID& \gray{ (\key{eq?}\;\Exp\;\Exp) \MID \CIF{\Exp}{\Exp}{\Exp} } \\
  16910. &\MID& \gray{ (\key{vector}\;\Exp\ldots) \MID
  16911. (\key{vector-ref}\;\Exp\;\Int)} \\
  16912. &\MID& \gray{(\key{vector-set!}\;\Exp\;\Int\;\Exp)\MID (\key{void})
  16913. \MID (\Exp \; \Exp\ldots) } \\
  16914. &\MID& \gray{ \LP \key{procedure-arity}~\Exp\RP }
  16915. \MID \CGLAMBDA{\LP\itm{param}\ldots\RP}{\itm{ret}}{\Exp} \\
  16916. &\MID& \gray{ \CSETBANG{\Var}{\Exp}
  16917. \MID \CBEGIN{\Exp\ldots}{\Exp}
  16918. \MID \CWHILE{\Exp}{\Exp} } \\
  16919. \Def &::=& \CGDEF{\Var}{\itm{param}\ldots}{\itm{ret}}{\Exp} \\
  16920. \LangGradM{} &::=& \gray{\Def\ldots \; \Exp}
  16921. \end{array}
  16922. \]
  16923. \end{minipage}
  16924. }
  16925. \caption{The concrete syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  16926. \label{fig:Rgrad-concrete-syntax}
  16927. \end{figure}
  16928. \begin{figure}[tp]
  16929. \centering
  16930. \fbox{
  16931. \begin{minipage}{0.96\textwidth}
  16932. \small
  16933. \[
  16934. \begin{array}{lcl}
  16935. \itm{param} &::=& \Var \MID \LS\Var \key{:} \Type\RS \\
  16936. \Exp &::=& \gray{ \INT{\Int} \VAR{\Var} \MID \LET{\Var}{\Exp}{\Exp} } \\
  16937. &\MID& \gray{ \PRIM{\itm{op}}{\Exp\ldots} }\\
  16938. &\MID& \gray{ \BOOL{\itm{bool}}
  16939. \MID \IF{\Exp}{\Exp}{\Exp} } \\
  16940. &\MID& \gray{ \VOID{} \MID \LP\key{HasType}~\Exp~\Type \RP
  16941. \MID \APPLY{\Exp}{\Exp\ldots} }\\
  16942. &\MID& \LAMBDA{\LP\itm{param}\ldots\RP}{\Type}{\Exp} \\
  16943. &\MID& \gray{ \SETBANG{\Var}{\Exp} \MID \BEGIN{\LP\Exp\ldots\RP}{\Exp} } \\
  16944. &\MID& \gray{ \WHILE{\Exp}{\Exp} } \\
  16945. \Def &::=& \FUNDEF{\Var}{\LP\itm{param}\ldots\RP}{\Type}{\code{'()}}{\Exp} \\
  16946. \LangGradM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  16947. \end{array}
  16948. \]
  16949. \end{minipage}
  16950. }
  16951. \caption{The abstract syntax of \LangGrad{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  16952. \label{fig:Rgrad-syntax}
  16953. \end{figure}
  16954. Both the type checker and the interpreter for \LangGrad{} require some
  16955. interesting changes to enable gradual typing, which we discuss in the
  16956. next two sections in the context of the \code{map} example from
  16957. Chapter~\ref{ch:Lfun}. In Figure~\ref{fig:gradual-map} we
  16958. revised the \code{map} example, omitting the type annotations from
  16959. the \code{inc} function.
  16960. \begin{figure}[btp]
  16961. % gradual_test_9.rkt
  16962. \begin{lstlisting}
  16963. (define (map [f : (Integer -> Integer)]
  16964. [v : (Vector Integer Integer)])
  16965. : (Vector Integer Integer)
  16966. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  16967. (define (inc x) (+ x 1))
  16968. (vector-ref (map inc (vector 0 41)) 1)
  16969. \end{lstlisting}
  16970. \caption{A partially-typed version of the \code{map} example.}
  16971. \label{fig:gradual-map}
  16972. \end{figure}
  16973. \section{Type Checking \LangGrad{} and \LangCast{}}
  16974. \label{sec:gradual-type-check}
  16975. The type checker for \LangGrad{} uses the \code{Any} type for missing
  16976. parameter and return types. For example, the \code{x} parameter of
  16977. \code{inc} in Figure~\ref{fig:gradual-map} is given the type
  16978. \code{Any} and the return type of \code{inc} is \code{Any}. Next
  16979. consider the \code{+} operator inside \code{inc}. It expects both
  16980. arguments to have type \code{Integer}, but its first argument \code{x}
  16981. has type \code{Any}. In a gradually typed language, such differences
  16982. are allowed so long as the types are \emph{consistent}, that is, they
  16983. are equal except in places where there is an \code{Any} type. The type
  16984. \code{Any} is consistent with every other type.
  16985. Figure~\ref{fig:consistent} defines the \code{consistent?} predicate.
  16986. \begin{figure}[tbp]
  16987. \begin{lstlisting}
  16988. (define/public (consistent? t1 t2)
  16989. (match* (t1 t2)
  16990. [('Integer 'Integer) #t]
  16991. [('Boolean 'Boolean) #t]
  16992. [('Void 'Void) #t]
  16993. [('Any t2) #t]
  16994. [(t1 'Any) #t]
  16995. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  16996. (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))]
  16997. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  16998. (and (for/and ([t1 ts1] [t2 ts2]) (consistent? t1 t2))
  16999. (consistent? rt1 rt2))]
  17000. [(other wise) #f]))
  17001. \end{lstlisting}
  17002. \caption{The consistency predicate on types.}
  17003. \label{fig:consistent}
  17004. \end{figure}
  17005. Returning to the \code{map} example of
  17006. Figure~\ref{fig:gradual-map}, the \code{inc} function has type
  17007. \code{(Any -> Any)} but parameter \code{f} of \code{map} has type
  17008. \code{(Integer -> Integer)}. The type checker for \LangGrad{} allows this
  17009. because the two types are consistent. In particular, \code{->} is
  17010. equal to \code{->} and because \code{Any} is consistent with
  17011. \code{Integer}.
  17012. Next consider a program with an error, such as applying the
  17013. \code{map} to a function that sometimes returns a Boolean, as
  17014. shown in Figure~\ref{fig:map-maybe-inc}. The type checker for
  17015. \LangGrad{} accepts this program because the type of \code{maybe-inc} is
  17016. consistent with the type of parameter \code{f} of \code{map}, that
  17017. is, \code{(Any -> Any)} is consistent with \code{(Integer ->
  17018. Integer)}. One might say that a gradual type checker is optimistic
  17019. in that it accepts programs that might execute without a runtime type
  17020. error.
  17021. %
  17022. Unfortunately, running this program with input \code{1} triggers an
  17023. error when the \code{maybe-inc} function returns \code{\#t}. \LangGrad{}
  17024. performs checking at runtime to ensure the integrity of the static
  17025. types, such as the \code{(Integer -> Integer)} annotation on parameter
  17026. \code{f} of \code{map}. This runtime checking is carried out by a
  17027. new \code{Cast} form that is inserted by the type checker. Thus, the
  17028. output of the type checker is a program in the \LangCast{} language, which
  17029. adds \code{Cast} to \LangLoop{}, as shown in
  17030. Figure~\ref{fig:Rgrad-prime-syntax}.
  17031. \begin{figure}[tp]
  17032. \centering
  17033. \fbox{
  17034. \begin{minipage}{0.96\textwidth}
  17035. \small
  17036. \[
  17037. \begin{array}{lcl}
  17038. \Exp &::=& \ldots \MID \CAST{\Exp}{\Type}{\Type} \\
  17039. \LangCastM{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  17040. \end{array}
  17041. \]
  17042. \end{minipage}
  17043. }
  17044. \caption{The abstract syntax of \LangCast{}, extending \LangLoop{} (Figure~\ref{fig:Lwhile-syntax}).}
  17045. \label{fig:Rgrad-prime-syntax}
  17046. \end{figure}
  17047. \begin{figure}[tbp]
  17048. \begin{lstlisting}
  17049. (define (map [f : (Integer -> Integer)]
  17050. [v : (Vector Integer Integer)])
  17051. : (Vector Integer Integer)
  17052. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17053. (define (inc x) (+ x 1))
  17054. (define (true) #t)
  17055. (define (maybe-inc x) (if (eq? 0 (read)) (inc x) (true)))
  17056. (vector-ref (map maybe-inc (vector 0 41)) 0)
  17057. \end{lstlisting}
  17058. \caption{A variant of the \code{map} example with an error.}
  17059. \label{fig:map-maybe-inc}
  17060. \end{figure}
  17061. Figure~\ref{fig:map-cast} shows the output of the type checker for
  17062. \code{map} and \code{maybe-inc}. The idea is that \code{Cast} is
  17063. inserted every time the type checker sees two types that are
  17064. consistent but not equal. In the \code{inc} function, \code{x} is
  17065. cast to \code{Integer} and the result of the \code{+} is cast to
  17066. \code{Any}. In the call to \code{map}, the \code{inc} argument
  17067. is cast from \code{(Any -> Any)} to \code{(Integer -> Integer)}.
  17068. \begin{figure}[btp]
  17069. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17070. (define (map [f : (Integer -> Integer)] [v : (Vector Integer Integer)])
  17071. : (Vector Integer Integer)
  17072. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17073. (define (inc [x : Any]) : Any
  17074. (cast (+ (cast x Any Integer) 1) Integer Any))
  17075. (define (true) : Any (cast #t Boolean Any))
  17076. (define (maybe-inc [x : Any]) : Any
  17077. (if (eq? 0 (read)) (inc x) (true)))
  17078. (vector-ref (map (cast maybe-inc (Any -> Any) (Integer -> Integer))
  17079. (vector 0 41)) 0)
  17080. \end{lstlisting}
  17081. \caption{Output of type checking \code{map}
  17082. and \code{maybe-inc}.}
  17083. \label{fig:map-cast}
  17084. \end{figure}
  17085. The type checker for \LangGrad{} is defined in
  17086. Figures~\ref{fig:type-check-Rgradual-1}, \ref{fig:type-check-Rgradual-2},
  17087. and \ref{fig:type-check-Rgradual-3}.
  17088. \begin{figure}[tbp]
  17089. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17090. (define type-check-gradual_class
  17091. (class type-check-Rwhile_class
  17092. (super-new)
  17093. (inherit operator-types type-predicates)
  17094. (define/override (type-check-exp env)
  17095. (lambda (e)
  17096. (define recur (type-check-exp env))
  17097. (match e
  17098. [(Prim 'vector-length (list e1))
  17099. (define-values (e1^ t) (recur e1))
  17100. (match t
  17101. [`(Vector ,ts ...)
  17102. (values (Prim 'vector-length (list e1^)) 'Integer)]
  17103. ['Any (values (Prim 'any-vector-length (list e1^)) 'Integer)])]
  17104. [(Prim 'vector-ref (list e1 e2))
  17105. (define-values (e1^ t1) (recur e1))
  17106. (define-values (e2^ t2) (recur e2))
  17107. (check-consistent? t2 'Integer e)
  17108. (match t1
  17109. [`(Vector ,ts ...)
  17110. (match e2^
  17111. [(Int i)
  17112. (unless (and (0 . <= . i) (i . < . (length ts)))
  17113. (error 'type-check "invalid index ~a in ~a" i e))
  17114. (values (Prim 'vector-ref (list e1^ (Int i))) (list-ref ts i))]
  17115. [else (define e1^^ (make-cast e1^ t1 'Any))
  17116. (define e2^^ (make-cast e2^ t2 'Integer))
  17117. (values (Prim 'any-vector-ref (list e1^^ e2^^)) 'Any)])]
  17118. ['Any
  17119. (define e2^^ (make-cast e2^ t2 'Integer))
  17120. (values (Prim 'any-vector-ref (list e1^ e2^^)) 'Any)]
  17121. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17122. [(Prim 'vector-set! (list e1 e2 e3) )
  17123. (define-values (e1^ t1) (recur e1))
  17124. (define-values (e2^ t2) (recur e2))
  17125. (define-values (e3^ t3) (recur e3))
  17126. (check-consistent? t2 'Integer e)
  17127. (match t1
  17128. [`(Vector ,ts ...)
  17129. (match e2^
  17130. [(Int i)
  17131. (unless (and (0 . <= . i) (i . < . (length ts)))
  17132. (error 'type-check "invalid index ~a in ~a" i e))
  17133. (check-consistent? (list-ref ts i) t3 e)
  17134. (define e3^^ (make-cast e3^ t3 (list-ref ts i)))
  17135. (values (Prim 'vector-set! (list e1^ (Int i) e3^^)) 'Void)]
  17136. [else
  17137. (define e1^^ (make-cast e1^ t1 'Any))
  17138. (define e2^^ (make-cast e2^ t2 'Integer))
  17139. (define e3^^ (make-cast e3^ t3 'Any))
  17140. (values (Prim 'any-vector-set! (list e1^^ e2^^ e3^^)) 'Void)])]
  17141. ['Any
  17142. (define e2^^ (make-cast e2^ t2 'Integer))
  17143. (define e3^^ (make-cast e3^ t3 'Any))
  17144. (values (Prim 'any-vector-set! (list e1^ e2^^ e3^^)) 'Void)]
  17145. [else (error 'type-check "expected vector not ~a\nin ~v" t1 e)])]
  17146. \end{lstlisting}
  17147. \caption{Type checker for the \LangGrad{} language, part 1.}
  17148. \label{fig:type-check-Rgradual-1}
  17149. \end{figure}
  17150. \begin{figure}[tbp]
  17151. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17152. [(Prim 'eq? (list e1 e2))
  17153. (define-values (e1^ t1) (recur e1))
  17154. (define-values (e2^ t2) (recur e2))
  17155. (check-consistent? t1 t2 e)
  17156. (define T (meet t1 t2))
  17157. (values (Prim 'eq? (list (make-cast e1^ t1 T) (make-cast e2^ t2 T)))
  17158. 'Boolean)]
  17159. [(Prim 'not (list e1))
  17160. (define-values (e1^ t1) (recur e1))
  17161. (match t1
  17162. ['Any
  17163. (recur (If (Prim 'eq? (list e1 (Inject (Bool #f) 'Boolean)))
  17164. (Bool #t) (Bool #f)))]
  17165. [else
  17166. (define-values (t-ret new-es^)
  17167. (type-check-op 'not (list t1) (list e1^) e))
  17168. (values (Prim 'not new-es^) t-ret)])]
  17169. [(Prim 'and (list e1 e2))
  17170. (recur (If e1 e2 (Bool #f)))]
  17171. [(Prim 'or (list e1 e2))
  17172. (define tmp (gensym 'tmp))
  17173. (recur (Let tmp e1 (If (Var tmp) (Var tmp) e2)))]
  17174. [(Prim op es)
  17175. #:when (not (set-member? explicit-prim-ops op))
  17176. (define-values (new-es ts)
  17177. (for/lists (exprs types) ([e es])
  17178. (recur e)))
  17179. (define-values (t-ret new-es^) (type-check-op op ts new-es e))
  17180. (values (Prim op new-es^) t-ret)]
  17181. [(If e1 e2 e3)
  17182. (define-values (e1^ T1) (recur e1))
  17183. (define-values (e2^ T2) (recur e2))
  17184. (define-values (e3^ T3) (recur e3))
  17185. (check-consistent? T2 T3 e)
  17186. (match T1
  17187. ['Boolean
  17188. (define Tif (join T2 T3))
  17189. (values (If e1^ (make-cast e2^ T2 Tif)
  17190. (make-cast e3^ T3 Tif)) Tif)]
  17191. ['Any
  17192. (define Tif (meet T2 T3))
  17193. (values (If (Prim 'eq? (list e1^ (Inject (Bool #f) 'Boolean)))
  17194. (make-cast e3^ T3 Tif) (make-cast e2^ T2 Tif))
  17195. Tif)]
  17196. [else (error 'type-check "expected Boolean not ~a\nin ~v" T1 e)])]
  17197. [(HasType e1 T)
  17198. (define-values (e1^ T1) (recur e1))
  17199. (check-consistent? T1 T)
  17200. (values (make-cast e1^ T1 T) T)]
  17201. [(SetBang x e1)
  17202. (define-values (e1^ T1) (recur e1))
  17203. (define varT (dict-ref env x))
  17204. (check-consistent? T1 varT e)
  17205. (values (SetBang x (make-cast e1^ T1 varT)) 'Void)]
  17206. [(WhileLoop e1 e2)
  17207. (define-values (e1^ T1) (recur e1))
  17208. (check-consistent? T1 'Boolean e)
  17209. (define-values (e2^ T2) ((type-check-exp env) e2))
  17210. (values (WhileLoop (make-cast e1^ T1 'Boolean) e2^) 'Void)]
  17211. \end{lstlisting}
  17212. \caption{Type checker for the \LangGrad{} language, part 2.}
  17213. \label{fig:type-check-Rgradual-2}
  17214. \end{figure}
  17215. \begin{figure}[tbp]
  17216. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17217. [(Apply e1 e2s)
  17218. (define-values (e1^ T1) (recur e1))
  17219. (define-values (e2s^ T2s) (for/lists (e* ty*) ([e2 e2s]) (recur e2)))
  17220. (match T1
  17221. [`(,T1ps ... -> ,T1rt)
  17222. (for ([T2 T2s] [Tp T1ps])
  17223. (check-consistent? T2 Tp e))
  17224. (define e2s^^ (for/list ([e2 e2s^] [src T2s] [tgt T1ps])
  17225. (make-cast e2 src tgt)))
  17226. (values (Apply e1^ e2s^^) T1rt)]
  17227. [`Any
  17228. (define e1^^ (make-cast e1^ 'Any
  17229. `(,@(for/list ([e e2s]) 'Any) -> Any)))
  17230. (define e2s^^ (for/list ([e2 e2s^] [src T2s])
  17231. (make-cast e2 src 'Any)))
  17232. (values (Apply e1^^ e2s^^) 'Any)]
  17233. [else (error 'type-check "expected function not ~a\nin ~v" T1 e)])]
  17234. [(Lambda params Tr e1)
  17235. (define-values (xs Ts) (for/lists (l1 l2) ([p params])
  17236. (match p
  17237. [`[,x : ,T] (values x T)]
  17238. [(? symbol? x) (values x 'Any)])))
  17239. (define-values (e1^ T1)
  17240. ((type-check-exp (append (map cons xs Ts) env)) e1))
  17241. (check-consistent? Tr T1 e)
  17242. (values (Lambda (for/list ([x xs] [T Ts]) `[,x : ,T]) Tr
  17243. (make-cast e1^ T1 Tr)) `(,@Ts -> ,Tr))]
  17244. [else ((super type-check-exp env) e)]
  17245. )))
  17246. \end{lstlisting}
  17247. \caption{Type checker for the \LangGrad{} language, part 3.}
  17248. \label{fig:type-check-Rgradual-3}
  17249. \end{figure}
  17250. \begin{figure}[tbp]
  17251. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  17252. (define/public (join t1 t2)
  17253. (match* (t1 t2)
  17254. [('Integer 'Integer) 'Integer]
  17255. [('Boolean 'Boolean) 'Boolean]
  17256. [('Void 'Void) 'Void]
  17257. [('Any t2) t2]
  17258. [(t1 'Any) t1]
  17259. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17260. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2)))]
  17261. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17262. `(,@(for/list ([t1 ts1] [t2 ts2]) (join t1 t2))
  17263. -> ,(join rt1 rt2))]))
  17264. (define/public (meet t1 t2)
  17265. (match* (t1 t2)
  17266. [('Integer 'Integer) 'Integer]
  17267. [('Boolean 'Boolean) 'Boolean]
  17268. [('Void 'Void) 'Void]
  17269. [('Any t2) 'Any]
  17270. [(t1 'Any) 'Any]
  17271. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17272. `(Vector ,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2)))]
  17273. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17274. `(,@(for/list ([t1 ts1] [t2 ts2]) (meet t1 t2))
  17275. -> ,(meet rt1 rt2))]))
  17276. (define/public (make-cast e src tgt)
  17277. (cond [(equal? src tgt) e] [else (Cast e src tgt)]))
  17278. (define/public (check-consistent? t1 t2 e)
  17279. (unless (consistent? t1 t2)
  17280. (error 'type-check "~a is inconsistent with ~a\nin ~v" t1 t2 e)))
  17281. (define/override (type-check-op op arg-types args e)
  17282. (match (dict-ref (operator-types) op)
  17283. [`(,param-types . ,return-type)
  17284. (for ([at arg-types] [pt param-types])
  17285. (check-consistent? at pt e))
  17286. (values return-type
  17287. (for/list ([e args] [s arg-types] [t param-types])
  17288. (make-cast e s t)))]
  17289. [else (error 'type-check-op "unrecognized ~a" op)]))
  17290. (define explicit-prim-ops
  17291. (set-union
  17292. (type-predicates)
  17293. (set 'procedure-arity 'eq?
  17294. 'vector 'vector-length 'vector-ref 'vector-set!
  17295. 'any-vector-length 'any-vector-ref 'any-vector-set!)))
  17296. (define/override (fun-def-type d)
  17297. (match d
  17298. [(Def f params rt info body)
  17299. (define ps
  17300. (for/list ([p params])
  17301. (match p
  17302. [`[,x : ,T] T]
  17303. [(? symbol?) 'Any]
  17304. [else (error 'fun-def-type "unmatched parameter ~a" p)])))
  17305. `(,@ps -> ,rt)]
  17306. [else (error 'fun-def-type "ill-formed function definition in ~a" d)]))
  17307. \end{lstlisting}
  17308. \caption{Auxiliary functions for type checking \LangGrad{}.}
  17309. \label{fig:type-check-Rgradual-aux}
  17310. \end{figure}
  17311. \clearpage
  17312. \section{Interpreting \LangCast{}}
  17313. \label{sec:interp-casts}
  17314. The runtime behavior of first-order casts is straightforward, that is,
  17315. casts involving simple types such as \code{Integer} and
  17316. \code{Boolean}. For example, a cast from \code{Integer} to \code{Any}
  17317. can be accomplished with the \code{Inject} operator of \LangAny{}, which
  17318. puts the integer into a tagged value
  17319. (Figure~\ref{fig:interp-Rany}). Similarly, a cast from \code{Any} to
  17320. \code{Integer} is accomplished with the \code{Project} operator, that
  17321. is, by checking the value's tag and either retrieving the underlying
  17322. integer or signaling an error if it the tag is not the one for
  17323. integers (Figure~\ref{fig:interp-Rany-aux}).
  17324. %
  17325. Things get more interesting for higher-order casts, that is, casts
  17326. involving function or vector types.
  17327. Consider the cast of the function \code{maybe-inc} from \code{(Any ->
  17328. Any)} to \code{(Integer -> Integer)}. When a function flows through
  17329. this cast at runtime, we can't know in general whether the function
  17330. will always return an integer.\footnote{Predicting the return value of
  17331. a function is equivalent to the halting problem, which is
  17332. undecidable.} The \LangCast{} interpreter therefore delays the checking
  17333. of the cast until the function is applied. This is accomplished by
  17334. wrapping \code{maybe-inc} in a new function that casts its parameter
  17335. from \code{Integer} to \code{Any}, applies \code{maybe-inc}, and then
  17336. casts the return value from \code{Any} to \code{Integer}.
  17337. Turning our attention to casts involving vector types, we consider the
  17338. example in Figure~\ref{fig:map-bang} that defines a
  17339. partially-typed version of \code{map} whose parameter \code{v} has
  17340. type \code{(Vector Any Any)} and that updates \code{v} in place
  17341. instead of returning a new vector. So we name this function
  17342. \code{map!}. We apply \code{map!} to a vector of integers, so
  17343. the type checker inserts a cast from \code{(Vector Integer Integer)}
  17344. to \code{(Vector Any Any)}. A naive way for the \LangCast{} interpreter to
  17345. cast between vector types would be a build a new vector whose elements
  17346. are the result of casting each of the original elements to the
  17347. appropriate target type. However, this approach is only valid for
  17348. immutable vectors; and our vectors are mutable. In the example of
  17349. Figure~\ref{fig:map-bang}, if the cast created a new vector, then
  17350. the updates inside of \code{map!} would happen to the new vector
  17351. and not the original one.
  17352. \begin{figure}[tbp]
  17353. % gradual_test_11.rkt
  17354. \begin{lstlisting}
  17355. (define (map! [f : (Any -> Any)]
  17356. [v : (Vector Any Any)]) : Void
  17357. (begin
  17358. (vector-set! v 0 (f (vector-ref v 0)))
  17359. (vector-set! v 1 (f (vector-ref v 1)))))
  17360. (define (inc x) (+ x 1))
  17361. (let ([v (vector 0 41)])
  17362. (begin (map! inc v) (vector-ref v 1)))
  17363. \end{lstlisting}
  17364. \caption{An example involving casts on vectors.}
  17365. \label{fig:map-bang}
  17366. \end{figure}
  17367. Instead the interpreter needs to create a new kind of value, a
  17368. \emph{vector proxy}, that intercepts every vector operation. On a
  17369. read, the proxy reads from the underlying vector and then applies a
  17370. cast to the resulting value. On a write, the proxy casts the argument
  17371. value and then performs the write to the underlying vector. For the
  17372. first \code{(vector-ref v 0)} in \code{map!}, the proxy casts
  17373. \code{0} from \code{Integer} to \code{Any}. For the first
  17374. \code{vector-set!}, the proxy casts a tagged \code{1} from \code{Any}
  17375. to \code{Integer}.
  17376. The final category of cast that we need to consider are casts between
  17377. the \code{Any} type and either a function or a vector
  17378. type. Figure~\ref{fig:map-any} shows a variant of \code{map!}
  17379. in which parameter \code{v} does not have a type annotation, so it is
  17380. given type \code{Any}. In the call to \code{map!}, the vector has
  17381. type \code{(Vector Integer Integer)} so the type checker inserts a
  17382. cast from \code{(Vector Integer Integer)} to \code{Any}. A first
  17383. thought is to use \code{Inject}, but that doesn't work because
  17384. \code{(Vector Integer Integer)} is not a flat type. Instead, we must
  17385. first cast to \code{(Vector Any Any)} (which is flat) and then inject
  17386. to \code{Any}.
  17387. \begin{figure}[tbp]
  17388. \begin{lstlisting}
  17389. (define (map! [f : (Any -> Any)] v) : 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{Casting a vector to \code{Any}.}
  17398. \label{fig:map-any}
  17399. \end{figure}
  17400. The \LangCast{} interpreter uses an auxiliary function named
  17401. \code{apply-cast} to cast a value from a source type to a target type,
  17402. shown in Figure~\ref{fig:apply-cast}. You'll find that it handles all
  17403. of the kinds of casts that we've discussed in this section.
  17404. \begin{figure}[tbp]
  17405. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17406. (define/public (apply-cast v s t)
  17407. (match* (s t)
  17408. [(t1 t2) #:when (equal? t1 t2) v]
  17409. [('Any t2)
  17410. (match t2
  17411. [`(,ts ... -> ,rt)
  17412. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17413. (define v^ (apply-project v any->any))
  17414. (apply-cast v^ any->any `(,@ts -> ,rt))]
  17415. [`(Vector ,ts ...)
  17416. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17417. (define v^ (apply-project v vec-any))
  17418. (apply-cast v^ vec-any `(Vector ,@ts))]
  17419. [else (apply-project v t2)])]
  17420. [(t1 'Any)
  17421. (match t1
  17422. [`(,ts ... -> ,rt)
  17423. (define any->any `(,@(for/list ([t ts]) 'Any) -> Any))
  17424. (define v^ (apply-cast v `(,@ts -> ,rt) any->any))
  17425. (apply-inject v^ (any-tag any->any))]
  17426. [`(Vector ,ts ...)
  17427. (define vec-any `(Vector ,@(for/list ([t ts]) 'Any)))
  17428. (define v^ (apply-cast v `(Vector ,@ts) vec-any))
  17429. (apply-inject v^ (any-tag vec-any))]
  17430. [else (apply-inject v (any-tag t1))])]
  17431. [(`(Vector ,ts1 ...) `(Vector ,ts2 ...))
  17432. (define x (gensym 'x))
  17433. (define cast-reads (for/list ([t1 ts1] [t2 ts2])
  17434. `(function (,x) ,(Cast (Var x) t1 t2) ())))
  17435. (define cast-writes
  17436. (for/list ([t1 ts1] [t2 ts2])
  17437. `(function (,x) ,(Cast (Var x) t2 t1) ())))
  17438. `(vector-proxy ,(vector v (apply vector cast-reads)
  17439. (apply vector cast-writes)))]
  17440. [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2))
  17441. (define xs (for/list ([t2 ts2]) (gensym 'x)))
  17442. `(function ,xs ,(Cast
  17443. (Apply (Value v)
  17444. (for/list ([x xs][t1 ts1][t2 ts2])
  17445. (Cast (Var x) t2 t1)))
  17446. rt1 rt2) ())]
  17447. ))
  17448. \end{lstlisting}
  17449. \caption{The \code{apply-cast} auxiliary method.}
  17450. \label{fig:apply-cast}
  17451. \end{figure}
  17452. The interpreter for \LangCast{} is defined in
  17453. Figure~\ref{fig:interp-Rcast}, with the case for \code{Cast}
  17454. dispatching to \code{apply-cast}. To handle the addition of vector
  17455. proxies, we update the vector primitives in \code{interp-op} using the
  17456. functions in Figure~\ref{fig:guarded-vector}.
  17457. \begin{figure}[tbp]
  17458. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17459. (define interp-Rcast_class
  17460. (class interp-Rwhile_class
  17461. (super-new)
  17462. (inherit apply-fun apply-inject apply-project)
  17463. (define/override (interp-op op)
  17464. (match op
  17465. ['vector-length guarded-vector-length]
  17466. ['vector-ref guarded-vector-ref]
  17467. ['vector-set! guarded-vector-set!]
  17468. ['any-vector-ref (lambda (v i)
  17469. (match v [`(tagged ,v^ ,tg)
  17470. (guarded-vector-ref v^ i)]))]
  17471. ['any-vector-set! (lambda (v i a)
  17472. (match v [`(tagged ,v^ ,tg)
  17473. (guarded-vector-set! v^ i a)]))]
  17474. ['any-vector-length (lambda (v)
  17475. (match v [`(tagged ,v^ ,tg)
  17476. (guarded-vector-length v^)]))]
  17477. [else (super interp-op op)]
  17478. ))
  17479. (define/override ((interp-exp env) e)
  17480. (define (recur e) ((interp-exp env) e))
  17481. (match e
  17482. [(Value v) v]
  17483. [(Cast e src tgt) (apply-cast (recur e) src tgt)]
  17484. [else ((super interp-exp env) e)]))
  17485. ))
  17486. (define (interp-Rcast p)
  17487. (send (new interp-Rcast_class) interp-program p))
  17488. \end{lstlisting}
  17489. \caption{The interpreter for \LangCast{}.}
  17490. \label{fig:interp-Rcast}
  17491. \end{figure}
  17492. \begin{figure}[tbp]
  17493. \begin{lstlisting}[basicstyle=\ttfamily\footnotesize]
  17494. (define (guarded-vector-ref vec i)
  17495. (match vec
  17496. [`(vector-proxy ,proxy)
  17497. (define val (guarded-vector-ref (vector-ref proxy 0) i))
  17498. (define rd (vector-ref (vector-ref proxy 1) i))
  17499. (apply-fun rd (list val) 'guarded-vector-ref)]
  17500. [else (vector-ref vec i)]))
  17501. (define (guarded-vector-set! vec i arg)
  17502. (match vec
  17503. [`(vector-proxy ,proxy)
  17504. (define wr (vector-ref (vector-ref proxy 2) i))
  17505. (define arg^ (apply-fun wr (list arg) 'guarded-vector-set!))
  17506. (guarded-vector-set! (vector-ref proxy 0) i arg^)]
  17507. [else (vector-set! vec i arg)]))
  17508. (define (guarded-vector-length vec)
  17509. (match vec
  17510. [`(vector-proxy ,proxy)
  17511. (guarded-vector-length (vector-ref proxy 0))]
  17512. [else (vector-length vec)]))
  17513. \end{lstlisting}
  17514. \caption{The guarded-vector auxiliary functions.}
  17515. \label{fig:guarded-vector}
  17516. \end{figure}
  17517. \section{Lower Casts}
  17518. \label{sec:lower-casts}
  17519. The next step in the journey towards x86 is the \code{lower-casts}
  17520. pass that translates the casts in \LangCast{} to the lower-level
  17521. \code{Inject} and \code{Project} operators and a new operator for
  17522. creating vector proxies, extending the \LangLoop{} language to create
  17523. \LangProxy{}. We recommend creating an auxiliary function named
  17524. \code{lower-cast} that takes an expression (in \LangCast{}), a source type,
  17525. and a target type, and translates it to expression in \LangProxy{} that has
  17526. the same behavior as casting the expression from the source to the
  17527. target type in the interpreter.
  17528. The \code{lower-cast} function can follow a code structure similar to
  17529. the \code{apply-cast} function (Figure~\ref{fig:apply-cast}) used in
  17530. the interpreter for \LangCast{} because it must handle the same cases as
  17531. \code{apply-cast} and it needs to mimic the behavior of
  17532. \code{apply-cast}. The most interesting cases are those concerning the
  17533. casts between two vector types and between two function types.
  17534. As mentioned in Section~\ref{sec:interp-casts}, a cast from one vector
  17535. type to another vector type is accomplished by creating a proxy that
  17536. intercepts the operations on the underlying vector. Here we make the
  17537. creation of the proxy explicit with the \code{vector-proxy} primitive
  17538. operation. It takes three arguments, the first is an expression for
  17539. the vector, the second is a vector of functions for casting an element
  17540. that is being read from the vector, and the third is a vector of
  17541. functions for casting an element that is being written to the vector.
  17542. You can create the functions using \code{Lambda}. Also, as we shall
  17543. see in the next section, we need to differentiate these vectors from
  17544. the user-created ones, so we recommend using a new primitive operator
  17545. named \code{raw-vector} instead of \code{vector} to create these
  17546. vectors of functions. Figure~\ref{fig:map-bang-lower-cast} shows
  17547. the output of \code{lower-casts} on the example in
  17548. Figure~\ref{fig:map-bang} that involved casting a vector of
  17549. integers to a vector of \code{Any}.
  17550. \begin{figure}[tbp]
  17551. \begin{lstlisting}
  17552. (define (map! [f : (Any -> Any)] [v : (Vector Any Any)]) : Void
  17553. (begin
  17554. (vector-set! v 0 (f (vector-ref v 0)))
  17555. (vector-set! v 1 (f (vector-ref v 1)))))
  17556. (define (inc [x : Any]) : Any
  17557. (inject (+ (project x Integer) 1) Integer))
  17558. (let ([v (vector 0 41)])
  17559. (begin
  17560. (map! inc (vector-proxy v
  17561. (raw-vector (lambda: ([x9 : Integer]) : Any
  17562. (inject x9 Integer))
  17563. (lambda: ([x9 : Integer]) : Any
  17564. (inject x9 Integer)))
  17565. (raw-vector (lambda: ([x9 : Any]) : Integer
  17566. (project x9 Integer))
  17567. (lambda: ([x9 : Any]) : Integer
  17568. (project x9 Integer)))))
  17569. (vector-ref v 1)))
  17570. \end{lstlisting}
  17571. \caption{Output of \code{lower-casts} on the example in
  17572. Figure~\ref{fig:map-bang}.}
  17573. \label{fig:map-bang-lower-cast}
  17574. \end{figure}
  17575. A cast from one function type to another function type is accomplished
  17576. by generating a \code{Lambda} whose parameter and return types match
  17577. the target function type. The body of the \code{Lambda} should cast
  17578. the parameters from the target type to the source type (yes,
  17579. backwards! functions are contravariant\index{subject}{contravariant} in the
  17580. parameters), then call the underlying function, and finally cast the
  17581. result from the source return type to the target return type.
  17582. Figure~\ref{fig:map-lower-cast} shows the output of the
  17583. \code{lower-casts} pass on the \code{map} example in
  17584. Figure~\ref{fig:gradual-map}. Note that the \code{inc} argument
  17585. in the call to \code{map} is wrapped in a \code{lambda}.
  17586. \begin{figure}[tbp]
  17587. \begin{lstlisting}
  17588. (define (map [f : (Integer -> Integer)]
  17589. [v : (Vector Integer Integer)])
  17590. : (Vector Integer Integer)
  17591. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17592. (define (inc [x : Any]) : Any
  17593. (inject (+ (project x Integer) 1) Integer))
  17594. (vector-ref (map (lambda: ([x9 : Integer]) : Integer
  17595. (project (inc (inject x9 Integer)) Integer))
  17596. (vector 0 41)) 1)
  17597. \end{lstlisting}
  17598. \caption{Output of \code{lower-casts} on the example in
  17599. Figure~\ref{fig:gradual-map}.}
  17600. \label{fig:map-lower-cast}
  17601. \end{figure}
  17602. \section{Differentiate Proxies}
  17603. \label{sec:differentiate-proxies}
  17604. So far the job of differentiating vectors and vector proxies has been
  17605. the job of the interpreter. For example, the interpreter for \LangCast{}
  17606. implements \code{vector-ref} using the \code{guarded-vector-ref}
  17607. function in Figure~\ref{fig:guarded-vector}. In the
  17608. \code{differentiate-proxies} pass we shift this responsibility to the
  17609. generated code.
  17610. We begin by designing the output language $R^p_8$. In
  17611. \LangGrad{} we used the type \code{Vector} for both real vectors and vector
  17612. proxies. In $R^p_8$ we return the \code{Vector} type to
  17613. its original meaning, as the type of real vectors, and we introduce a
  17614. new type, \code{PVector}, whose values can be either real vectors or
  17615. vector proxies. This new type comes with a suite of new primitive
  17616. operations for creating and using values of type \code{PVector}. We
  17617. don't need to introduce a new type to represent vector proxies. A
  17618. proxy is represented by a vector containing three things: 1) the
  17619. underlying vector, 2) a vector of functions for casting elements that
  17620. are read from the vector, and 3) a vector of functions for casting
  17621. values to be written to the vector. So we define the following
  17622. abbreviation for the type of a vector proxy:
  17623. \[
  17624. \itm{Proxy} (T\ldots \Rightarrow T'\ldots)
  17625. = (\ttm{Vector}~(\ttm{PVector}~ T\ldots) ~R~ W)
  17626. \to (\key{PVector}~ T' \ldots)
  17627. \]
  17628. where $R = (\ttm{Vector}~(T\to T') \ldots)$ and
  17629. $W = (\ttm{Vector}~(T'\to T) \ldots)$.
  17630. %
  17631. Next we describe each of the new primitive operations.
  17632. \begin{description}
  17633. \item[\code{inject-vector} : (\key{Vector} $T \ldots$) $\to$
  17634. (\key{PVector} $T \ldots$)]\ \\
  17635. %
  17636. This operation brands a vector as a value of the \code{PVector} type.
  17637. \item[\code{inject-proxy} : $\itm{Proxy}(T\ldots \Rightarrow T'\ldots)$
  17638. $\to$ (\key{PVector} $T' \ldots$)]\ \\
  17639. %
  17640. This operation brands a vector proxy as value of the \code{PVector} type.
  17641. \item[\code{proxy?} : (\key{PVector} $T \ldots$) $\to$
  17642. \code{Boolean}] \ \\
  17643. %
  17644. returns true if the value is a vector proxy and false if it is a
  17645. real vector.
  17646. \item[\code{project-vector} : (\key{PVector} $T \ldots$) $\to$
  17647. (\key{Vector} $T \ldots$)]\ \\
  17648. %
  17649. Assuming that the input is a vector (and not a proxy), this
  17650. operation returns the vector.
  17651. \item[\code{proxy-vector-length} : (\key{PVector} $T \ldots$)
  17652. $\to$ \code{Boolean}]\ \\
  17653. %
  17654. Given a vector proxy, this operation returns the length of the
  17655. underlying vector.
  17656. \item[\code{proxy-vector-ref} : (\key{PVector} $T \ldots$)
  17657. $\to$ ($i$ : \code{Integer}) $\to$ $T_i$]\ \\
  17658. %
  17659. Given a vector proxy, this operation returns the $i$th element of
  17660. the underlying vector.
  17661. \item[\code{proxy-vector-set!} : (\key{PVector} $T \ldots$) $\to$ ($i$
  17662. : \code{Integer}) $\to$ $T_i$ $\to$ \key{Void}]\ \\ Given a vector
  17663. proxy, this operation writes a value to the $i$th element of the
  17664. underlying vector.
  17665. \end{description}
  17666. Now to discuss the translation that differentiates vectors from
  17667. proxies. First, every type annotation in the program must be
  17668. translated (recursively) to replace \code{Vector} with \code{PVector}.
  17669. Next, we must insert uses of \code{PVector} operations in the
  17670. appropriate places. For example, we wrap every vector creation with an
  17671. \code{inject-vector}.
  17672. \begin{lstlisting}
  17673. (vector |$e_1 \ldots e_n$|)
  17674. |$\Rightarrow$|
  17675. (inject-vector (vector |$e'_1 \ldots e'_n$|))
  17676. \end{lstlisting}
  17677. The \code{raw-vector} operator that we introduced in the previous
  17678. section does not get injected.
  17679. \begin{lstlisting}
  17680. (raw-vector |$e_1 \ldots e_n$|)
  17681. |$\Rightarrow$|
  17682. (vector |$e'_1 \ldots e'_n$|)
  17683. \end{lstlisting}
  17684. The \code{vector-proxy} primitive translates as follows.
  17685. \begin{lstlisting}
  17686. (vector-proxy |$e_1~e_2~e_3$|)
  17687. |$\Rightarrow$|
  17688. (inject-proxy (vector |$e'_1~e'_2~e'_3$|))
  17689. \end{lstlisting}
  17690. We translate the vector operations into conditional expressions that
  17691. check whether the value is a proxy and then dispatch to either the
  17692. appropriate proxy vector operation or the regular vector operation.
  17693. For example, the following is the translation for \code{vector-ref}.
  17694. \begin{lstlisting}
  17695. (vector-ref |$e_1$| |$i$|)
  17696. |$\Rightarrow$|
  17697. (let ([|$v~e_1$|])
  17698. (if (proxy? |$v$|)
  17699. (proxy-vector-ref |$v$| |$i$|)
  17700. (vector-ref (project-vector |$v$|) |$i$|)
  17701. \end{lstlisting}
  17702. Note in the case of a real vector, we must apply \code{project-vector}
  17703. before the \code{vector-ref}.
  17704. \section{Reveal Casts}
  17705. \label{sec:reveal-casts-gradual}
  17706. Recall that the \code{reveal-casts} pass
  17707. (Section~\ref{sec:reveal-casts-Rany}) is responsible for lowering
  17708. \code{Inject} and \code{Project} into lower-level operations. In
  17709. particular, \code{Project} turns into a conditional expression that
  17710. inspects the tag and retrieves the underlying value. Here we need to
  17711. augment the translation of \code{Project} to handle the situation when
  17712. the target type is \code{PVector}. Instead of using
  17713. \code{vector-length} we need to use \code{proxy-vector-length}.
  17714. \begin{lstlisting}
  17715. (project |$e$| (PVector Any|$_1$| |$\ldots$| Any|$_n$|))
  17716. |$\Rightarrow$|
  17717. (let |$\itm{tmp}$| |$e'$|
  17718. (if (eq? (tag-of-any |$\itm{tmp}$| 2))
  17719. (let |$\itm{tup}$| (value-of |$\itm{tmp}$| (PVector Any |$\ldots$| Any))
  17720. (if (eq? (proxy-vector-length |$\itm{tup}$|) |$n$|) |$\itm{tup}$| (exit)))
  17721. (exit)))
  17722. \end{lstlisting}
  17723. \section{Closure Conversion}
  17724. \label{sec:closure-conversion-gradual}
  17725. The closure conversion pass only requires one minor adjustment. The
  17726. auxiliary function that translates type annotations needs to be
  17727. updated to handle the \code{PVector} type.
  17728. \section{Explicate Control}
  17729. \label{sec:explicate-control-gradual}
  17730. Update the \code{explicate\_control} pass to handle the new primitive
  17731. operations on the \code{PVector} type.
  17732. \section{Select Instructions}
  17733. \label{sec:select-instructions-gradual}
  17734. Recall that the \code{select\_instructions} pass is responsible for
  17735. lowering the primitive operations into x86 instructions. So we need
  17736. to translate the new \code{PVector} operations to x86. To do so, the
  17737. first question we need to answer is how will we differentiate the two
  17738. kinds of values (vectors and proxies) that can inhabit \code{PVector}.
  17739. We need just one bit to accomplish this, and use the bit in position
  17740. $57$ of the 64-bit tag at the front of every vector (see
  17741. Figure~\ref{fig:tuple-rep}). So far, this bit has been set to $0$, so
  17742. for \code{inject-vector} we leave it that way.
  17743. \begin{lstlisting}
  17744. (Assign |$\itm{lhs}$| (Prim 'inject-vector (list |$e_1$|)))
  17745. |$\Rightarrow$|
  17746. movq |$e'_1$|, |$\itm{lhs'}$|
  17747. \end{lstlisting}
  17748. On the other hand, \code{inject-proxy} sets bit $57$ to $1$.
  17749. \begin{lstlisting}
  17750. (Assign |$\itm{lhs}$| (Prim 'inject-proxy (list |$e_1$|)))
  17751. |$\Rightarrow$|
  17752. movq |$e'_1$|, %r11
  17753. movq |$(1 << 57)$|, %rax
  17754. orq 0(%r11), %rax
  17755. movq %rax, 0(%r11)
  17756. movq %r11, |$\itm{lhs'}$|
  17757. \end{lstlisting}
  17758. The \code{proxy?} operation consumes the information so carefully
  17759. stashed away by \code{inject-vector} and \code{inject-proxy}. It
  17760. isolates the $57$th bit to tell whether the value is a real vector or
  17761. a proxy.
  17762. \begin{lstlisting}
  17763. (Assign |$\itm{lhs}$| (Prim 'proxy? (list e)))
  17764. |$\Rightarrow$|
  17765. movq |$e_1'$|, %r11
  17766. movq 0(%r11), %rax
  17767. sarq $57, %rax
  17768. andq $1, %rax
  17769. movq %rax, |$\itm{lhs'}$|
  17770. \end{lstlisting}
  17771. The \code{project-vector} operation is straightforward to translate,
  17772. so we leave it up to the reader.
  17773. Regarding the \code{proxy-vector} operations, the runtime provides
  17774. procedures that implement them (they are recursive functions!) so
  17775. here we simply need to translate these vector operations into the
  17776. appropriate function call. For example, here is the translation for
  17777. \code{proxy-vector-ref}.
  17778. \begin{lstlisting}
  17779. (Assign |$\itm{lhs}$| (Prim 'proxy-vector-ref (list |$e_1$| |$e_2$|)))
  17780. |$\Rightarrow$|
  17781. movq |$e_1'$|, %rdi
  17782. movq |$e_2'$|, %rsi
  17783. callq proxy_vector_ref
  17784. movq %rax, |$\itm{lhs'}$|
  17785. \end{lstlisting}
  17786. We have another batch of vector operations to deal with, those for the
  17787. \code{Any} type. Recall that the type checker for \LangGrad{} generates an
  17788. \code{any-vector-ref} when there is a \code{vector-ref} on something
  17789. of type \code{Any}, and similarly for \code{any-vector-set!} and
  17790. \code{any-vector-length} (Figure~\ref{fig:type-check-Rgradual-1}). In
  17791. Section~\ref{sec:select-Rany} we selected instructions for these
  17792. operations based on the idea that the underlying value was a real
  17793. vector. But in the current setting, the underlying value is of type
  17794. \code{PVector}. So \code{any-vector-ref} can be translates to
  17795. pseudo-x86 as follows. We begin by projecting the underlying value out
  17796. of the tagged value and then call the \code{proxy\_vector\_ref}
  17797. procedure in the runtime.
  17798. \begin{lstlisting}
  17799. (Assign |$\itm{lhs}$| (Prim 'any-vector-ref (list |$e_1$| |$e_2$|)))
  17800. movq |$\neg 111$|, %rdi
  17801. andq |$e_1'$|, %rdi
  17802. movq |$e_2'$|, %rsi
  17803. callq proxy_vector_ref
  17804. movq %rax, |$\itm{lhs'}$|
  17805. \end{lstlisting}
  17806. The \code{any-vector-set!} and \code{any-vector-length} operators can
  17807. be translated in a similar way.
  17808. \begin{exercise}\normalfont\normalsize
  17809. Implement a compiler for the gradually-typed \LangGrad{} language by
  17810. extending and adapting your compiler for \LangLoop{}. Create 10 new
  17811. partially-typed test programs. In addition to testing with these
  17812. new programs, also test your compiler on all the tests for \LangLoop{}
  17813. and tests for \LangDyn{}. Sometimes you may get a type checking error
  17814. on the \LangDyn{} programs but you can adapt them by inserting
  17815. a cast to the \code{Any} type around each subexpression
  17816. causing a type error. While \LangDyn{} does not have explicit casts,
  17817. you can induce one by wrapping the subexpression \code{e}
  17818. with a call to an un-annotated identity function, like this:
  17819. \code{((lambda (x) x) e)}.
  17820. \end{exercise}
  17821. \begin{figure}[p]
  17822. \begin{tikzpicture}[baseline=(current bounding box.center)]
  17823. \node (Rgradual) at (6,4) {\large \LangGrad{}};
  17824. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  17825. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  17826. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  17827. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  17828. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  17829. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  17830. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  17831. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  17832. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  17833. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  17834. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  17835. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  17836. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  17837. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  17838. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  17839. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  17840. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  17841. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  17842. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  17843. \path[->,bend right=15] (Rgradual) edge [above] node
  17844. {\ttfamily\footnotesize type\_check} (Rgradualp);
  17845. \path[->,bend right=15] (Rgradualp) edge [above] node
  17846. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  17847. \path[->,bend right=15] (Rwhilepp) edge [right] node
  17848. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  17849. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  17850. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  17851. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  17852. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  17853. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  17854. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  17855. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  17856. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  17857. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  17858. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  17859. \path[->,bend left=15] (F1-1) edge [below] node
  17860. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  17861. \path[->,bend right=15] (F1-2) edge [above] node
  17862. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  17863. \path[->,bend right=15] (F1-3) edge [above] node
  17864. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  17865. \path[->,bend right=15] (F1-4) edge [above] node
  17866. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  17867. \path[->,bend right=15] (F1-5) edge [right] node
  17868. {\ttfamily\footnotesize explicate\_control} (C3-2);
  17869. \path[->,bend left=15] (C3-2) edge [left] node
  17870. {\ttfamily\footnotesize select\_instr.} (x86-2);
  17871. \path[->,bend right=15] (x86-2) edge [left] node
  17872. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  17873. \path[->,bend right=15] (x86-2-1) edge [below] node
  17874. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  17875. \path[->,bend right=15] (x86-2-2) edge [left] node
  17876. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  17877. \path[->,bend left=15] (x86-3) edge [above] node
  17878. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  17879. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print-x86} (x86-5);
  17880. \end{tikzpicture}
  17881. \caption{Diagram of the passes for \LangGrad{} (gradual typing).}
  17882. \label{fig:Rgradual-passes}
  17883. \end{figure}
  17884. Figure~\ref{fig:Rgradual-passes} provides an overview of all the passes needed
  17885. for the compilation of \LangGrad{}.
  17886. \section{Further Reading}
  17887. This chapter just scratches the surface of gradual typing. The basic
  17888. approach described here is missing two key ingredients that one would
  17889. want in a implementation of gradual typing: blame
  17890. tracking~\citep{Tobin-Hochstadt:2006fk,Wadler:2009qv} and
  17891. space-efficient casts~\citep{Herman:2006uq,Herman:2010aa}. The
  17892. problem addressed by blame tracking is that when a cast on a
  17893. higher-order value fails, it often does so at a point in the program
  17894. that is far removed from the original cast. Blame tracking is a
  17895. technique for propagating extra information through casts and proxies
  17896. so that when a cast fails, the error message can point back to the
  17897. original location of the cast in the source program.
  17898. The problem addressed by space-efficient casts also relates to
  17899. higher-order casts. It turns out that in partially typed programs, a
  17900. function or vector can flow through very-many casts at runtime. With
  17901. the approach described in this chapter, each cast adds another
  17902. \code{lambda} wrapper or a vector proxy. Not only does this take up
  17903. considerable space, but it also makes the function calls and vector
  17904. operations slow. For example, a partially-typed version of quicksort
  17905. could, in the worst case, build a chain of proxies of length $O(n)$
  17906. around the vector, changing the overall time complexity of the
  17907. algorithm from $O(n^2)$ to $O(n^3)$! \citet{Herman:2006uq} suggested a
  17908. solution to this problem by representing casts using the coercion
  17909. calculus of \citet{Henglein:1994nz}, which prevents the creation of
  17910. long chains of proxies by compressing them into a concise normal
  17911. form. \citet{Siek:2015ab} give and algorithm for compressing coercions
  17912. and \citet{Kuhlenschmidt:2019aa} show how to implement these ideas in
  17913. the Grift compiler.
  17914. \begin{center}
  17915. \url{https://github.com/Gradual-Typing/Grift}
  17916. \end{center}
  17917. There are also interesting interactions between gradual typing and
  17918. other language features, such as parametetric polymorphism,
  17919. information-flow types, and type inference, to name a few. We
  17920. recommend the reader to the online gradual typing bibliography:
  17921. \begin{center}
  17922. \url{http://samth.github.io/gradual-typing-bib/}
  17923. \end{center}
  17924. % TODO: challenge problem:
  17925. % type analysis and type specialization?
  17926. % coercions?
  17927. \fi
  17928. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  17929. \chapter{Parametric Polymorphism}
  17930. \label{ch:Lpoly}
  17931. \index{subject}{parametric polymorphism}
  17932. \index{subject}{generics}
  17933. \if\edition\pythonEd
  17934. UNDER CONSTRUCTION
  17935. \fi
  17936. \if\edition\racketEd
  17937. This chapter studies the compilation of parametric
  17938. polymorphism\index{subject}{parametric polymorphism}
  17939. (aka. generics\index{subject}{generics}) in the subset \LangPoly{} of Typed
  17940. Racket. Parametric polymorphism enables improved code reuse by
  17941. parameterizing functions and data structures with respect to the types
  17942. that they operate on. For example, Figure~\ref{fig:map-poly}
  17943. revisits the \code{map} example but this time gives it a more
  17944. fitting type. This \code{map} function is parameterized with
  17945. respect to the element type of the vector. The type of \code{map}
  17946. is the following polymorphic type as specified by the \code{All} and
  17947. the type parameter \code{a}.
  17948. \begin{lstlisting}
  17949. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  17950. \end{lstlisting}
  17951. The idea is that \code{map} can be used at \emph{all} choices of a
  17952. type for parameter \code{a}. In Figure~\ref{fig:map-poly} we apply
  17953. \code{map} to a vector of integers, a choice of \code{Integer} for
  17954. \code{a}, but we could have just as well applied \code{map} to a
  17955. vector of Booleans (and a function on Booleans).
  17956. \begin{figure}[tbp]
  17957. % poly_test_2.rkt
  17958. \begin{lstlisting}
  17959. (: map (All (a) ((a -> a) (Vector a a) -> (Vector a a))))
  17960. (define (map f v)
  17961. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  17962. (define (inc [x : Integer]) : Integer (+ x 1))
  17963. (vector-ref (map inc (vector 0 41)) 1)
  17964. \end{lstlisting}
  17965. \caption{The \code{map} example using parametric polymorphism.}
  17966. \label{fig:map-poly}
  17967. \end{figure}
  17968. Figure~\ref{fig:Rpoly-concrete-syntax} defines the concrete syntax of
  17969. \LangPoly{} and Figure~\ref{fig:Rpoly-syntax} defines the abstract
  17970. syntax. We add a second form for function definitions in which a type
  17971. declaration comes before the \code{define}. In the abstract syntax,
  17972. the return type in the \code{Def} is \code{Any}, but that should be
  17973. ignored in favor of the return type in the type declaration. (The
  17974. \code{Any} comes from using the same parser as in
  17975. Chapter~\ref{ch:Ldyn}.) The presence of a type declaration
  17976. enables the use of an \code{All} type for a function, thereby making
  17977. it polymorphic. The grammar for types is extended to include
  17978. polymorphic types and type variables.
  17979. \begin{figure}[tp]
  17980. \centering
  17981. \fbox{
  17982. \begin{minipage}{0.96\textwidth}
  17983. \small
  17984. \[
  17985. \begin{array}{lcl}
  17986. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  17987. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS \ldots}{\Type}{\Exp} } \\
  17988. &\MID& \LP\key{:}~\Var~\Type\RP \\
  17989. && \LP\key{define}~ \LP\Var ~ \Var\ldots\RP ~ \Exp\RP \\
  17990. \LangPoly{} &::=& \gray{ \Def \ldots ~ \Exp }
  17991. \end{array}
  17992. \]
  17993. \end{minipage}
  17994. }
  17995. \caption{The concrete syntax of \LangPoly{}, extending \LangLoop{}
  17996. (Figure~\ref{fig:Lwhile-concrete-syntax}).}
  17997. \label{fig:Rpoly-concrete-syntax}
  17998. \end{figure}
  17999. \begin{figure}[tp]
  18000. \centering
  18001. \fbox{
  18002. \begin{minipage}{0.96\textwidth}
  18003. \small
  18004. \[
  18005. \begin{array}{lcl}
  18006. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18007. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18008. &\MID& \DECL{\Var}{\Type} \\
  18009. && \DEF{\Var}{\LP\Var \ldots\RP}{\key{'Any}}{\code{'()}}{\Exp} \\
  18010. \LangPoly{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18011. \end{array}
  18012. \]
  18013. \end{minipage}
  18014. }
  18015. \caption{The abstract syntax of \LangPoly{}, extending \LangLoop{}
  18016. (Figure~\ref{fig:Lwhile-syntax}).}
  18017. \label{fig:Rpoly-syntax}
  18018. \end{figure}
  18019. By including polymorphic types in the $\Type$ non-terminal we choose
  18020. to make them first-class which has interesting repercussions on the
  18021. compiler. Many languages with polymorphism, such as
  18022. C++~\citep{stroustrup88:_param_types} and Standard
  18023. ML~\citep{Milner:1990fk}, only support second-class polymorphism, so
  18024. it is useful to see an example of first-class polymorphism. In
  18025. Figure~\ref{fig:apply-twice} we define a function \code{apply-twice}
  18026. whose parameter is a polymorphic function. The occurrence of a
  18027. polymorphic type underneath a function type is enabled by the normal
  18028. recursive structure of the grammar for $\Type$ and the categorization
  18029. of the \code{All} type as a $\Type$. The body of \code{apply-twice}
  18030. applies the polymorphic function to a Boolean and to an integer.
  18031. \begin{figure}[tbp]
  18032. \begin{lstlisting}
  18033. (: apply-twice ((All (b) (b -> b)) -> Integer))
  18034. (define (apply-twice f)
  18035. (if (f #t) (f 42) (f 777)))
  18036. (: id (All (a) (a -> a)))
  18037. (define (id x) x)
  18038. (apply-twice id)
  18039. \end{lstlisting}
  18040. \caption{An example illustrating first-class polymorphism.}
  18041. \label{fig:apply-twice}
  18042. \end{figure}
  18043. The type checker for \LangPoly{} in Figure~\ref{fig:type-check-Lvar0} has
  18044. three new responsibilities (compared to \LangLoop{}). The type checking of
  18045. function application is extended to handle the case where the operator
  18046. expression is a polymorphic function. In that case the type arguments
  18047. are deduced by matching the type of the parameters with the types of
  18048. the arguments.
  18049. %
  18050. The \code{match-types} auxiliary function carries out this deduction
  18051. by recursively descending through a parameter type \code{pt} and the
  18052. corresponding argument type \code{at}, making sure that they are equal
  18053. except when there is a type parameter on the left (in the parameter
  18054. type). If it is the first time that the type parameter has been
  18055. encountered, then the algorithm deduces an association of the type
  18056. parameter to the corresponding type on the right (in the argument
  18057. type). If it is not the first time that the type parameter has been
  18058. encountered, the algorithm looks up its deduced type and makes sure
  18059. that it is equal to the type on the right.
  18060. %
  18061. Once the type arguments are deduced, the operator expression is
  18062. wrapped in an \code{Inst} AST node (for instantiate) that records the
  18063. type of the operator, but more importantly, records the deduced type
  18064. arguments. The return type of the application is the return type of
  18065. the polymorphic function, but with the type parameters replaced by the
  18066. deduced type arguments, using the \code{subst-type} function.
  18067. The second responsibility of the type checker is extending the
  18068. function \code{type-equal?} to handle the \code{All} type. This is
  18069. not quite a simple as equal on other types, such as function and
  18070. vector types, because two polymorphic types can be syntactically
  18071. different even though they are equivalent types. For example,
  18072. \code{(All (a) (a -> a))} is equivalent to \code{(All (b) (b -> b))}.
  18073. Two polymorphic types should be considered equal if they differ only
  18074. in the choice of the names of the type parameters. The
  18075. \code{type-equal?} function in Figure~\ref{fig:type-check-Lvar0-aux}
  18076. renames the type parameters of the first type to match the type
  18077. parameters of the second type.
  18078. The third responsibility of the type checker is making sure that only
  18079. defined type variables appear in type annotations. The
  18080. \code{check-well-formed} function defined in
  18081. Figure~\ref{fig:well-formed-types} recursively inspects a type, making
  18082. sure that each type variable has been defined.
  18083. The output language of the type checker is \LangInst{}, defined in
  18084. Figure~\ref{fig:Rpoly-prime-syntax}. The type checker combines the type
  18085. declaration and polymorphic function into a single definition, using
  18086. the \code{Poly} form, to make polymorphic functions more convenient to
  18087. process in next pass of the compiler.
  18088. \begin{figure}[tp]
  18089. \centering
  18090. \fbox{
  18091. \begin{minipage}{0.96\textwidth}
  18092. \small
  18093. \[
  18094. \begin{array}{lcl}
  18095. \Type &::=& \ldots \MID \LP\key{All}~\LP\Var\ldots\RP~ \Type\RP \MID \Var \\
  18096. \Exp &::=& \ldots \MID \INST{\Exp}{\Type}{\LP\Type\ldots\RP} \\
  18097. \Def &::=& \gray{ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp} } \\
  18098. &\MID& \LP\key{Poly}~\LP\Var\ldots\RP~ \DEF{\Var}{\LP\LS\Var \key{:} \Type\RS \ldots\RP}{\Type}{\code{'()}}{\Exp}\RP \\
  18099. \LangInst{} &::=& \gray{ \PROGRAMDEFSEXP{\code{'()}}{\LP\Def\ldots\RP}{\Exp} }
  18100. \end{array}
  18101. \]
  18102. \end{minipage}
  18103. }
  18104. \caption{The abstract syntax of \LangInst{}, extending \LangLoop{}
  18105. (Figure~\ref{fig:Lwhile-syntax}).}
  18106. \label{fig:Rpoly-prime-syntax}
  18107. \end{figure}
  18108. The output of the type checker on the polymorphic \code{map}
  18109. example is listed in Figure~\ref{fig:map-type-check}.
  18110. \begin{figure}[tbp]
  18111. % poly_test_2.rkt
  18112. \begin{lstlisting}
  18113. (poly (a) (define (map [f : (a -> a)] [v : (Vector a a)]) : (Vector a a)
  18114. (vector (f (vector-ref v 0)) (f (vector-ref v 1)))))
  18115. (define (inc [x : Integer]) : Integer (+ x 1))
  18116. (vector-ref ((inst map (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18117. (Integer))
  18118. inc (vector 0 41)) 1)
  18119. \end{lstlisting}
  18120. \caption{Output of the type checker on the \code{map} example.}
  18121. \label{fig:map-type-check}
  18122. \end{figure}
  18123. \begin{figure}[tbp]
  18124. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18125. (define type-check-poly-class
  18126. (class type-check-Rwhile-class
  18127. (super-new)
  18128. (inherit check-type-equal?)
  18129. (define/override (type-check-apply env e1 es)
  18130. (define-values (e^ ty) ((type-check-exp env) e1))
  18131. (define-values (es^ ty*) (for/lists (es^ ty*) ([e (in-list es)])
  18132. ((type-check-exp env) e)))
  18133. (match ty
  18134. [`(,ty^* ... -> ,rt)
  18135. (for ([arg-ty ty*] [param-ty ty^*])
  18136. (check-type-equal? arg-ty param-ty (Apply e1 es)))
  18137. (values e^ es^ rt)]
  18138. [`(All ,xs (,tys ... -> ,rt))
  18139. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18140. (define env^^ (for/fold ([env^^ env^]) ([arg-ty ty*] [param-ty tys])
  18141. (match-types env^^ param-ty arg-ty)))
  18142. (define targs
  18143. (for/list ([x xs])
  18144. (match (dict-ref env^^ x (lambda () #f))
  18145. [#f (error 'type-check "type variable ~a not deduced\nin ~v"
  18146. x (Apply e1 es))]
  18147. [ty ty])))
  18148. (values (Inst e^ ty targs) es^ (subst-type env^^ rt))]
  18149. [else (error 'type-check "expected a function, not ~a" ty)]))
  18150. (define/override ((type-check-exp env) e)
  18151. (match e
  18152. [(Lambda `([,xs : ,Ts] ...) rT body)
  18153. (for ([T Ts]) ((check-well-formed env) T))
  18154. ((check-well-formed env) rT)
  18155. ((super type-check-exp env) e)]
  18156. [(HasType e1 ty)
  18157. ((check-well-formed env) ty)
  18158. ((super type-check-exp env) e)]
  18159. [else ((super type-check-exp env) e)]))
  18160. (define/override ((type-check-def env) d)
  18161. (verbose 'type-check "poly/def" d)
  18162. (match d
  18163. [(Generic ts (Def f (and p:t* (list `[,xs : ,ps] ...)) rt info body))
  18164. (define ts-env (for/list ([t ts]) (cons t 'Type)))
  18165. (for ([p ps]) ((check-well-formed ts-env) p))
  18166. ((check-well-formed ts-env) rt)
  18167. (define new-env (append ts-env (map cons xs ps) env))
  18168. (define-values (body^ ty^) ((type-check-exp new-env) body))
  18169. (check-type-equal? ty^ rt body)
  18170. (Generic ts (Def f p:t* rt info body^))]
  18171. [else ((super type-check-def env) d)]))
  18172. (define/override (type-check-program p)
  18173. (match p
  18174. [(Program info body)
  18175. (type-check-program (ProgramDefsExp info '() body))]
  18176. [(ProgramDefsExp info ds body)
  18177. (define ds^ (combine-decls-defs ds))
  18178. (define new-env (for/list ([d ds^])
  18179. (cons (def-name d) (fun-def-type d))))
  18180. (define ds^^ (for/list ([d ds^]) ((type-check-def new-env) d)))
  18181. (define-values (body^ ty) ((type-check-exp new-env) body))
  18182. (check-type-equal? ty 'Integer body)
  18183. (ProgramDefsExp info ds^^ body^)]))
  18184. ))
  18185. \end{lstlisting}
  18186. \caption{Type checker for the \LangPoly{} language.}
  18187. \label{fig:type-check-Lvar0}
  18188. \end{figure}
  18189. \begin{figure}[tbp]
  18190. \begin{lstlisting}[basicstyle=\ttfamily\scriptsize]
  18191. (define/override (type-equal? t1 t2)
  18192. (match* (t1 t2)
  18193. [(`(All ,xs ,T1) `(All ,ys ,T2))
  18194. (define env (map cons xs ys))
  18195. (type-equal? (subst-type env T1) T2)]
  18196. [(other wise)
  18197. (super type-equal? t1 t2)]))
  18198. (define/public (match-types env pt at)
  18199. (match* (pt at)
  18200. [('Integer 'Integer) env] [('Boolean 'Boolean) env]
  18201. [('Void 'Void) env] [('Any 'Any) env]
  18202. [(`(Vector ,pts ...) `(Vector ,ats ...))
  18203. (for/fold ([env^ env]) ([pt1 pts] [at1 ats])
  18204. (match-types env^ pt1 at1))]
  18205. [(`(,pts ... -> ,prt) `(,ats ... -> ,art))
  18206. (define env^ (match-types env prt art))
  18207. (for/fold ([env^^ env^]) ([pt1 pts] [at1 ats])
  18208. (match-types env^^ pt1 at1))]
  18209. [(`(All ,pxs ,pt1) `(All ,axs ,at1))
  18210. (define env^ (append (map cons pxs axs) env))
  18211. (match-types env^ pt1 at1)]
  18212. [((? symbol? x) at)
  18213. (match (dict-ref env x (lambda () #f))
  18214. [#f (error 'type-check "undefined type variable ~a" x)]
  18215. ['Type (cons (cons x at) env)]
  18216. [t^ (check-type-equal? at t^ 'matching) env])]
  18217. [(other wise) (error 'type-check "mismatch ~a != a" pt at)]))
  18218. (define/public (subst-type env pt)
  18219. (match pt
  18220. ['Integer 'Integer] ['Boolean 'Boolean]
  18221. ['Void 'Void] ['Any 'Any]
  18222. [`(Vector ,ts ...)
  18223. `(Vector ,@(for/list ([t ts]) (subst-type env t)))]
  18224. [`(,ts ... -> ,rt)
  18225. `(,@(for/list ([t ts]) (subst-type env t)) -> ,(subst-type env rt))]
  18226. [`(All ,xs ,t)
  18227. `(All ,xs ,(subst-type (append (map cons xs xs) env) t))]
  18228. [(? symbol? x) (dict-ref env x)]
  18229. [else (error 'type-check "expected a type not ~a" pt)]))
  18230. (define/public (combine-decls-defs ds)
  18231. (match ds
  18232. ['() '()]
  18233. [`(,(Decl name type) . (,(Def f params _ info body) . ,ds^))
  18234. (unless (equal? name f)
  18235. (error 'type-check "name mismatch, ~a != ~a" name f))
  18236. (match type
  18237. [`(All ,xs (,ps ... -> ,rt))
  18238. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18239. (cons (Generic xs (Def name params^ rt info body))
  18240. (combine-decls-defs ds^))]
  18241. [`(,ps ... -> ,rt)
  18242. (define params^ (for/list ([x params] [T ps]) `[,x : ,T]))
  18243. (cons (Def name params^ rt info body) (combine-decls-defs ds^))]
  18244. [else (error 'type-check "expected a function type, not ~a" type) ])]
  18245. [`(,(Def f params rt info body) . ,ds^)
  18246. (cons (Def f params rt info body) (combine-decls-defs ds^))]))
  18247. \end{lstlisting}
  18248. \caption{Auxiliary functions for type checking \LangPoly{}.}
  18249. \label{fig:type-check-Lvar0-aux}
  18250. \end{figure}
  18251. \begin{figure}[tbp]
  18252. \begin{lstlisting}%[basicstyle=\ttfamily\scriptsize]
  18253. (define/public ((check-well-formed env) ty)
  18254. (match ty
  18255. ['Integer (void)]
  18256. ['Boolean (void)]
  18257. ['Void (void)]
  18258. [(? symbol? a)
  18259. (match (dict-ref env a (lambda () #f))
  18260. ['Type (void)]
  18261. [else (error 'type-check "undefined type variable ~a" a)])]
  18262. [`(Vector ,ts ...)
  18263. (for ([t ts]) ((check-well-formed env) t))]
  18264. [`(,ts ... -> ,t)
  18265. (for ([t ts]) ((check-well-formed env) t))
  18266. ((check-well-formed env) t)]
  18267. [`(All ,xs ,t)
  18268. (define env^ (append (for/list ([x xs]) (cons x 'Type)) env))
  18269. ((check-well-formed env^) t)]
  18270. [else (error 'type-check "unrecognized type ~a" ty)]))
  18271. \end{lstlisting}
  18272. \caption{Well-formed types.}
  18273. \label{fig:well-formed-types}
  18274. \end{figure}
  18275. % TODO: interpreter for R'_10
  18276. \section{Compiling Polymorphism}
  18277. \label{sec:compiling-poly}
  18278. Broadly speaking, there are four approaches to compiling parametric
  18279. polymorphism, which we describe below.
  18280. \begin{description}
  18281. \item[Monomorphization] generates a different version of a polymorphic
  18282. function for each set of type arguments that it is used with,
  18283. producing type-specialized code. This approach results in the most
  18284. efficient code but requires whole-program compilation (no separate
  18285. compilation) and increases code size. For our current purposes
  18286. monomorphization is a non-starter because, with first-class
  18287. polymorphism, it is sometimes not possible to determine which
  18288. generic functions are used with which type arguments during
  18289. compilation. (It can be done at runtime, with just-in-time
  18290. compilation.) This approach is used to compile C++
  18291. templates~\citep{stroustrup88:_param_types} and polymorphic
  18292. functions in NESL~\citep{Blelloch:1993aa} and
  18293. ML~\citep{Weeks:2006aa}.
  18294. \item[Uniform representation] generates one version of each
  18295. polymorphic function but requires all values have a common ``boxed''
  18296. format, such as the tagged values of type \code{Any} in
  18297. \LangAny{}. Non-polymorphic code (i.e. monomorphic code) is compiled
  18298. similarly to code in a dynamically typed language (like \LangDyn{}),
  18299. in which primitive operators require their arguments to be projected
  18300. from \code{Any} and their results are injected into \code{Any}. (In
  18301. object-oriented languages, the projection is accomplished via
  18302. virtual method dispatch.) The uniform representation approach is
  18303. compatible with separate compilation and with first-class
  18304. polymorphism. However, it produces the least-efficient code because
  18305. it introduces overhead in the entire program, including
  18306. non-polymorphic code. This approach is used in implementations of
  18307. CLU~\cite{liskov79:_clu_ref,Liskov:1993dk},
  18308. ML~\citep{Cardelli:1984aa,Appel:1987aa}, and
  18309. Java~\citep{Bracha:1998fk}.
  18310. \item[Mixed representation] generates one version of each polymorphic
  18311. function, using a boxed representation for type
  18312. variables. Monomorphic code is compiled as usual (as in \LangLoop{})
  18313. and conversions are performed at the boundaries between monomorphic
  18314. and polymorphic (e.g. when a polymorphic function is instantiated
  18315. and called). This approach is compatible with separate compilation
  18316. and first-class polymorphism and maintains the efficiency of
  18317. monomorphic code. The tradeoff is increased overhead at the boundary
  18318. between monomorphic and polymorphic code. This approach is used in
  18319. implementations of ML~\citep{Leroy:1992qb} and Java, starting in
  18320. Java 5 with the addition of autoboxing.
  18321. \item[Type passing] uses the unboxed representation in both
  18322. monomorphic and polymorphic code. Each polymorphic function is
  18323. compiled to a single function with extra parameters that describe
  18324. the type arguments. The type information is used by the generated
  18325. code to know how to access the unboxed values at runtime. This
  18326. approach is used in implementation of the Napier88
  18327. language~\citep{Morrison:1991aa} and ML~\citep{Harper:1995um}. Type
  18328. passing is compatible with separate compilation and first-class
  18329. polymorphism and maintains the efficiency for monomorphic
  18330. code. There is runtime overhead in polymorphic code from dispatching
  18331. on type information.
  18332. \end{description}
  18333. In this chapter we use the mixed representation approach, partly
  18334. because of its favorable attributes, and partly because it is
  18335. straightforward to implement using the tools that we have already
  18336. built to support gradual typing. To compile polymorphic functions, we
  18337. add just one new pass, \code{erase-types}, to compile \LangInst{} to
  18338. \LangCast{}.
  18339. \section{Erase Types}
  18340. \label{sec:erase-types}
  18341. We use the \code{Any} type from Chapter~\ref{ch:Ldyn} to
  18342. represent type variables. For example, Figure~\ref{fig:map-erase}
  18343. shows the output of the \code{erase-types} pass on the polymorphic
  18344. \code{map} (Figure~\ref{fig:map-poly}). The occurrences of
  18345. type parameter \code{a} are replaced by \code{Any} and the polymorphic
  18346. \code{All} types are removed from the type of \code{map}.
  18347. \begin{figure}[tbp]
  18348. \begin{lstlisting}
  18349. (define (map [f : (Any -> Any)] [v : (Vector Any Any)])
  18350. : (Vector Any Any)
  18351. (vector (f (vector-ref v 0)) (f (vector-ref v 1))))
  18352. (define (inc [x : Integer]) : Integer (+ x 1))
  18353. (vector-ref ((cast map
  18354. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18355. ((Integer -> Integer) (Vector Integer Integer)
  18356. -> (Vector Integer Integer)))
  18357. inc (vector 0 41)) 1)
  18358. \end{lstlisting}
  18359. \caption{The polymorphic \code{map} example after type erasure.}
  18360. \label{fig:map-erase}
  18361. \end{figure}
  18362. This process of type erasure creates a challenge at points of
  18363. instantiation. For example, consider the instantiation of
  18364. \code{map} in Figure~\ref{fig:map-type-check}.
  18365. The type of \code{map} is
  18366. \begin{lstlisting}
  18367. (All (a) ((a -> a) (Vector a a) -> (Vector a a)))
  18368. \end{lstlisting}
  18369. and it is instantiated to
  18370. \begin{lstlisting}
  18371. ((Integer -> Integer) (Vector Integer Integer)
  18372. -> (Vector Integer Integer))
  18373. \end{lstlisting}
  18374. After erasure, the type of \code{map} is
  18375. \begin{lstlisting}
  18376. ((Any -> Any) (Vector Any Any) -> (Vector Any Any))
  18377. \end{lstlisting}
  18378. but we need to convert it to the instantiated type. This is easy to
  18379. do in the target language \LangCast{} with a single \code{cast}. In
  18380. Figure~\ref{fig:map-erase}, the instantiation of \code{map}
  18381. has been compiled to a \code{cast} from the type of \code{map} to
  18382. the instantiated type. The source and target type of a cast must be
  18383. consistent (Figure~\ref{fig:consistent}), which indeed is the case
  18384. because both the source and target are obtained from the same
  18385. polymorphic type of \code{map}, replacing the type parameters with
  18386. \code{Any} in the former and with the deduced type arguments in the
  18387. later. (Recall that the \code{Any} type is consistent with any type.)
  18388. To implement the \code{erase-types} pass, we recommend defining a
  18389. recursive auxiliary function named \code{erase-type} that applies the
  18390. following two transformations. It replaces type variables with
  18391. \code{Any}
  18392. \begin{lstlisting}
  18393. |$x$|
  18394. |$\Rightarrow$|
  18395. Any
  18396. \end{lstlisting}
  18397. and it removes the polymorphic \code{All} types.
  18398. \begin{lstlisting}
  18399. (All |$xs$| |$T_1$|)
  18400. |$\Rightarrow$|
  18401. |$T'_1$|
  18402. \end{lstlisting}
  18403. Apply the \code{erase-type} function to all of the type annotations in
  18404. the program.
  18405. Regarding the translation of expressions, the case for \code{Inst} is
  18406. the interesting one. We translate it into a \code{Cast}, as shown
  18407. below. The type of the subexpression $e$ is the polymorphic type
  18408. $\LP\key{All} xs T\RP$. The source type of the cast is the erasure of
  18409. $T$, the type $T'$. The target type $T''$ is the result of
  18410. substituting the arguments types $ts$ for the type parameters $xs$ in
  18411. $T$ followed by doing type erasure.
  18412. \begin{lstlisting}
  18413. (Inst |$e$| (All |$xs$| |$T$|) |$ts$|)
  18414. |$\Rightarrow$|
  18415. (Cast |$e'$| |$T'$| |$T''$|)
  18416. \end{lstlisting}
  18417. where $T'' = \LP\code{erase-type}~\LP\code{subst-type}~s~T\RP\RP$
  18418. and $s = \LP\code{map}~\code{cons}~xs~ts\RP$.
  18419. Finally, each polymorphic function is translated to a regular
  18420. functions in which type erasure has been applied to all the type
  18421. annotations and the body.
  18422. \begin{lstlisting}
  18423. (Poly |$ts$| (Def |$f$| ([|$x_1$| : |$T_1$|] |$\ldots$|) |$T_r$| |$\itm{info}$| |$e$|))
  18424. |$\Rightarrow$|
  18425. (Def |$f$| ([|$x_1$| : |$T'_1$|] |$\ldots$|) |$T'_r$| |$\itm{info}$| |$e'$|)
  18426. \end{lstlisting}
  18427. \begin{exercise}\normalfont\normalsize
  18428. Implement a compiler for the polymorphic language \LangPoly{} by
  18429. extending and adapting your compiler for \LangGrad{}. Create 6 new test
  18430. programs that use polymorphic functions. Some of them should make
  18431. use of first-class polymorphism.
  18432. \end{exercise}
  18433. \begin{figure}[p]
  18434. \begin{tikzpicture}[baseline=(current bounding box.center)]
  18435. \node (Rpoly) at (9,4) {\large \LangPoly{}};
  18436. \node (Rpolyp) at (6,4) {\large \LangInst{}};
  18437. \node (Rgradualp) at (3,4) {\large \LangCast{}};
  18438. \node (Rwhilepp) at (0,4) {\large \LangProxy{}};
  18439. \node (Rwhileproxy) at (0,2) {\large \LangPVec{}};
  18440. \node (Rwhileproxy-2) at (3,2) {\large \LangPVec{}};
  18441. \node (Rwhileproxy-3) at (6,2) {\large \LangPVec{}};
  18442. \node (Rwhileproxy-4) at (9,2) {\large \LangPVecFunRef{}};
  18443. \node (Rwhileproxy-5) at (12,2) {\large \LangPVecFunRef{}};
  18444. \node (F1-1) at (12,0) {\large \LangPVecFunRef{}};
  18445. \node (F1-2) at (9,0) {\large \LangPVecFunRef{}};
  18446. \node (F1-3) at (6,0) {\large \LangPVecFunRef{}};
  18447. \node (F1-4) at (3,0) {\large \LangPVecAlloc{}};
  18448. \node (F1-5) at (0,0) {\large \LangPVecAlloc{}};
  18449. \node (C3-2) at (3,-2) {\large \LangCLoopPVec{}};
  18450. \node (x86-2) at (3,-4) {\large \LangXIndCallVar{}};
  18451. \node (x86-2-1) at (3,-6) {\large \LangXIndCallVar{}};
  18452. \node (x86-2-2) at (6,-6) {\large \LangXIndCallVar{}};
  18453. \node (x86-3) at (6,-4) {\large \LangXIndCallVar{}};
  18454. \node (x86-4) at (9,-4) {\large \LangXIndCall{}};
  18455. \node (x86-5) at (9,-6) {\large \LangXIndCall{}};
  18456. \path[->,bend right=15] (Rpoly) edge [above] node
  18457. {\ttfamily\footnotesize type\_check} (Rpolyp);
  18458. \path[->,bend right=15] (Rpolyp) edge [above] node
  18459. {\ttfamily\footnotesize erase\_types} (Rgradualp);
  18460. \path[->,bend right=15] (Rgradualp) edge [above] node
  18461. {\ttfamily\footnotesize lower\_casts} (Rwhilepp);
  18462. \path[->,bend right=15] (Rwhilepp) edge [right] node
  18463. {\ttfamily\footnotesize differentiate\_proxies} (Rwhileproxy);
  18464. \path[->,bend left=15] (Rwhileproxy) edge [above] node
  18465. {\ttfamily\footnotesize shrink} (Rwhileproxy-2);
  18466. \path[->,bend left=15] (Rwhileproxy-2) edge [above] node
  18467. {\ttfamily\footnotesize uniquify} (Rwhileproxy-3);
  18468. \path[->,bend left=15] (Rwhileproxy-3) edge [above] node
  18469. {\ttfamily\footnotesize reveal\_functions} (Rwhileproxy-4);
  18470. \path[->,bend left=15] (Rwhileproxy-4) edge [above] node
  18471. {\ttfamily\footnotesize reveal\_casts} (Rwhileproxy-5);
  18472. \path[->,bend left=15] (Rwhileproxy-5) edge [left] node
  18473. {\ttfamily\footnotesize convert\_assignments} (F1-1);
  18474. \path[->,bend left=15] (F1-1) edge [below] node
  18475. {\ttfamily\footnotesize convert\_to\_clos.} (F1-2);
  18476. \path[->,bend right=15] (F1-2) edge [above] node
  18477. {\ttfamily\footnotesize limit\_fun.} (F1-3);
  18478. \path[->,bend right=15] (F1-3) edge [above] node
  18479. {\ttfamily\footnotesize expose\_alloc.} (F1-4);
  18480. \path[->,bend right=15] (F1-4) edge [above] node
  18481. {\ttfamily\footnotesize remove\_complex.} (F1-5);
  18482. \path[->,bend right=15] (F1-5) edge [right] node
  18483. {\ttfamily\footnotesize explicate\_control} (C3-2);
  18484. \path[->,bend left=15] (C3-2) edge [left] node
  18485. {\ttfamily\footnotesize select\_instr.} (x86-2);
  18486. \path[->,bend right=15] (x86-2) edge [left] node
  18487. {\ttfamily\footnotesize uncover\_live} (x86-2-1);
  18488. \path[->,bend right=15] (x86-2-1) edge [below] node
  18489. {\ttfamily\footnotesize build\_inter.} (x86-2-2);
  18490. \path[->,bend right=15] (x86-2-2) edge [left] node
  18491. {\ttfamily\footnotesize allocate\_reg.} (x86-3);
  18492. \path[->,bend left=15] (x86-3) edge [above] node
  18493. {\ttfamily\footnotesize patch\_instr.} (x86-4);
  18494. \path[->,bend left=15] (x86-4) edge [right] node {\ttfamily\footnotesize print\_x86} (x86-5);
  18495. \end{tikzpicture}
  18496. \caption{Diagram of the passes for \LangPoly{} (parametric polymorphism).}
  18497. \label{fig:Rpoly-passes}
  18498. \end{figure}
  18499. Figure~\ref{fig:Rpoly-passes} provides an overview of all the passes needed
  18500. for the compilation of \LangPoly{}.
  18501. % TODO: challenge problem: specialization of instantiations
  18502. % Further Reading
  18503. \fi
  18504. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  18505. \clearpage
  18506. \appendix
  18507. \chapter{Appendix}
  18508. \if\edition\racketEd
  18509. \section{Interpreters}
  18510. \label{appendix:interp}
  18511. \index{subject}{interpreter}
  18512. We provide interpreters for each of the source languages \LangInt{},
  18513. \LangVar{}, $\ldots$ in the files \code{interp\_Lint.rkt},
  18514. \code{interp-Lvar.rkt}, etc. The interpreters for the intermediate
  18515. languages \LangCVar{} and \LangCIf{} are in \code{interp-Cvar.rkt} and
  18516. \code{interp-C1.rkt}. The interpreters for \LangCVec{}, \LangCFun{}, pseudo-x86,
  18517. and x86 are in the \key{interp.rkt} file.
  18518. \section{Utility Functions}
  18519. \label{appendix:utilities}
  18520. The utility functions described in this section are in the
  18521. \key{utilities.rkt} file of the support code.
  18522. \paragraph{\code{interp-tests}}
  18523. The \key{interp-tests} function runs the compiler passes and the
  18524. interpreters on each of the specified tests to check whether each pass
  18525. is correct. The \key{interp-tests} function has the following
  18526. parameters:
  18527. \begin{description}
  18528. \item[name (a string)] a name to identify the compiler,
  18529. \item[typechecker] a function of exactly one argument that either
  18530. raises an error using the \code{error} function when it encounters a
  18531. type error, or returns \code{\#f} when it encounters a type
  18532. error. If there is no type error, the type checker returns the
  18533. program.
  18534. \item[passes] a list with one entry per pass. An entry is a list with
  18535. four things:
  18536. \begin{enumerate}
  18537. \item a string giving the name of the pass,
  18538. \item the function that implements the pass (a translator from AST
  18539. to AST),
  18540. \item a function that implements the interpreter (a function from
  18541. AST to result value) for the output language,
  18542. \item and a type checker for the output language. Type checkers for
  18543. the $R$ and $C$ languages are provided in the support code. For
  18544. example, the type checkers for \LangVar{} and \LangCVar{} are in
  18545. \code{type-check-Lvar.rkt} and \code{type-check-Cvar.rkt}. The
  18546. type checker entry is optional. The support code does not provide
  18547. type checkers for the x86 languages.
  18548. \end{enumerate}
  18549. \item[source-interp] an interpreter for the source language. The
  18550. interpreters from Appendix~\ref{appendix:interp} make a good choice.
  18551. \item[test-family (a string)] for example, \code{"r1"}, \code{"r2"}, etc.
  18552. \item[tests] a list of test numbers that specifies which tests to
  18553. run. (see below)
  18554. \end{description}
  18555. %
  18556. The \key{interp-tests} function assumes that the subdirectory
  18557. \key{tests} has a collection of Racket programs whose names all start
  18558. with the family name, followed by an underscore and then the test
  18559. number, ending with the file extension \key{.rkt}. Also, for each test
  18560. program that calls \code{read} one or more times, there is a file with
  18561. the same name except that the file extension is \key{.in} that
  18562. provides the input for the Racket program. If the test program is
  18563. expected to fail type checking, then there should be an empty file of
  18564. the same name but with extension \key{.tyerr}.
  18565. \paragraph{\code{compiler-tests}}
  18566. runs the compiler passes to generate x86 (a \key{.s} file) and then
  18567. runs the GNU C compiler (gcc) to generate machine code. It runs the
  18568. machine code and checks that the output is $42$. The parameters to the
  18569. \code{compiler-tests} function are similar to those of the
  18570. \code{interp-tests} function, and consist of
  18571. \begin{itemize}
  18572. \item a compiler name (a string),
  18573. \item a type checker,
  18574. \item description of the passes,
  18575. \item name of a test-family, and
  18576. \item a list of test numbers.
  18577. \end{itemize}
  18578. \paragraph{\code{compile-file}}
  18579. takes a description of the compiler passes (see the comment for
  18580. \key{interp-tests}) and returns a function that, given a program file
  18581. name (a string ending in \key{.rkt}), applies all of the passes and
  18582. writes the output to a file whose name is the same as the program file
  18583. name but with \key{.rkt} replaced with \key{.s}.
  18584. \paragraph{\code{read-program}}
  18585. takes a file path and parses that file (it must be a Racket program)
  18586. into an abstract syntax tree.
  18587. \paragraph{\code{parse-program}}
  18588. takes an S-expression representation of an abstract syntax tree and converts it into
  18589. the struct-based representation.
  18590. \paragraph{\code{assert}}
  18591. takes two parameters, a string (\code{msg}) and Boolean (\code{bool}),
  18592. and displays the message \key{msg} if the Boolean \key{bool} is false.
  18593. \paragraph{\code{lookup}}
  18594. % remove discussion of lookup? -Jeremy
  18595. takes a key and an alist, and returns the first value that is
  18596. associated with the given key, if there is one. If not, an error is
  18597. triggered. The alist may contain both immutable pairs (built with
  18598. \key{cons}) and mutable pairs (built with \key{mcons}).
  18599. %The \key{map2} function ...
  18600. \fi %\racketEd
  18601. \section{x86 Instruction Set Quick-Reference}
  18602. \label{sec:x86-quick-reference}
  18603. \index{subject}{x86}
  18604. Table~\ref{tab:x86-instr} lists some x86 instructions and what they
  18605. do. We write $A \to B$ to mean that the value of $A$ is written into
  18606. location $B$. Address offsets are given in bytes. The instruction
  18607. arguments $A, B, C$ can be immediate constants (such as \code{\$4}),
  18608. registers (such as \code{\%rax}), or memory references (such as
  18609. \code{-4(\%ebp)}). Most x86 instructions only allow at most one memory
  18610. reference per instruction. Other operands must be immediates or
  18611. registers.
  18612. \begin{table}[tbp]
  18613. \centering
  18614. \begin{tabular}{l|l}
  18615. \textbf{Instruction} & \textbf{Operation} \\ \hline
  18616. \texttt{addq} $A$, $B$ & $A + B \to B$\\
  18617. \texttt{negq} $A$ & $- A \to A$ \\
  18618. \texttt{subq} $A$, $B$ & $B - A \to B$\\
  18619. \texttt{imulq} $A$, $B$ & $A \times B \to B$\\
  18620. \texttt{callq} $L$ & Pushes the return address and jumps to label $L$ \\
  18621. \texttt{callq} \texttt{*}$A$ & Calls the function at the address $A$. \\
  18622. %\texttt{leave} & $\texttt{ebp} \to \texttt{esp};$ \texttt{popl \%ebp} \\
  18623. \texttt{retq} & Pops the return address and jumps to it \\
  18624. \texttt{popq} $A$ & $*\mathtt{rsp} \to A; \mathtt{rsp} + 8 \to \mathtt{rsp}$ \\
  18625. \texttt{pushq} $A$ & $\texttt{rsp} - 8 \to \texttt{rsp}; A \to *\texttt{rsp}$\\
  18626. \texttt{leaq} $A$,$B$ & $A \to B$ ($B$ must be a register) \\
  18627. \texttt{cmpq} $A$, $B$ & compare $A$ and $B$ and set the flag register ($B$ must not
  18628. be an immediate) \\
  18629. \texttt{je} $L$ & \multirow{5}{3.7in}{Jump to label $L$ if the flag register
  18630. matches the condition code of the instruction, otherwise go to the
  18631. next instructions. The condition codes are \key{e} for ``equal'',
  18632. \key{l} for ``less'', \key{le} for ``less or equal'', \key{g}
  18633. for ``greater'', and \key{ge} for ``greater or equal''.} \\
  18634. \texttt{jl} $L$ & \\
  18635. \texttt{jle} $L$ & \\
  18636. \texttt{jg} $L$ & \\
  18637. \texttt{jge} $L$ & \\
  18638. \texttt{jmp} $L$ & Jump to label $L$ \\
  18639. \texttt{movq} $A$, $B$ & $A \to B$ \\
  18640. \texttt{movzbq} $A$, $B$ &
  18641. \multirow{3}{3.7in}{$A \to B$, \text{where } $A$ is a single-byte register
  18642. (e.g., \texttt{al} or \texttt{cl}), $B$ is a 8-byte register,
  18643. and the extra bytes of $B$ are set to zero.} \\
  18644. & \\
  18645. & \\
  18646. \texttt{notq} $A$ & $\sim A \to A$ \qquad (bitwise complement)\\
  18647. \texttt{orq} $A$, $B$ & $A | B \to B$ \qquad (bitwise-or)\\
  18648. \texttt{andq} $A$, $B$ & $A \& B \to B$ \qquad (bitwise-and)\\
  18649. \texttt{salq} $A$, $B$ & $B$ \texttt{<<} $A \to B$ (arithmetic shift left, where $A$ is a constant)\\
  18650. \texttt{sarq} $A$, $B$ & $B$ \texttt{>>} $A \to B$ (arithmetic shift right, where $A$ is a constant)\\
  18651. \texttt{sete} $A$ & \multirow{5}{3.7in}{If the flag matches the condition code,
  18652. then $1 \to A$, else $0 \to A$. Refer to \texttt{je} above for the
  18653. description of the condition codes. $A$ must be a single byte register
  18654. (e.g., \texttt{al} or \texttt{cl}).} \\
  18655. \texttt{setl} $A$ & \\
  18656. \texttt{setle} $A$ & \\
  18657. \texttt{setg} $A$ & \\
  18658. \texttt{setge} $A$ &
  18659. \end{tabular}
  18660. \vspace{5pt}
  18661. \caption{Quick-reference for the x86 instructions used in this book.}
  18662. \label{tab:x86-instr}
  18663. \end{table}
  18664. \if\edition\racketEd
  18665. \cleardoublepage
  18666. \section{Concrete Syntax for Intermediate Languages}
  18667. The concrete syntax of \LangAny{} is defined in
  18668. Figure~\ref{fig:Rany-concrete-syntax}.
  18669. \begin{figure}[tp]
  18670. \centering
  18671. \fbox{
  18672. \begin{minipage}{0.97\textwidth}\small
  18673. \[
  18674. \begin{array}{lcl}
  18675. \Type &::=& \gray{\key{Integer} \MID \key{Boolean}
  18676. \MID \LP\key{Vector}\;\Type\ldots\RP \MID \key{Void}} \\
  18677. &\MID& \gray{\LP\Type\ldots \; \key{->}\; \Type\RP} \MID \ANYTY{} \\
  18678. \FType &::=& \key{Integer} \MID \key{Boolean} \MID \key{Void}
  18679. \MID \LP\key{Vector}\; \ANYTY{}\ldots\RP \\
  18680. &\MID& \LP\ANYTY{}\ldots \; \key{->}\; \ANYTY{}\RP\\
  18681. \Exp &::=& \ldots \CINJECT{\Exp}{\FType}\RP \MID \CPROJECT{\Exp}{\FType}\\
  18682. &\MID& \LP\key{any-vector-length}\;\Exp\RP
  18683. \MID \LP\key{any-vector-ref}\;\Exp\;\Exp\RP \\
  18684. &\MID& \LP\key{any-vector-set!}\;\Exp\;\Exp\;\Exp\RP\\
  18685. &\MID& \LP\key{boolean?}\;\Exp\RP \MID \LP\key{integer?}\;\Exp\RP
  18686. \MID \LP\key{void?}\;\Exp\RP \\
  18687. &\MID& \LP\key{vector?}\;\Exp\RP \MID \LP\key{procedure?}\;\Exp\RP \\
  18688. \Def &::=& \gray{ \CDEF{\Var}{\LS\Var \key{:} \Type\RS\ldots}{\Type}{\Exp} } \\
  18689. \LangAnyM{} &::=& \gray{\Def\ldots \; \Exp}
  18690. \end{array}
  18691. \]
  18692. \end{minipage}
  18693. }
  18694. \caption{The concrete syntax of \LangAny{}, extending \LangLam{}
  18695. (Figure~\ref{fig:Rlam-syntax}).}
  18696. \label{fig:Rany-concrete-syntax}
  18697. \end{figure}
  18698. The concrete syntax for \LangCVar{}, \LangCIf{}, \LangCVec{} and
  18699. \LangCFun{} is defined in Figures~\ref{fig:c0-concrete-syntax},
  18700. \ref{fig:c1-concrete-syntax}, \ref{fig:c2-concrete-syntax}, and
  18701. \ref{fig:c3-concrete-syntax}, respectively.
  18702. \begin{figure}[tbp]
  18703. \fbox{
  18704. \begin{minipage}{0.96\textwidth}
  18705. \small
  18706. \[
  18707. \begin{array}{lcl}
  18708. \Atm &::=& \gray{ \Int \MID \Var \MID \itm{bool} } \\
  18709. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18710. \Exp &::=& \gray{ \Atm \MID \key{(read)} \MID \key{(-}~\Atm\key{)} \MID \key{(+}~\Atm~\Atm\key{)} } \\
  18711. &\MID& \gray{ \LP \key{not}~\Atm \RP \MID \LP \itm{cmp}~\Atm~\Atm\RP } \\
  18712. &\MID& \LP \key{allocate}~\Int~\Type \RP \\
  18713. &\MID& (\key{vector-ref}\;\Atm\;\Int) \MID (\key{vector-set!}\;\Atm\;\Int\;\Atm)\\
  18714. &\MID& \LP \key{global-value}~\Var \RP \MID \LP \key{void} \RP \\
  18715. \Stmt &::=& \gray{ \Var~\key{=}~\Exp\key{;} } \MID \LP\key{collect}~\Int \RP\\
  18716. \Tail &::= & \gray{ \key{return}~\Exp\key{;} \MID \Stmt~\Tail }
  18717. \MID \gray{ \key{goto}~\itm{label}\key{;} }\\
  18718. &\MID& \gray{ \key{if}~\LP \itm{cmp}~\Atm~\Atm \RP~ \key{goto}~\itm{label}\key{;} ~\key{else}~\key{goto}~\itm{label}\key{;} } \\
  18719. \LangCVecM{} & ::= & \gray{ (\itm{label}\key{:}~ \Tail)\ldots }
  18720. \end{array}
  18721. \]
  18722. \end{minipage}
  18723. }
  18724. \caption{The concrete syntax of the \LangCVec{} intermediate language.}
  18725. \label{fig:c2-concrete-syntax}
  18726. \end{figure}
  18727. \begin{figure}[tp]
  18728. \fbox{
  18729. \begin{minipage}{0.96\textwidth}
  18730. \small
  18731. \[
  18732. \begin{array}{lcl}
  18733. \Atm &::=& \gray{ \Int \MID \Var \MID \key{\#t} \MID \key{\#f} }
  18734. \\
  18735. \itm{cmp} &::= & \gray{ \key{eq?} \MID \key{<} } \\
  18736. \Exp &::= & \gray{ \Atm \MID \LP\key{read}\RP \MID \LP\key{-}\;\Atm\RP \MID \LP\key{+} \; \Atm\;\Atm\RP
  18737. \MID \LP\key{not}\;\Atm\RP \MID \LP\itm{cmp}\;\Atm\;\Atm\RP } \\
  18738. &\MID& \gray{ \LP\key{allocate}\,\Int\,\Type\RP
  18739. \MID \LP\key{vector-ref}\, \Atm\, \Int\RP } \\
  18740. &\MID& \gray{ \LP\key{vector-set!}\,\Atm\,\Int\,\Atm\RP \MID \LP\key{global-value} \,\itm{name}\RP \MID \LP\key{void}\RP } \\
  18741. &\MID& \LP\key{fun-ref}~\itm{label}~\Int\RP \MID \LP\key{call} \,\Atm\,\Atm\ldots\RP \\
  18742. \Stmt &::=& \gray{ \ASSIGN{\Var}{\Exp} \MID \RETURN{\Exp}
  18743. \MID \LP\key{collect} \,\itm{int}\RP }\\
  18744. \Tail &::= & \gray{\RETURN{\Exp} \MID \LP\key{seq}\;\Stmt\;\Tail\RP} \\
  18745. &\MID& \gray{\LP\key{goto}\,\itm{label}\RP
  18746. \MID \IF{\LP\itm{cmp}\, \Atm\,\Atm\RP}{\LP\key{goto}\,\itm{label}\RP}{\LP\key{goto}\,\itm{label}\RP}} \\
  18747. &\MID& \LP\key{tail-call}\,\Atm\,\Atm\ldots\RP \\
  18748. \Def &::=& \LP\key{define}\; \LP\itm{label} \; [\Var \key{:} \Type]\ldots\RP \key{:} \Type \; \LP\LP\itm{label}\,\key{.}\,\Tail\RP\ldots\RP\RP \\
  18749. \LangCFunM{} & ::= & \Def\ldots
  18750. \end{array}
  18751. \]
  18752. \end{minipage}
  18753. }
  18754. \caption{The \LangCFun{} language, extending \LangCVec{} (Figure~\ref{fig:c2-concrete-syntax}) with functions.}
  18755. \label{fig:c3-concrete-syntax}
  18756. \end{figure}
  18757. \fi % racketEd
  18758. \backmatter
  18759. \addtocontents{toc}{\vspace{11pt}}
  18760. %% \addtocontents{toc}{\vspace{11pt}}
  18761. %% \nocite{*} is a way to get all the entries in the .bib file to print in the bibliography:
  18762. \nocite{*}\let\bibname\refname
  18763. \addcontentsline{toc}{fmbm}{\refname}
  18764. \printbibliography
  18765. \printindex{authors}{Author Index}
  18766. \printindex{subject}{Subject Index}
  18767. \end{document}
  18768. % LocalWords: Nano Siek CC NC ISBN wonks wizardry Backus nanopasses
  18769. % LocalWords: dataflow nx generics autoboxing Hulman Ch CO Dybvig aa
  18770. % LocalWords: Abelson uq Felleisen Flatt Lutz vp vj Sweigart vn Matz
  18771. % LocalWords: Matthes github gcc MacOS Chez Friedman's Dipanwita fk
  18772. % LocalWords: Sarkar Dybvig's Abdulaziz Ghuloum bh IU Factora Bor qf
  18773. % LocalWords: Cameron Kuhlenschmidt Vollmer Vitousek Yuh Nystrom AST
  18774. % LocalWords: Tolmach Wollowski ASTs Aho ast struct int backquote op
  18775. % LocalWords: args neg def init UnaryOp USub func BinOp Naur BNF rkt
  18776. % LocalWords: fixnum datatype structure's arith exp stmt Num Expr tr
  18777. % LocalWords: plt PSF ref CPython cpython reynolds interp cond fx pe
  18778. % LocalWords: arg Hitchhiker's TODO nullary Lvar Lif cnd thn var sam
  18779. % LocalWords: IfExp Bool InterpLvar InterpLif InterpRVar alist jane
  18780. % LocalWords: basicstyle kate dict alists env stmts ss len lhs globl
  18781. % LocalWords: rsp rbp rax rbx rcx rdx rsi rdi movq retq callq jmp es
  18782. % LocalWords: pushq subq popq negq addq arity uniquify Cvar instr cg
  18783. % LocalWords: Seq CProgram gensym lib Fprivate Flist tmp ANF Danvy
  18784. % LocalWords: rco Flists py rhs unhandled cont immediates lstlisting
  18785. % LocalWords: numberstyle Cormen Sudoku Balakrishnan ve aka DSATUR
  18786. % LocalWords: Brelaz eu Gebremedhin Omari deletekeywords min JGS
  18787. % LocalWords: morekeywords fullflexible